Mysqli get last insert id
Get ID of The Last Inserted RecordIf we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately. Show
In the table "MyGuests", the "id" column is an AUTO_INCREMENT field: CREATE TABLE MyGuests ( The following examples are equal to the examples from the previous page (PHP Insert Data Into MySQL), except that we have added one single line of code to retrieve the ID of the last inserted record. We also echo the last inserted ID: Example (MySQLi Object-oriented)$servername = "localhost"; // Create connection $sql = "INSERT INTO MyGuests (firstname, lastname, email) if ($conn->query($sql) === TRUE) { $conn->close(); Example (MySQLi Procedural)$servername = "localhost"; // Create connection $sql = "INSERT INTO MyGuests (firstname, lastname, email) if (mysqli_query($conn, $sql)) { mysqli_close($conn); Example (PDO)$servername = "localhost"; try { $conn = null; ❮ PHP MySQLi Reference Example - Object Oriented styleAssume that the "Persons" table has an auto-generated id field. Return the id from the last query: $mysqli = new mysqli("localhost","my_user","my_password","my_db"); if ($mysqli -> connect_errno) { $mysqli -> query("INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)"); // Print auto-generated id $mysqli -> close(); Look at example of procedural style at the bottom. Definition and UsageThe mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) from the last query. SyntaxObject oriented style:Procedural style:mysqli_insert_id(connection) Parameter Values
Technical Details
Example - Procedural styleAssume that the "Persons" table has an auto-generated id field. Return the id from the last query: $con = mysqli_connect("localhost","my_user","my_password","my_db"); if (mysqli_connect_errno()) { mysqli_query($con, "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Glenn', 'Quagmire', 33)"); // Print auto-generated id mysqli_close($con); ❮ PHP MySQLi Reference How do I get the last inserted id in mysql?If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.
How do I get the last inserted record in SQL?Now, in order to get the lasted inserted record ID, we can use the following options:. SELECT @@IDENTITY. ... . SELECT SCOPE_IDENTITY() ... . SELECT IDENT_CURRENT('TableName'). What does last insert ID return?PDO::lastInsertId
Returns the identifier for the row most recently inserted into a table in the database.
How can I get last inserted record in mysql using PHP?If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.
|