Welcome to this comprehensive guide on using PHP MySQLi to get the last inserted ID! In this lesson, we'll learn how to fetch the ID of the most recently inserted record, making it easier to manage your database operations. π Note: This tutorial is designed for beginners and intermediates, so we'll be explaining the concepts from the ground up.
When you insert a new record into a MySQL database, the database assigns a unique ID to that record. The LAST_INSERT_ID() function in MySQL allows you to retrieve the ID of the most recently inserted row.
Before we dive into the PHP code, make sure you have the following prerequisites:
First, we'll establish a connection to our MySQL database using the PHP MySQLi extension.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>Replace username, password, and database_name with your actual credentials.
Next, let's insert a new record into our table. We'll also store the last inserted ID for later use.
// SQL query to insert a new record
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
// Execute the query
if ($conn->query($sql) === TRUE) {
// Get the last inserted ID
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID: $last_id";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}Make sure to replace table_name, column1, column2, value1, and value2 with your actual table name, columns, and values.
Now that we've inserted a new record, let's fetch the last inserted ID using the $conn->insert_id property.
// Close the database connection
$conn->close();
// Example usage of last inserted ID
echo "The last inserted ID was: " . $last_id;And that's it! You've now learned how to use PHP MySQLi to get the last inserted ID in a MySQL database. β
Which PHP MySQLi function is used to retrieve the last inserted ID?