Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/MySQL Get autoincremented value after insert

Tags:

In my mysql table i have an id-column which is set to autoincrement.

then i do queries like this:

INSERT INTO table (id, foo) VALUES ('', 'bar')

how can i then safely find out which id was generated with this insert?

if i just query the last id this might not be safe, since another insert could have happened in the meantime, right?

like image 493
clamp Avatar asked Jan 02 '12 14:01

clamp


People also ask

How can I get auto increment value after INSERT?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

How can I get last inserted record in MySQL using PHP?

$last_id=mysql_query("SELECT id FROM `table_name` ORDER BY id DESC LIMIT 0 , 1" ); $row=mysql_fetch_assoc($last_id); echo $row['id']; Replace id by your id field name in database and table_name by your table name.

How do I get the last row inserted id in MySQL?

MySQL LAST_INSERT_ID() Function The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How can I get auto increment ID?

To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment. Inserting records into the table. To display all the records.


1 Answers

There's a PHP and also a MySQL function for this: mysqli_insert_id() and PDO::lastInsertId().

http://php.net/manual/en/function.mysql-insert-id.php

like image 92
sascha Avatar answered Sep 23 '22 08:09

sascha