How can PHP developers ensure data integrity when updating records in a database using PHP?

To ensure data integrity when updating records in a database using PHP, developers can use transactions. Transactions allow developers to group multiple database operations into a single unit of work, ensuring that either all operations succeed or none of them do, thus maintaining data integrity.

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

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

try {
    // Perform database update operations
    $stmt = $pdo->prepare("UPDATE users SET name = :name WHERE id = :id");
    $stmt->execute(['name' => 'John Doe', 'id' => 1]);

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