How can the mysql_insert_id() function be used to retrieve the auto_increment ID after inserting a record in PHP?

When inserting a record into a MySQL database table with an auto_increment primary key column, you can use the mysql_insert_id() function in PHP to retrieve the last inserted ID. This function returns the ID generated by the most recent INSERT query, which is useful for getting the auto_increment ID of the record just inserted. You can then use this ID for further operations or to display to the user.

// Insert a record into the database
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
$result = mysqli_query($connection, $query);

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

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