PHP - SPLessons

PHP Get ID of Last Inserted Record

Home > Lesson > Chapter 35
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Get ID of Last Inserted Record

PHP Get ID of Last Inserted Record

shape Description

If UPDATE or INSERT are applied on a table that has the field AUTO_INCREMENT,then ID of lastly updated/inserted record can be obtained right away. Suppose, the table "Student" has the column "id" which has a field AUTO_INCREMENT field [php] CREATE TABLE users2 ( ID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, Username varchar(20), Password varchar(20), First varchar(20), Last varchar(20) )[/php]

shape Example

(MySQLi Object-oriented) [php] <!DOCTYPE html> <html> <body> <?php $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "accounts"; // Create connection $connection = new mysqli($servername, $username, $password, $dbname); // Check connection if ($connection->connect_error) { die("Connection failed: " . $connection->connect_error); } //Inserting record $sql = "INSERT INTO users2 (Username, Password, First, Last) VALUES ('Adam', 'password', 'Adam' , 'Gilchrist')"; if ($connection->query($sql) === TRUE) { //Finding id of lastly inserted record $last_id = $connection->insert_id; echo "New record created successfully. Last inserted ID is: " . $last_id; } else { echo "Error: " . $sql . "<br>" . $connection->error; } $connection->close(); ?> </body> </html> [/php] After inserting the record again, the output will be as follows. So, the lastly inserted record ID will be 2. MySQLi Procedural [php] <!DOCTYPE html> <html> <body> <?php $servername = "localhost"; $username = "root"; $password = "password"; $dbname = "accounts"; // Create connection $connection = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } //Inserting record $sql = "INSERT INTO users2 (Username, Password, First, Last) VALUES ('Adam', 'password', 'Adam' , 'Gilchrist')"; if (mysqli_query($connection, $sql)) { //Getting id of lastly inserted record $last_id = mysqli_insert_id($connection); echo "New record created successfully. Last inserted ID is: " . $last_id; } else { echo "Error: " . $sql . "<br>" . mysqli_error($connection); } mysqli_close($connection); ?> </body> </html> [/php]

Summary

shape Key Points

"PHP Get ID of Last Inserted Record" illustrates the following important points.
  • The id of last inserted record is found out by using sql query and php $lastid.