What are the best practices for retrieving the ID of a newly inserted record in PHP and MySQL?

When inserting new records into a MySQL database using PHP, it is important to retrieve the auto-generated ID of the newly inserted record for future reference or to perform additional operations. One common practice is to use 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
$connection = mysqli_connect("localhost", "username", "password", "database");

// Insert new record into table
mysqli_query($connection, "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");

// Retrieve the ID of the newly inserted record
$new_id = mysqli_insert_id($connection);

// Use the $new_id variable as needed
echo "The ID of the newly inserted record is: " . $new_id;

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