PHP MySQL Get Last Inserted ID

If we use INSERT or UPDATE on a table with an AUTO INCREMENT field, we can immediately get the ID of the last record that was added or changed.

The “id” column in the “student” table is an AUTO INCREMENT field:

CREATE TABLE student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(40) NOT NULL,
lastname VARCHAR(40) NOT NULL,
email VARCHAR(70)
)

The examples on this page are the same as the ones on the previous page (PHP Insert Data Into MySQL), but we’ve added one line of code to get the ID of the last record that was inserted. We also repeat the last ID that was put in:

 

Example

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “school”;

// Create connection
$link = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$link) {
die(“Connection failed: ” . mysqli_connect_error());
}

$sql = “INSERT INTO student (firstname, lastname, email)
VALUES (‘ram’, ‘lal’, ‘ramlal@example.com’)”;

if (mysqli_query($link, $sql)) {
$last_id = mysqli_insert_id($link);
echo “New record created successfully. Last inserted ID is: ” . $last_id;
} else {
echo “Error: ” . $sql . “<br>” . mysqli_error($link);
}

mysqli_close($link);
?>

People also search
Scroll to Top