Get ID of The Last Inserted Record

You can simply get the last insert record id by using php insert_id statement.

Example Code:

[php]<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)";

if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>[/php]

Code Explanation:

In the above code, we have just added one additional statement to get last inserted id.

if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
}

In the if statement, once we confirm the connection, is true, on the next line we are asking php to check the last insert_id. The php script will check the statement and return the value in the echo statement.

Related Posts

Leave a Reply