What are the best practices for retrieving the last inserted ID in a SQL query using PHP?

When inserting data into a database using SQL queries in PHP, it is often necessary to retrieve the ID of the last inserted record. One common way to achieve this is by using the mysqli_insert_id() function provided by PHP's MySQLi extension. This function returns the auto-generated ID that was generated during the last INSERT query.

// Perform the INSERT query
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
$result = mysqli_query($connection, $query);

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

echo "The ID of the last inserted record is: " . $last_insert_id;