How can PHP developers ensure data integrity when inserting records into tables with 1:n and n:m relationships?

When inserting records into tables with 1:n and n:m relationships, PHP developers can ensure data integrity by using transactions. By wrapping the insert statements in a transaction, developers can guarantee that all related records are inserted or none at all, preventing partial inserts that could lead to data inconsistencies.

// Start a transaction
$pdo->beginTransaction();

try {
    // Insert parent record
    $pdo->query("INSERT INTO parent_table (column1, column2) VALUES ('value1', 'value2')");
    
    // Get the ID of the parent record
    $parent_id = $pdo->lastInsertId();
    
    // Insert child records
    $pdo->query("INSERT INTO child_table (parent_id, column3) VALUES ($parent_id, 'value3')");
    
    // Commit the transaction
    $pdo->commit();
} catch (Exception $e) {
    // Rollback the transaction if an error occurs
    $pdo->rollback();
    echo "Error: " . $e->getMessage();
}