UPDATE...SET)The UPDATE statement modifies existing record column values in a database table matching specified WHERE conditions.
flowchart LR
A["Prepare UPDATE Query"] -->|'UPDATE users SET email = :email WHERE id = :id'|| B["Bind Parameters"]
B -->|'$stmt->execute()'|| C["MySQL Modifies Matching Record Row"]
C --> D["Check $stmt->rowCount() for Affected Row Count"]
<?php
declare(strict_types=1);
function updateUserEmail(PDO $pdo, int $userId, string $newEmail): bool
{
// Prepared UPDATE query
$sql = "UPDATE users SET email = :email, updated_at = NOW() WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([
'email' => $newEmail,
'id' => $userId
]);
$affectedRows = $stmt->rowCount();
echo "Updated $affectedRows record(s).
";
return $affectedRows > 0;
}
try {
$pdo = new PDO("mysql:host=127.0.0.1;dbname=ecommerce_db;charset=utf8mb4", 'root', 'secret_password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
updateUserEmail($pdo, 1, "[email protected]");
} catch (PDOException $e) {
die("Update Failed: " . $e->getMessage());
}
WHERE Clause: Omitting WHERE in an UPDATE statement overwrites that column for EVERY row in the database table!updated_at column to track when records were modified.Write a SQL UPDATE statement using named parameters to set status = :status for a specific record :id!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.