What are some alternative approaches for handling transactions involving multiple tables in PHP to ensure data integrity?

When handling transactions involving multiple tables in PHP to ensure data integrity, one approach is to use database transactions. By wrapping the related SQL queries in a transaction block, you can ensure that either all the queries are executed successfully or none of them are, maintaining the integrity of the data across tables.

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

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

try {
    // Perform multiple SQL queries within the transaction
    $pdo->exec("INSERT INTO table1 (column1, column2) VALUES ('value1', 'value2')");
    $pdo->exec("UPDATE table2 SET column3 = 'new_value' WHERE column4 = 'condition'");

    // Commit the transaction if all queries are successful
    $pdo->commit();
} catch (PDOException $e) {
    // Rollback the transaction if an error occurs
    $pdo->rollBack();
    echo "Transaction failed: " . $e->getMessage();
}