Mysql Get Last Id in PHP
To retrieve the last inserted ID in a MySQL database using MySQLi in PHP, you can use the mysqli_insert_id() function (procedural) or the $conn->insert_id property (object-oriented). This is helpful when you want to get the ID of a newly inserted record, especially when the ID is auto-incremented.
1. Get Last Inserted ID Using MySQLi (Procedural Approach)
<?php// Database connection parameters$host = "localhost";$username = "root";$password = "";$dbname = "testDB"; // Database where the table is located// Create connection$conn = mysqli_connect($host, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}// SQL query to insert a new record$sql = "INSERT INTO users (name, email) VALUES ('Jane Doe', 'jane@example.com')";// Execute the queryif (mysqli_query($conn, $sql)) { // Get the last inserted ID $last_id = mysqli_insert_id($conn); echo "New record created successfully. Last inserted ID is: " . $last_id;} else { echo "Error inserting record: " . mysqli_error($conn);}// Close the connectionmysqli_close($conn);?>2. Get Last Inserted ID Using MySQLi (Object-Oriented Approach)
<?php// Database connection parameters$host = "localhost";$username = "root";$password = "";$dbname = "testDB"; // Database where the table is located// Create connection$conn = new mysqli($host, $username, $password, $dbname);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}// SQL query to insert a new record$sql = "INSERT INTO users (name, email) VALUES ('Jane Doe', 'jane@example.com')";// Execute the queryif ($conn->query($sql) === TRUE) { // Get the last inserted ID $last_id = $conn->insert_id; echo "New record created successfully. Last inserted ID is: " . $last_id;} else { echo "Error inserting record: " . $conn->error;}// Close the connection$conn->close();?>Explanation:
Database Connection:
We first connect to the database using either
mysqli_connect()(procedural) ornew mysqli()(object-oriented).
Insert Data:
We insert a new record into the
userstable. In this example, a record is inserted with the name "Jane Doe" and the email "jane@example.com".
Get Last Inserted ID:
After executing the
INSERTquery, we use:Procedural:
mysqli_insert_id($conn)to get the last inserted ID.Object-Oriented:
$conn->insert_idto retrieve the last inserted ID.
This will return the auto-incremented ID of the last inserted row.
Close the Connection:
Finally, the connection is closed using
mysqli_close()(procedural) or$conn->close()(object-oriented).
When to Use the Last Inserted ID:
The last inserted ID is typically used after inserting a new record with an auto-incremented primary key. For example, you may want to use this ID to associate it with other records in different tables or as part of a related operation.
Let me know if you need further details or assistance!