How to Get Last Insert ID in PHP MySQLi
When inserting data into a MySQL table with an auto-incrementing primary key, you often need to retrieve the newly created ID for use in subsequent queries. This article provides a straightforward guide on how to get the last inserted ID using both the object-oriented and procedural approaches of the MySQLi extension in PHP.
Object-Oriented Method
In the object-oriented approach, you can retrieve the last inserted
ID by accessing the insert_id property of your MySQLi
connection object immediately after executing the INSERT
query.
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')";
if ($mysqli->query($sql) === TRUE) {
// Retrieve the last inserted ID
$last_id = $mysqli->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
$mysqli->close();
?>Procedural Method
If you are using the procedural style of MySQLi, you can use the
mysqli_insert_id() function. This function accepts the
active database connection link as its only argument.
<?php
$conn = mysqli_connect("localhost", "username", "password", "database");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (username, email) VALUES ('jane_doe', 'jane@example.com')";
if (mysqli_query($conn, $sql)) {
// Retrieve the last inserted ID
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>Key Considerations
- Timing: You must retrieve the ID immediately after
the
INSERTquery. Performing another query on the same connection before fetching the ID may overwrite or reset the value. - Connection-Specific: The returned ID is specific to
the current database connection. It is unaffected by other users
executing
INSERTstatements simultaneously on the same table. - Table Schema: This feature only works if the table
contains an
AUTO_INCREMENTcolumn. If the table does not have an auto-incrementing field, the property or function will return0.