How we can find last insert id in table?

Last updated 2 years, 4 months ago | 461 views 75     5

Tags:- PHP PHP-MySQL

MySQL | Find last insert id in the table

By using the MySQL function mysqli_insert_id() we can retrieve the last inserted id in the database table.

 
<?php
$con = mysqli_connect("localhost","user_name","user_password","db_name");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}

mysqli_query($con, "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)");

// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);

mysqli_close($con);
?>