How can the LAST_INSERT_ID() function be utilized in PHP to handle database entries?

When inserting data into a database, we often need to retrieve the auto-generated ID of the last inserted row. This can be achieved using the LAST_INSERT_ID() function in MySQL. In PHP, we can execute a query to insert data into the database and then immediately retrieve the last inserted ID using the mysqli_insert_id() function.

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

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Insert data into the database
$mysqli->query("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");

// Get the ID of the last inserted row
$last_insert_id = $mysqli->insert_id;

// Use the last insert ID as needed
echo "Last Inserted ID: " . $last_insert_id;

// Close the connection
$mysqli->close();