How can foreign keys be utilized to maintain data integrity when duplicating records in a MySQL database with PHP?

When duplicating records in a MySQL database with PHP, foreign keys can be utilized to maintain data integrity by ensuring that the relationships between tables are preserved. This can be achieved by first inserting the new record into the parent table, retrieving the auto-generated primary key value, and then inserting the corresponding records into the child tables using the retrieved primary key value as the foreign key.

// Insert new record into parent table
$query = "INSERT INTO parent_table (column1, column2) VALUES ('value1', 'value2')";
mysqli_query($conn, $query);

// Retrieve auto-generated primary key value
$parent_id = mysqli_insert_id($conn);

// Insert corresponding records into child tables
$query_child = "INSERT INTO child_table (parent_id, column3) VALUES ('$parent_id', 'value3')";
mysqli_query($conn, $query_child);