What are some best practices for handling database updates in PHP?

When handling database updates in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, it is recommended to use transactions to group multiple database operations into a single unit of work to maintain consistency.

// Example of handling database updates in PHP using prepared statements and transactions

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

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

try {
    // Prepare update statement
    $stmt = $pdo->prepare("UPDATE users SET email = :email WHERE id = :id");

    // Bind parameters
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':id', $id);

    // Set parameters
    $email = 'newemail@example.com';
    $id = 1;

    // Execute update statement
    $stmt->execute();

    // Commit transaction
    $pdo->commit();

    echo "Database update successful";
} catch (Exception $e) {
    // Rollback transaction on error
    $pdo->rollBack();
    echo "Database update failed: " . $e->getMessage();
}