What is the issue with writing data to two different tables in a database using PHP?

When writing data to two different tables in a database using PHP, the issue arises when the data needs to be inserted into both tables within the same transaction to ensure data integrity. This can be solved by using transactions in PHP to make sure that both insert operations are either committed or rolled back together.

<?php

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

try {
    // Insert data into first table
    $pdo->query("INSERT INTO table1 (column1, column2) VALUES ('value1', 'value2')");

    // Insert data into second table
    $pdo->query("INSERT INTO table2 (column3, column4) VALUES ('value3', 'value4')");

    // Commit the transaction
    $pdo->commit();
} catch (Exception $e) {
    // Roll back the transaction if an error occurs
    $pdo->rollBack();
    echo "Transaction failed: " . $e->getMessage();
}