How can transactions be implemented in PHP to ensure data integrity in multiple database operations?
To ensure data integrity in multiple database operations in PHP, transactions can be used. Transactions allow multiple database operations to be treated as a single unit of work, ensuring that either all operations are completed successfully or none of them are. This helps maintain data consistency and prevents partial updates or errors.
// Start the transaction
$pdo->beginTransaction();
try {
// Perform multiple database operations here
// Commit the transaction if all operations are successful
$pdo->commit();
} catch (Exception $e) {
// Rollback the transaction if an error occurs
$pdo->rollBack();
echo "Transaction failed: " . $e->getMessage();
}