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;
?>
Related
Let's say I am doing a MySQL INSERT into one of my tables and the table has the column item_id which is set to autoincrement and primary key.
How do I get the query to output the value of the newly generated primary key item_id in the same query?
Currently I am running a second query to retrieve the id but this hardly seems like good practice considering this might produce the wrong result...
If this is not possible then what is the best practice to ensure I retrieve the correct id?
You need to use the LAST_INSERT_ID() function: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Eg:
INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();
This will get you back the PRIMARY KEY value of the last row that you inserted:
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.
So the value returned by LAST_INSERT_ID() is per user and is unaffected by other queries that might be running on the server from other users.
BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.
I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.
The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.
IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.
From the LAST_INSERT_ID() documentation:
The ID that was generated is maintained in the server on a per-connection basis
That is if you have two separate requests to the script simultaneously they won't affect each others' LAST_INSERT_ID() (unless you're using a persistent connection perhaps).
You will receive these parameters on your query result:
"fieldCount": 0,
"affectedRows": 1,
"insertId": 66,
"serverStatus": 2,
"warningCount": 1,
"message": "",
"protocol41": true,
"changedRows": 0
The insertId is exactly what you need.
(NodeJS-mySql)
Here what you are looking for !!!
select LAST_INSERT_ID()
This is the best alternative of SCOPE_IDENTITY() function being used in SQL Server.
You also need to keep in mind that this will only work if Last_INSERT_ID() is fired following by your Insert query.
That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.
For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?
If in python using pymysql, from the cursor you can use cursor.lastrowid.
It is a documented extension in PEP-249 DB API standard, and also works with other Python MySQL implementations.
You need to use the LAST_INSERT_ID() function with transaction:
START TRANSACTION;
INSERT INTO dog (name, created_by, updated_by) VALUES ('name', 'migration', 'migration');
SELECT LAST_INSERT_ID();
COMMIT;
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
This function will be return last inserted primary key in table.
Simply use:
$last_id = mysqli_insert_id($conn);
If you need the value before insert a row:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
You can use this in a insert:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( concat (convert ( now() , char), ' ', getAutoincrementalNextval ('document') ) ),
'Title',
'Body'
);
If you are using PHP: On a PDO object you can simple invoke the
lastInsertId method after your insert.
Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();
i used return $this->db->insert_id(); for Codeigniter
Do this:
$idc = DB::table('tb_clients')->insertGetId([
'ide' => $ide,
'nome' => $nome,
'email' => $email
]);
on $idc you will get the last id
I just want to share my approach to this in PHP, some of you may found it not an efficient way but this is a 100 better than other available options.
generate a random key and insert it into the table creating a new row.
then you can use that key to retrieve the primary key.
use the update to add data and do other stuff.
doing this way helps to secure a row and have the correct primary key.
I really don't recommend this unless you don't have any other options.
Let's say I am doing a MySQL INSERT into one of my tables and the table has the column item_id which is set to autoincrement and primary key.
How do I get the query to output the value of the newly generated primary key item_id in the same query?
Currently I am running a second query to retrieve the id but this hardly seems like good practice considering this might produce the wrong result...
If this is not possible then what is the best practice to ensure I retrieve the correct id?
You need to use the LAST_INSERT_ID() function: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Eg:
INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();
This will get you back the PRIMARY KEY value of the last row that you inserted:
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.
So the value returned by LAST_INSERT_ID() is per user and is unaffected by other queries that might be running on the server from other users.
BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.
I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.
The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.
IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.
From the LAST_INSERT_ID() documentation:
The ID that was generated is maintained in the server on a per-connection basis
That is if you have two separate requests to the script simultaneously they won't affect each others' LAST_INSERT_ID() (unless you're using a persistent connection perhaps).
You will receive these parameters on your query result:
"fieldCount": 0,
"affectedRows": 1,
"insertId": 66,
"serverStatus": 2,
"warningCount": 1,
"message": "",
"protocol41": true,
"changedRows": 0
The insertId is exactly what you need.
(NodeJS-mySql)
Here what you are looking for !!!
select LAST_INSERT_ID()
This is the best alternative of SCOPE_IDENTITY() function being used in SQL Server.
You also need to keep in mind that this will only work if Last_INSERT_ID() is fired following by your Insert query.
That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.
For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?
If in python using pymysql, from the cursor you can use cursor.lastrowid.
It is a documented extension in PEP-249 DB API standard, and also works with other Python MySQL implementations.
You need to use the LAST_INSERT_ID() function with transaction:
START TRANSACTION;
INSERT INTO dog (name, created_by, updated_by) VALUES ('name', 'migration', 'migration');
SELECT LAST_INSERT_ID();
COMMIT;
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
This function will be return last inserted primary key in table.
Simply use:
$last_id = mysqli_insert_id($conn);
If you need the value before insert a row:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
You can use this in a insert:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( concat (convert ( now() , char), ' ', getAutoincrementalNextval ('document') ) ),
'Title',
'Body'
);
If you are using PHP: On a PDO object you can simple invoke the
lastInsertId method after your insert.
Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();
i used return $this->db->insert_id(); for Codeigniter
Do this:
$idc = DB::table('tb_clients')->insertGetId([
'ide' => $ide,
'nome' => $nome,
'email' => $email
]);
on $idc you will get the last id
I just want to share my approach to this in PHP, some of you may found it not an efficient way but this is a 100 better than other available options.
generate a random key and insert it into the table creating a new row.
then you can use that key to retrieve the primary key.
use the update to add data and do other stuff.
doing this way helps to secure a row and have the correct primary key.
I really don't recommend this unless you don't have any other options.
Let's say I am doing a MySQL INSERT into one of my tables and the table has the column item_id which is set to autoincrement and primary key.
How do I get the query to output the value of the newly generated primary key item_id in the same query?
Currently I am running a second query to retrieve the id but this hardly seems like good practice considering this might produce the wrong result...
If this is not possible then what is the best practice to ensure I retrieve the correct id?
You need to use the LAST_INSERT_ID() function: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Eg:
INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();
This will get you back the PRIMARY KEY value of the last row that you inserted:
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.
So the value returned by LAST_INSERT_ID() is per user and is unaffected by other queries that might be running on the server from other users.
BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.
I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.
The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.
IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.
From the LAST_INSERT_ID() documentation:
The ID that was generated is maintained in the server on a per-connection basis
That is if you have two separate requests to the script simultaneously they won't affect each others' LAST_INSERT_ID() (unless you're using a persistent connection perhaps).
You will receive these parameters on your query result:
"fieldCount": 0,
"affectedRows": 1,
"insertId": 66,
"serverStatus": 2,
"warningCount": 1,
"message": "",
"protocol41": true,
"changedRows": 0
The insertId is exactly what you need.
(NodeJS-mySql)
Here what you are looking for !!!
select LAST_INSERT_ID()
This is the best alternative of SCOPE_IDENTITY() function being used in SQL Server.
You also need to keep in mind that this will only work if Last_INSERT_ID() is fired following by your Insert query.
That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.
For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?
If in python using pymysql, from the cursor you can use cursor.lastrowid.
It is a documented extension in PEP-249 DB API standard, and also works with other Python MySQL implementations.
You need to use the LAST_INSERT_ID() function with transaction:
START TRANSACTION;
INSERT INTO dog (name, created_by, updated_by) VALUES ('name', 'migration', 'migration');
SELECT LAST_INSERT_ID();
COMMIT;
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
This function will be return last inserted primary key in table.
Simply use:
$last_id = mysqli_insert_id($conn);
If you need the value before insert a row:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
You can use this in a insert:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( concat (convert ( now() , char), ' ', getAutoincrementalNextval ('document') ) ),
'Title',
'Body'
);
If you are using PHP: On a PDO object you can simple invoke the
lastInsertId method after your insert.
Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();
i used return $this->db->insert_id(); for Codeigniter
Do this:
$idc = DB::table('tb_clients')->insertGetId([
'ide' => $ide,
'nome' => $nome,
'email' => $email
]);
on $idc you will get the last id
I just want to share my approach to this in PHP, some of you may found it not an efficient way but this is a 100 better than other available options.
generate a random key and insert it into the table creating a new row.
then you can use that key to retrieve the primary key.
use the update to add data and do other stuff.
doing this way helps to secure a row and have the correct primary key.
I really don't recommend this unless you don't have any other options.
Let's say I am doing a MySQL INSERT into one of my tables and the table has the column item_id which is set to autoincrement and primary key.
How do I get the query to output the value of the newly generated primary key item_id in the same query?
Currently I am running a second query to retrieve the id but this hardly seems like good practice considering this might produce the wrong result...
If this is not possible then what is the best practice to ensure I retrieve the correct id?
You need to use the LAST_INSERT_ID() function: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Eg:
INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();
This will get you back the PRIMARY KEY value of the last row that you inserted:
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.
So the value returned by LAST_INSERT_ID() is per user and is unaffected by other queries that might be running on the server from other users.
BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.
I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.
The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.
IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.
From the LAST_INSERT_ID() documentation:
The ID that was generated is maintained in the server on a per-connection basis
That is if you have two separate requests to the script simultaneously they won't affect each others' LAST_INSERT_ID() (unless you're using a persistent connection perhaps).
You will receive these parameters on your query result:
"fieldCount": 0,
"affectedRows": 1,
"insertId": 66,
"serverStatus": 2,
"warningCount": 1,
"message": "",
"protocol41": true,
"changedRows": 0
The insertId is exactly what you need.
(NodeJS-mySql)
Here what you are looking for !!!
select LAST_INSERT_ID()
This is the best alternative of SCOPE_IDENTITY() function being used in SQL Server.
You also need to keep in mind that this will only work if Last_INSERT_ID() is fired following by your Insert query.
That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.
For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?
If in python using pymysql, from the cursor you can use cursor.lastrowid.
It is a documented extension in PEP-249 DB API standard, and also works with other Python MySQL implementations.
You need to use the LAST_INSERT_ID() function with transaction:
START TRANSACTION;
INSERT INTO dog (name, created_by, updated_by) VALUES ('name', 'migration', 'migration');
SELECT LAST_INSERT_ID();
COMMIT;
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
This function will be return last inserted primary key in table.
Simply use:
$last_id = mysqli_insert_id($conn);
If you need the value before insert a row:
CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
RETURNS BIGINT
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE Value BIGINT;
SELECT
AUTO_INCREMENT INTO Value
FROM
information_schema.tables
WHERE
table_name = TableName AND
table_schema = DATABASE();
RETURN Value;
END
You can use this in a insert:
INSERT INTO
document (Code, Title, Body)
VALUES (
sha1( concat (convert ( now() , char), ' ', getAutoincrementalNextval ('document') ) ),
'Title',
'Body'
);
If you are using PHP: On a PDO object you can simple invoke the
lastInsertId method after your insert.
Otherwise with a LAST_INSERT_ID you can get the value like this: SELECT LAST_INSERT_ID();
i used return $this->db->insert_id(); for Codeigniter
Do this:
$idc = DB::table('tb_clients')->insertGetId([
'ide' => $ide,
'nome' => $nome,
'email' => $email
]);
on $idc you will get the last id
I just want to share my approach to this in PHP, some of you may found it not an efficient way but this is a 100 better than other available options.
generate a random key and insert it into the table creating a new row.
then you can use that key to retrieve the primary key.
use the update to add data and do other stuff.
doing this way helps to secure a row and have the correct primary key.
I really don't recommend this unless you don't have any other options.
How can I edit the latest row in the database. I only know it's the last one. I don't know its id.
I don't know which language you are working with, in PHP's mySQL functions you can use
mysql_insert_id()
there are similar function in every other mySQL client library I know of.
Also, there is a native mySQL function!
LAST_INSERT_ID() (with no argument)
returns the first automatically
generated value that was set for an
AUTO_INCREMENT column by the most
recently executed INSERT statement to
affect such a column. For example,
after inserting a row that generates
an AUTO_INCREMENT value, you can get
the value like this:
mysql> SELECT LAST_INSERT_ID();
-> 195
Of course, a primary key with AUTO_INCREMENT is required for these functions to work.
For a table with an auto_increment id field:
UPDATE tbl SET col1 = 'val1' WHERE id = MAX(id);
If it's a row that has been inserted in your script (the same script from which you want to update it) and there is an auto_increment column on your table, you can get that auto_increment value, using functions such as those, for PHP :
mysql_insert_id
mysqli_insert_id
PDO::lastInsertId
There should be an equivalent for probably any language you can possibly be using for your application.
If your are trying to do an update from another script than the one in which you did the insert, and still have an auto_increment column, the best way will probably be to update the row that has the biggest value for that column :
update your_table
set your_column = ...
where id = max(id)
Or, in two steps (not sure it'll work in one) :
select max(id) as id from your_table
update your_table set your_column = ... where id = [what you got with thr first query]
You can also use UPDATE table SET ... WHERE id=LAST_INSERT_ID() (supposing the last insert was on the table you want to query).
I would not use TWO steps to find the last insert ID simply because a new record could be added in the mean time.
Depending on your version, you should be able to call $handle->last_id(); or $handle->{mysql_insertid};
Chris