How can one effectively insert data into two tables simultaneously in PHP without encountering errors like the one mentioned in the forum thread?

Issue: When inserting data into two tables simultaneously in PHP, errors can occur if the queries are not executed within a transaction. To solve this, wrap the insert queries in a transaction block to ensure that both inserts either succeed or fail 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 the first table
    $pdo->exec("INSERT INTO table1 (column1, column2) VALUES ('value1', 'value2')");

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

    // Commit the transaction
    $pdo->commit();
} catch (PDOException $e) {
    // Rollback the transaction if an error occurs
    $pdo->rollback();
    echo "Error: " . $e->getMessage();
}