What is the best way to retrieve the ID of a newly inserted record in a MySQL database using PHP?

When inserting a new record into a MySQL database using PHP, the best way to retrieve the ID of the newly inserted record is by using the mysqli_insert_id() function. This function returns the auto-generated ID used in the last query. After inserting the record, call mysqli_insert_id() to get the ID value.

// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Insert a new record
$mysqli->query("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");

// Get the ID of the newly inserted record
$new_id = $mysqli->insert_id;

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