How can PHP developers ensure data consistency when working with multiple tables in a database?
When working with multiple tables in a database, PHP developers can ensure data consistency by using transactions. Transactions allow developers to perform a series of database operations as a single unit, ensuring that either all operations are completed successfully or none of them are. This helps maintain data integrity and prevents inconsistencies in the database.
// Start a transaction
$pdo->beginTransaction();
try {
// Perform multiple database operations within the transaction
$pdo->query("INSERT INTO table1 (column1) VALUES ('value1')");
$pdo->query("INSERT INTO table2 (column2) VALUES ('value2')");
// Commit the transaction if all operations are successful
$pdo->commit();
} catch (Exception $e) {
// Rollback the transaction if any operation fails
$pdo->rollBack();
echo "Transaction failed: " . $e->getMessage();
}