How can PHP prevent data inconsistency when deleting records from related tables in a database?
When deleting records from related tables in a database, PHP can prevent data inconsistency by using transactions. By wrapping the delete queries in a transaction block, PHP ensures that either all related records are deleted successfully or none are deleted, preserving data integrity.
<?php
// Start a transaction
$pdo->beginTransaction();
try {
// Delete related records from table 1
$stmt1 = $pdo->prepare("DELETE FROM table1 WHERE related_id = :id");
$stmt1->execute(['id' => $related_id]);
// Delete related records from table 2
$stmt2 = $pdo->prepare("DELETE FROM table2 WHERE related_id = :id");
$stmt2->execute(['id' => $related_id]);
// Commit the transaction
$pdo->commit();
} catch (Exception $e) {
// Rollback the transaction if an error occurs
$pdo->rollBack();
echo "Error deleting records: " . $e->getMessage();
}