How to get id of row i just inserted php / mysql

Possible duplicate:
PHP: how to get the last inserted table id?

I am writing a function to add data to a database, but then I want to immediately use this entry in my code.

I know I can query: SELECT id FROM table ORDER BY id DESC

But I am wondering if there is a more direct way to do this.

+6
php mysql insert
source share
4 answers

This mainly depends on the interface you use to access MySQL.

If you use PDO (recommended), you should use PDO::lastInsertId() : http://us.php.net/manual/en/pdo.lastinsertid.php

If you are using MySQL, you must use mysql_insert_id() http://php.net/manual/en/function.mysql-insert-id.php

If you are using MySQLi, you should use mysqli_insert_id() : http://us.php.net/manual/en/mysqli.insert-id.php

Just call whichever function is right right after the completion of INSERT.

It is important to note that you probably do not want to retrieve the id from the database using SELECT, because if you have several authors, you can get the identifier that some other thread inserted. In the best case, you will work with incorrect data, and in the worst case, you may have serious security problems and / or corruption.

+13
source share

With PHP, you can use mysql_insert_id () .

+7
source share
 select last_insert_id(); 

Doc

+3
source share

Perhaps this could help:

Get a unique identifier for the last inserted row

If you insert a record into a table that contains an AUTO_INCREMENT column, you can get the value stored in that column by calling mysql_insert_id ().

+2
source share

All Articles