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?
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.
$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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With