MySQL Get Last ID

PHP MySQL Get Last Inserted ID

When you execute an INSERT statement on a table that has an AUTO_INCREMENT column (like our id column), MySQL automatically generates a unique ID for that new record.

Very often, you need to know what that new ID is so you can use it in other parts of your script (like associating a user with their newly created profile).


Getting the ID

You can retrieve the last inserted ID immediately after your mysqli_query() executes by using the mysqli_insert_id() function.

Get Last ID Example

<?php
$servername = "localhost";
$username = "root";
$password = "your_password";
$dbname = "myDB";

$conn = mysqli_connect($servername, $username, $password, $dbname);

$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com')";

if (mysqli_query($conn, $sql)) { // Grab the ID of the row we just inserted $last_id = mysqli_insert_id($conn);

echo "New record created successfully. Last inserted ID is: " . $last_id; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }

mysqli_close($conn); ?>

This function is vital for building complex applications that require relational data across multiple tables!


Exercise

?

Which PHP function retrieves the ID generated for an AUTO_INCREMENT column from the previous query?