What is the recommended method for retrieving the last inserted ID in a MySQL database using PHP?

When inserting a new record into a MySQL database using PHP, you may want to retrieve the auto-generated ID of the last inserted record for further processing or referencing. One common method to achieve this is by using the mysqli_insert_id() function in PHP, which returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.

// Connect to MySQL database
$conn = mysqli_connect("localhost", "username", "password", "database");

// Insert a new record into the database
mysqli_query($conn, "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");

// Get the ID of the last inserted record
$last_id = mysqli_insert_id($conn);

// Output the last inserted ID
echo "Last inserted ID: " . $last_id;

// Close the database connection
mysqli_close($conn);