How can multiple PDO queries be effectively managed in a PHP script without conflicts or errors?
When managing multiple PDO queries in a PHP script, it is important to use transactions to ensure data integrity and prevent conflicts. By wrapping the queries in a transaction block, you can commit or rollback the changes as needed. This helps to maintain consistency in the database and avoid errors.
try {
$pdo->beginTransaction();
// Query 1
$stmt1 = $pdo->prepare("UPDATE table1 SET column1 = :value1");
$stmt1->execute([':value1' => $newValue1]);
// Query 2
$stmt2 = $pdo->prepare("INSERT INTO table2 (column2) VALUES (:value2)");
$stmt2->execute([':value2' => $newValue2]);
$pdo->commit();
} catch (PDOException $e) {
$pdo->rollback();
echo "Error: " . $e->getMessage();
}
Related questions
-
file uploads directory selections PHP web applications
-
multilingual file names filtering
-
PHP string processing stristr