Skip to content
PHP Logo

How can PHP developers ensure data consistency when querying a database?

PHP developers can ensure data consistency when querying a database by using transactions. By wrapping database queries within a transaction, developers can ensure that either all queries are successfully executed or none are, maintaining data integrity. This helps prevent partial updates or inconsistencies in the database.

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

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

try {
    // Perform database queries within the transaction
    $pdo->query("UPDATE table1 SET column1 = 'value1'");
    $pdo->query("INSERT INTO table2 (column2) VALUES ('value2')");

    // Commit the transaction if all queries are successful
    $pdo->commit();
} catch (PDOException $e) {
    // Rollback the transaction if an error occurs
    $pdo->rollBack();
    echo "Error: " . $e->getMessage();
}