What is the purpose of using mysql_insert_id() function in PHP?

The mysql_insert_id() function in PHP is used to retrieve the ID generated by a query (usually an INSERT query) on a table with an AUTO_INCREMENT column. This function is useful when you need to get the ID of the last inserted record in order to perform further operations or to display it to the user.

// Connect to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Perform an INSERT query
$query = "INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')";
mysqli_query($connection, $query);

// Get the ID of the last inserted record
$last_insert_id = mysqli_insert_id($connection);

// Use the ID for further operations
echo "The ID of the last inserted record is: " . $last_insert_id;