PHP MySQL Last Inserted ID



In this source code example, we will see how to mysqli_insert_id() function to retrieve the most recently generated ID in PHP using MySQLi.

PHP MySQL Last Inserted ID

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */

$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysqli = new mysqli($host, $username, $password,  $db_name);
 
// Check connection
if($mysqli === false){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}
 
// Attempt insert query execution
$sql = "INSERT INTO students (first_name, last_name, email) VALUES ('Ram', 'jadhav', 'ram123@mail.com')";
if(mysqli_query($mysqli, $sql)){
    // Obtain last inserted id
    $last_id = mysqli_insert_id($mysqli);
    echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($mysqli);
}
 
// Close connection
$mysqli->close();
?>
Let's understand the above PHP script.

The mysqli_connect() function opens a new connection to the MySQL server:

$host= "localhost";
$username= "root";
$password = "";

$db_name = "demo_db";

$mysqli = new mysqli($host, $username, $password,  $db_name);
SQL query for inserting data into a database table:

$sql = "INSERT INTO students (first_name, last_name, email) VALUES ('Ram', 'jadhav', 'ram123@mail.com')";
The  mysqli_insert_id() function to retrieve the most recently generated ID in PHP using MySQLi:
 $last_id = mysqli_insert_id($mysqli);
Closing MySQL server connection:
// Close connection
$mysqli->close();

Comments