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);
Related Questions
- How does the placement of braces in if-else statements impact the execution flow and logic in PHP code?
- What is the function of simplexml_load_file() in PHP and how is it used?
- In the given scenario, how can the PHP code be modified to correctly identify and handle users belonging to different squads?