What is the best practice for inserting data into multiple tables simultaneously in PHP?

When inserting data into multiple tables simultaneously in PHP, it is best practice to use transactions to ensure data consistency. By using transactions, you can make sure that either all the inserts succeed or none of them do, preventing partial data insertion. This helps maintain data integrity and ensures that the database remains in a consistent state.

<?php

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

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

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

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

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