Last Inserted ID Using PHP

Last Inserted ID Using PHP

In the PHP MySQL insert chapter you’ve learnt MySQL automatically generate an unique ID for the AUTO_INCREMENT column each time you insert a new record or row into the table. However, there are certain situations when you need that automatically generated ID to insert it into a second table. In these situations you can use the PHP mysqli_insert_id() function to retrieve the most recently generated ID, as shown in the upcoming example.

<?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();

?>

Leave a Reply