I created a new mySql table and I need the first field to be an index and a key.
I'm not sure I got the terminology right but I simply need that field to automatically increment by 1 with each insert.
So I defined that field as an index and gave it the auto_increment attribute.
Now I try to insert the first row like this:
$wpdb->insert('wp_branches', array(user_id=>$user_id, branchName=>$bname));
The index/key field branchId is missing from this query because I'm counting on the db to automatically give it the value 1 since it's the first insert, and then increment it with every additional insert.
For some reason the row isn't being inserted and db is left empty.
What am I doing wrong?
try like so:
$sql = $wpdb->prepare(
"INSERT INTO `wp_branches` (`user_id`,`branchName`) values (%d,%s)",
$user_id, $bname);
$wpdb->query($sql);
this will protect you against "injections" too.
modified so:
$wpdb->insert('wp_branches', array('user_id' => $user_id, 'branchName' => $bname));
Related
I am trying to insert ROW NUMBER inside table through controller but failed,
I have tried something like this but showing error,
$data = array(
'name'=>$request->name, 'email'=>$request->email, 'password'=>$password, 'status'=>1, 'user_id' =>ROW_NUMBER()
);
I just want to insert ROW NUMBER of table inside user_id.
Also, if not possible can we insert unique serial number inside user_id
Please help me out.
Each row has a column with name 'id' that is unique and Auto increment.
You can pass 'id' value to 'user_id' like below: (but it's not a good idea)
Why it is a bad idea?
Because when you delete your last row (assume id is 5) your next record 'id' is 6 but the user_id that will you retrieve with code below will be 5.
So, use the alternate option that I will give you in the following.
$last_user = User::orderBy('created_at', 'desc')->first();
$new_user = new User;
...
$new_user->user_id = $last_user->id + 1 ;
$new_user->save();
I figure it out from comments that you need a unique id and this your idea to solve this problem.
I have a better idea and hope that will help you.
you can use uniqid() method.
$new_user = new User;
...
$new_user->user_id = uniqid();
$new_user->save();
On my db-server i am inserting data in a table having a auto increment field say 'id'. Now i want to use the value of this last inserted 'id' in subsequent steps. I can use this:-
select * from table_name order by id desc limit 1;
But the problem here is, it is a server and many more insertions could be happening and there could be a case where i try to retrieve the data with the query i mentioned and get a different id ie. between my insert and select there could be some other insert and i wont get the value i inserted. Any way in which this could be addressed.?
Thanks in advance.
Use this
mysql_insert_id(&mysql);
as its basic structure are
mysql_insert_id ([ resource $link_identifier = NULL ] )
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
or in mysql use
SELECT LAST_INSERT_ID();
here is the ref links
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://php.net/manual/en/function.mysql-insert-id.php
try this
SELECT LAST_INSERT_ID(colid) From tablename;
heres the Link
call LAST_INSERT_ID() function immediately after insertion and save id somewhere.
Use this mysql_insert_id()
It returns the AUTO_INCREMENT ID generated from the previous INSERT operation.
This function returns 0 if the previous operation does not generate an AUTO_INCREMENT ID, or FALSE on MySQL connection failure.
you can get the id if you call LAST_INSERT_ID() function immediately after insertion and then you can use it.
For any last inserted record will be get through mysql_insert_id()
If your table contain any AUTO_INCREMENT column it will return that Value.
mysql_query("INSERT INTO test(emsg,etime) values ('inserted',now())");
printf("Last inserted record has id %d\n", mysql_insert_id());
$last_id=mysql_insert_id();
echo $last_id;
?>
I can insert 2 pets into a table, and get their lastInsertId() for further processing one at a time (2 queries). I am wondering if there is a way to get two lastInsertIds() and assign them to variables if I am inserting 2 rows in 1 query:
$query = "INSERT INTO pets (pet_name) VALUES (':coco'),(':jojo')";
$pet_insert = $dbh->prepare($query);
$pet_insert->execute(array(':coco' => $coco,':jojo' => $jojo));
$New_PetID = $dbh->lastInsertId();
Is it possible to get the lastInsertId() for coco and for jojo? So something like:
$New_PetID1 = $dbh->lastInsertId();//coco
$New_PetID2 = $dbh->lastInsertId();//jojo
This will give the same ID, any way to get the 2 IDs? Just for reference, this is in a try block.
It's not possible. If you need generated ids for both rows - you need to perform 2 separated INSERT
Important If you insert multiple rows using a single INSERT statement,
LAST_INSERT_ID() returns the value generated for the first inserted
row only. The reason for this is to make it possible to reproduce
easily the same INSERT statement against some other server.
http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id
you can add 1 to last insert id to achieve the real last record id.and if you insert more than 2 record just add rowCount - 1 to last_insert_id.
With innodb_autoinc_lock_mode set to 0 (“traditional”) or 1 (“consecutive”), the auto-increment values generated by any given statement will be consecutive, without gaps, because the table-level AUTO-INC lock is held until the end of the statement, and only one such statement can execute at a time.
and
The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.
for more info read this document http://dev.mysql.com/doc/refman/5.1/en/innodb-auto-increment-handling.html
Please, please avoid the type of solutions given by Bruce. The auto increment value can be set to be different than 1. For instance in case of master to master replication. A little while back a host where one of our applications runs on changed their db setup. I happened to notice -purely by coincidence- that all of a sudden the id's incremented with two instead of one. Would we have had any code like this it could have caused us serious problems.
The documentation states: Returns the ID of the last inserted row or sequence value
You will need to perform two queries to get the id for each inserted row.
I tried to assume that is is not possible until I tried it on my own and figured that IT IS POSSIBLE.
After each execute, add the lastInsertId() and assign a key.
For my example:
// First query
$sql = "INSERT INTO users
(username, email)
values
(:username, :email)";
$sth = $this->db->prepare($sql);
$sth->bindParam(':username', $data['username'], PDO::PARAM_STR);
$sth->bindParam(':email', $data['email'], PDO::PARAM_STR);
// Second Query
$sql2 = "INSERT INTO users
(username, email)
values
(:username, :email)";
$sth2 = $this->db->prepare($sql2);
$sth2->bindParam(':username', $data['username'], PDO::PARAM_STR);
$sth2->bindParam(':email', $data['email'], PDO::PARAM_STR);
// Start trans
$this->db->beginTransaction();
// Execute the two queries
$sth->execute();
$last['ux1'] = $this->db->lastInsertId(); // <---- FIRST KEY
$sth2->execute();
$last['ux2'] = $this->db->lastInsertId(); // <---- SECOND KEY
// Commit
$this->db->commit();
And I was able to retrieve the two last inserted ids
Array (
[create] => Array
(
[ux1] => 117
[ux2] => 118
)
)
I hope this will help others who are seeking the right answer.
Well, since 1000 inserts is a bit longer than 1 insert, the issue of topic is still interesting. Possible workaround would be to make 2 queries. The first one is to insert 1000 rows and the second one is to select them if there is something unique in those inserted rows.
For example with pets:
INSERT INTO pets ( name ) VALUES ( 'coco', 'jojo' );
SELECT id FROM pets WHERE name IN ( 'coco', 'jojo' );
This could give benefit only for big data sets.
I used the array in the first statement and in the second add if condition. So If insert record get its last id then make the second statement. If insert the second array get its last id then repeat the second statement
for ($count=0; $count < count($_POST["laptop_ram_capacity"]); $count++) {
$stmt = $con->prepare('INSERT INTO `ram`
(ram_capacity_id, ram_type_id, ram_bus_id, ram_brand_id, ram_module_id)
VALUES (?,?,?,?,?)');
//excute query//
$stmt->execute(array(
$_POST['laptop_ram_capacity'][$count],
$_POST["laptop_ram_type"][$count],
$_POST["laptop_ram_bus"][$count],
$_POST["laptop_ram_brand"][$count],
$_POST["laptop_ram_module"][$count]
));
//fetsh the data//
$rows = $stmt->rowCount();
// i add the below statment in if condition to repeat the insert and pass the repeated of the last statement//
if ($rows > 0) {
$LASTRAM_ID = $con->lastInsertId();
$stmt = $con->prepare('INSERT INTO `ram_devicedesc_rel`
(ram_id, Parent_device_description_id)
VALUES (?,?)');
//excute query//
$stmt->execute(array(
$LASTRAM_ID,
$LASTdevicedesc_ID
));
//fetsh the data//
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
you can use 'multi_query()'
add all the query into one variable like :
'$sql1 = "first insert";'
'$sql2 = "second insert";'
'$sql3 = "third insert";' and so on...
take the count of number of inserts your gonna make.
now execute all the '$sql' queries using 'multi_query()'.
get the last insert id.
now all you have to do is '$rowno = $lastinsertid - $countofinserts'.
so basically you will get a number.
add 1 to it and from the resulting number to the lastinsertid are the insert id's of the insert queries you ran
It is possible! All you need to do is call the PDO lastInsertId() method. This will return the first inserted id when doing multiple or bulk INSERT. Next we need to perform a simple addition subtraction operation with the number of rows affected by the last INSERT statement.
$firstInsertedId = $this->lastInsertId();
$InsertedIds = range($firstInsertedId, ($firstInsertedId + ($stmt->rowCount() - 1)) );
print_r($InsertedIds);
I am currently using MySQL. I have a table that has an auto_increment 'id' field, and an 'imgname' field containing a string that is the file name of an image.
I need to generate the 'imgname' value using the auto_increment value that is create by an INSERT INTO statement. The problem is, I don't know this value until I can use mysql_insert_id, AFTER the insert query has run. I would like to know if it's possible to access this value DURING the insert query somehow and then use it to generate my string in the query statement.
Thanks in advance.
I would keep the id and imgname independent of each other and combine the two on SELECT when needed. If the need is frequent enough, create a view.
Have a look at LAST_INSERT_ID() function. If performance is not an issue, INSERT regularly, and then UPDATE using LAST_INSERT_ID(), like:
UPDATE table SET name = CONCAT(name, "-", LAST_INSERT_ID()) WHERE id = LAST_INSERT_ID();
I am inserting a row with a char column for a hash based on (among other things) the row's auto id.
I know I can insert it, fetch the insert_id, calculate the hash, and update it.
Does anyone know of a way to do this in a single query? You would need the rows insert_id at the time of insert. Is that completely impossible, or is there something like current_insert_id()...
Thanks!
No, there's no function in MySQL that gives you the current_insert_id().
The only way to get a generated ID value from an AUTO_INCREMENT field in MySQL is to do the INSERT and then call last_insert_id(). So your plan of doing a separate UPDATE to calculate the hash is probably what you'll have to do.
I can think of two other alternatives:
Generate the unique value yourself before the INSERT with some other mechanism besides the AUTO_INCREMENT. For example, see the UUID() function.
SET #id = SELECT UUID();
INSERT INTO MyTable (id, hash) VALUES (#id, hash(#id...));
Don't include the ID in your hash calculation.
There's no way that I know of to do it in MySQL in one query, but you could do something like this in your server-side scripting language of choice:
<?php
$query = mysql_query("SHOW TABLE STATUS LIKE 'MyTable'");
$row = mysql_fetch_assoc($query);
$next_id = $row['Auto_increment'];
?>
...which gives you the id to incorporate in your SQL.
EDIT: I also found this answer which may be helpful.
You can query the next-to-be-used value from the information_schema.TABLES table, the AUTO_INCREMENT column there. (You might be setting yourself up for a race condition?)
When I do inserts I do something like this:
INSERT INTO table (col1,col2) VALUES (data1,data2);SELECT LAST_INSERT_ID()
and just run the query like I was fetching data. In VB.NET the syntax is (assuming you have the MySql.Data.MySqlClient .dll):
Dim sql As String = "[sql string above]"
Dim dr As MySqlDataReader = YourRetrieveDataFunction(sql)
dr.Read()
yourObjectInstance.ID = dr(0)
dr.Close
It's technically two queries, but only one hit on the database :)