PHP Example | Get the Last ID of Inserted Row in MySQL

When we are using php to insert some rows into mysql, we may have to get the last row id. This php example will show us how to get.

For example:

/* 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', '')";
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

In this example code, we will use php mysqli_insert_id() function to get the last id.