Loading... In this tutorial you will learn how to retrieve the unique ID of the last inserted row from a MySQL database table using PHP. ## How to Get the ID of Last Inserted Row In the [PHP MySQL insert](http://www.bixiaguangnian.com/manual/php7/4004.html "PHP MySQL insert") chapter you’ve learnt MySQL automatically generate an unique ID for the AUTO\_INCREMENT column each time you insert a new record or row into the table. However, there are certain situations when you need that automatically generated ID to insert it into a second table. In these situations you can use the PHP mysqli\_insert\_id() function to retrieve the most recently generated ID, as shown in the upcoming example. For this example we’ll use the same persons table that we’ve created in the [PHP MySQL create tables](http://www.bixiaguangnian.com/manual/php7/4003.html "PHP MySQL create tables") chapter, which has four columns id, first\_name, last\_name and email, where id is the primary key column and marked with AUTO\_INCREMENT flag. ```php <?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect("localhost", "root", "", "demo"); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Attempt insert query execution $sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Ron', 'Weasley', 'ronweasley@mail.com')"; if(mysqli_query($link, $sql)){ // Obtain last inserted id $last_id = mysqli_insert_id($link); echo "Records inserted successfully. Last inserted ID is: " . $last_id; } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); } // Close connection mysqli_close($link); ?> ``` Last modification:September 14, 2024 © Allow specification reprint Like 如果觉得我的文章对你有用,请随意赞赏