What is the function in PHP to get the last inserted ID after an INSERT query?

When performing an INSERT query in PHP, you may need to retrieve the ID of the last inserted record. This can be achieved using the mysqli_insert_id() function, which returns the auto-generated ID that was created during the last INSERT query on the current connection. This function should be called immediately after the INSERT query to ensure accuracy.

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

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

// Use the $last_insert_id as needed
echo "The ID of the last inserted record is: " . $last_insert_id;