How can the LastInsertID function in mysqli be used to assign a new ID to duplicated data in a MySQL database through PHP?

When inserting data into a MySQL database through PHP, we can use the LastInsertID function in mysqli to retrieve the auto-generated ID of the last inserted row. If we encounter duplicated data while inserting, we can use this function to assign a new ID to the duplicated data, ensuring each entry in the database has a unique identifier.

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

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

// Check for duplicate entry
if ($mysqli->errno == 1062) {
    // Assign a new ID to the duplicated data
    $new_id = $mysqli->insert_id + 1;
    $query = "INSERT INTO table_name (id, column1, column2) VALUES ('$new_id', 'value1', 'value2')";
    $mysqli->query($query);
}