How can PHP developers ensure data integrity when working with multiple tables in a database?

When working with multiple tables in a database, PHP developers can ensure data integrity by using transactions. Transactions allow developers to execute a series of database operations as a single unit, ensuring that all changes are either committed together or rolled back if an error occurs. This helps maintain consistency and prevent data corruption across multiple tables.

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

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

try {
    // Perform database operations
    $pdo->exec("INSERT INTO table1 (column1) VALUES ('value1')");
    $pdo->exec("UPDATE table2 SET column2 = 'new_value' WHERE id = 1");

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