Get Last insert id from MySQL Table with PHP

There is the various approach of selecting the last insert id from the MySQL table.

  • Select a single row from the table in descending order and store the id.
  • Select Maximum value.
  • The following query gives you the next AUTO_INCREMENT value from the selected table which you can use to get the last id.

If your currently AUTO_INCREMENT column last value is 8 and when you execute the above query on the Table this will return 9.

In PHP there is an inbuilt method that simply returns the last insert id according to the previous insert query.

Get Last insert id from MySQL Table with PHP


  1. mysqli_insert_id()
  2. Example
  3. Conclusion

1. mysqli_insert_id()

It returns the last AUTO_INCREMENT column value of the previously successfully executed insert query.

Syntax –


It returns 0 when the table doesn’t have any AUTO_INCREMENT column.

2. Example

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
   die("Connection failed: " . mysqli_connect_error());

// Insert query 
$query = "insert into users(username,fname,lname) values('sonarika','Sonarika','Bhadoria')"; 


   // Get last insert id 
   $lastid = mysqli_insert_id($con); 

   echo "last id : ".$lastid; 


last id : 4

3. Conclusion

Now you know how to get the last insert id value using an inbuilt method. But you need to call it immediately after the insert query because it works according to the last query.

If you are maintaining the id column manually and not using AUTO_INCREMENT in the MySQL table then it is not a good choice you can go with other options.

You can learn more about the mysqli_insert_id() method from here.

If you found this tutorial helpful then don't forget to share.