PHP MySQL – How To Get Last Inserted ID
It is often necessary to retrieve PHP MySQL Last Inserted ID record in a database, when inserting new records into the database using PHP.
You can use this ID as a reference in other tables or operations that are part of the application in order to make your work easier.
Throughout this article, we will be exploring a PHP solution for retrieving a MySQL database’s last inserted ID by using the PDO extension in order to retrieve the ID from that database.
We are also going to highlight some best practices that can be applied when working with ID generation and retrieval in MySQL databases so that we avoid common pitfalls.
PHP MySQL Last Inserted ID
An INSERT or UPDATE operation on a table, which has an AUTO_INCREMENT field, will allow us to get the ID of the last record that has been inserted or updated immediately once the operation has been performed.
The “id” column in the table “Users” is a field that is an AUTO_INCREMENT field.
CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), age INT, gender VARCHAR(50), reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )
As in the examples from the previous page (PHP Insert Data Into MySQL), the following examples are identical to those from the previous page except that we have added one single line of code to retrieve the ID of the previous record that has been inserted.
Our code also echo’s the last ID that has been inserted.
Below is an example using MySQLi’s Object-Oriented method:
Example (MySQLi’s Object-Oriented):
Example (MySQLi’s Procedural):
- The code starts by defining the variables $servername, $username, $password, and $dbname, which are used to specify database connection details.
- A try-catch block is used to handle any exceptions that may occur during the database connection and query execution. Inside the try block, the PDO constructor is used to create a new database connection. The connection string is created by combining the servername, dbname, username, and password variables.
- The PDO::setAttribute() method is called on the $conn object to set the error mode to ERRMODE_EXCEPTION, which means that PDO will throw an exception if an error occurs.
- A SQL INSERT statement is defined in the $sql variable. The statement inserts a new record into the “Users” table with the values ‘Matt‘ for firstname, ‘LeBlanc‘ for lastname, ‘[email protected]‘ for email, 55 for age, and ‘Male‘ for gender.
- The $conn->exec() method is called to execute the INSERT statement. Because the statement does not return any results, the exec() method is used instead of query().
- The $conn->lastInsertId() method is called to retrieve the ID of the last inserted record.
- The ID is stored in the $last_id variable.
- If the INSERT statement is executed successfully, the message “New record added successfully. Last inserted ID is: ” is displayed along with the value of $last_id.
- If an exception is caught, the catch block is executed. The catch block displays an error message that includes the SQL query and the error message returned by PDO.
- Finally, the $conn variable is set to null to close the database connection.