How can data be saved in multiple tables in PHP?

When saving data in multiple tables in PHP, you can use transactions to ensure that either all the data is saved successfully or none of it is saved. This helps maintain data integrity and consistency across the tables.

<?php

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

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

try {
    // Save data to the first table
    $stmt1 = $pdo->prepare("INSERT INTO table1 (column1, column2) VALUES (:value1, :value2)");
    $stmt1->execute(['value1' => 'data1', 'value2' => 'data2']);

    // Save data to the second table
    $stmt2 = $pdo->prepare("INSERT INTO table2 (column1, column2) VALUES (:value1, :value2)");
    $stmt2->execute(['value1' => 'data3', 'value2' => 'data4']);

    // Commit the transaction
    $pdo->commit();

    echo "Data saved successfully in multiple tables.";

} catch (Exception $e) {
    // Rollback the transaction if an error occurs
    $pdo->rollBack();

    echo "Error saving data: " . $e->getMessage();
}