Thuta Learning
PHP
AdvancedProgrammingBeginner

UPDATE Data

PHPLesson 3135 min

What you'll walk away with

  • Write an UPDATE with SET, WHERE and bound parameters through PDO
  • Show what happens when WHERE is missing and how to guard against it
  • Read rowCount() correctly and know why MySQL's default differs
  • Limit which columns a form may change and catch conflicting edits with a version column

Explain it simply

Explain it simply

INSERT adds a new row. UPDATE changes a row that is already there. Think of the contacts app on your phone: when a friend gets a new number you open that one contact and edit it, you do not retype the whole address book. An UPDATE statement does the same job in a database table. SET says which columns get new values, and WHERE says which rows are allowed to change.

The WHERE part is the one you must never forget. A database does not guess which contact you meant. If you leave WHERE out, it happily edits every contact in the table and does not even raise an error.

Problem → Why → Solution

The problem: an UPDATE that forgot its WHERE

A support team stores contact-form messages in a contacts table. One message contains a phone number that must be hidden, so a developer writes a quick UPDATE in a PHP script. The query runs without an error, the page says "Done", and the developer closes the laptop.

The next morning every contact has the message [hidden]. The statement had no WHERE clause, so it matched every row. The demo below reproduces this on three sample rows. Run it and read the last lines of the output carefully.

missing-where.php
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE contacts (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    message TEXT NOT NULL
)');
$pdo->exec("INSERT INTO contacts (name, message) VALUES
    ('Aung', 'Hello'), ('Su', 'Need a quote'), ('Mya', 'Call me back')");

// The goal was to hide only Su's message. The WHERE clause is missing.
$touched = $pdo->exec("UPDATE contacts SET message = '[hidden]'");
echo "No error. Rows touched: $touched\n";

foreach ($pdo->query('SELECT id, name, message FROM contacts ORDER BY id') as $row) {
    echo "#{$row['id']} {$row['name']}: {$row['message']}\n";
}
text
No error. Rows touched: 3
#1 Aung: [hidden]
#2 Su: [hidden]
#3 Mya: [hidden]

Why doesn't the database warn you?

SQL is declarative: you describe the rows you want changed and the database changes exactly those. A statement with no condition simply describes all rows, which is a perfectly valid request, for example resetting every price after a sale. PHP and PDO cannot tell a mistake from an intention either, so the safeguards are yours: write the WHERE first, bind the key as a parameter, and check how many rows were touched.

Core concept: choose the rows, then change them

An UPDATE statement has three parts. UPDATE names the table, SET lists the columns with their new values, and WHERE filters the rows. In PHP with PDO you do not paste values into that SQL text. You write placeholders such as :message and :id, call prepare() once, and hand the real values to execute(). The database receives the SQL shape and the data separately, so a message like O'Brien said "hi", or a malicious string, can never change the meaning of the query.

1. Pick the row with a stable key

Use the primary key (id) in WHERE. Names and emails can repeat, change or differ in letter case, so WHERE name = 'Su' may match several people. An id is unique by definition and never changes.

2. Choose the columns that may change

Only list columns the user is allowed to edit. Never take column names from form field names: placeholders can bind values but not identifiers. Keep a whitelist array in your own code.

3. Bind the values and run

Call prepare(), then execute() with an array such as ['message' => ..., 'id' => ...]. Cast or validate the id as an integer before it gets here.

4. Read rowCount()

After execute(), rowCount() reports how many rows the statement affected. For a one-row edit, 1 means success. 0 means the id matched nothing, so show "not found" instead of a fake success message.

5. Decide what an unexpected count means

If you expected exactly 1 and got 2 or more, your WHERE is wrong. Inside a transaction (next lesson) you can roll that change back.

SituationSQLite (this lesson's demos)MySQL default
Row found, value changed11
Row found, same value written10 (counts changed rows only)
No row with that id00

That table is why rowCount() === 0 is a weak signal for "this id does not exist" on MySQL: writing the same value back also gives 0. The ways out are to SELECT the row first, to turn on the FOUND_ROWS option on the MySQL connection, or to bump a version or updated_at column so every real edit genuinely changes the row.

Mental model: a filter, then an edit
  1. Choose the row with WHERE id
  2. SET the new column values
  3. Count the rows affected
  4. Treat 0 as "nothing happened"

Think about WHERE first and SET second. If the row selection is right, the rest is small.

General pattern

php
<?php
$stmt = $pdo->prepare(
    'UPDATE table_name SET column_a = :a, column_b = :b WHERE id = :id'
);
$stmt->execute(['a' => $valueA, 'b' => $valueB, 'id' => $id]);

$affected = $stmt->rowCount();
// 1 = the row was updated
// 0 = no such id (on MySQL: or nothing actually changed)

Prepare the SQL once with placeholders, pass the values to execute() as an array, then inspect rowCount(). The key in the WHERE clause is always bound as well.

Update one contact and handle a missing id

This file builds the contacts table in an in-memory SQLite database and inserts three contacts. updateMessage() runs a prepared UPDATE and returns how many rows it affected. The first call edits the existing id #2; the second tries id #99, which does not exist, so it changes zero rows. The course's MySQL lessons write the same kind of SQL, and PDO offers one API for every database driver, so the demo runs here without a MySQL server.

update-contact.php
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE contacts (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    message TEXT NOT NULL
)');

$insert = $pdo->prepare('INSERT INTO contacts (name, message) VALUES (:name, :message)');
$seed = [['Aung', 'Hello'], ['Su', 'Need a quote'], ['Mya', 'Call me back']];
foreach ($seed as [$name, $message]) {
    $insert->execute(['name' => $name, 'message' => $message]);
}

function showContacts(PDO $pdo, string $label): void
{
    echo $label . "\n";
    $rows = $pdo->query('SELECT id, name, message FROM contacts ORDER BY id');
    foreach ($rows as $row) {
        echo "  #{$row['id']} {$row['name']}: {$row['message']}\n";
    }
}

function updateMessage(PDO $pdo, int $id, string $message): int
{
    $stmt = $pdo->prepare('UPDATE contacts SET message = :message WHERE id = :id');
    $stmt->execute(['message' => $message, 'id' => $id]);
    return $stmt->rowCount();
}

showContacts($pdo, 'Before:');

$touched = updateMessage($pdo, 2, 'Please send the quote by Friday');
echo "Updating #2 touched $touched row(s)\n";

$touched = updateMessage($pdo, 99, 'Nobody home');
echo "Updating #99 touched $touched row(s)\n";

showContacts($pdo, 'After:');

Code breakdown

  1. Typed helperfunction updateMessage(PDO $pdo, int $id, string $message): int

    The parameter and return types mean that passing a string as the id raises a TypeError under strict_types. The function returns the affected row count as an int.

  2. Placeholders in the SQL'UPDATE contacts SET message = :message WHERE id = :id'

    No real value appears in the SQL text, only the placeholders :message and :id. WHERE id selects exactly one row.

  3. Values travel separately$stmt->execute(['message' => $message, 'id' => $id]);

    The array keys match the placeholder names. Even if the message contains quotes or SQL keywords, it is only ever treated as data.

  4. Return the affected countreturn $stmt->rowCount();

    This value is why the output reports 1 row for #2 and 0 rows for #99. The calling code can use it to decide whether to show a "not found" message.

  5. Stable output order'SELECT id, name, message FROM contacts ORDER BY id'

    Without ORDER BY, SQL does not promise any row order. Adding ORDER BY id makes the before and after lists appear in the same order every time.

You should see
Before:
  #1 Aung: Hello
  #2 Su: Need a quote
  #3 Mya: Call me back
Updating #2 touched 1 row(s)
Updating #99 touched 0 row(s)
After:
  #1 Aung: Hello
  #2 Su: Please send the quote by Friday
  #3 Mya: Call me back

Let the form change only what it should

A profile form is meant to edit only name and message. But anyone can tamper with the request in their browser and add is_admin=1. If you turn $_POST straight into a SET list (this is called mass assignment), that column changes too. The fix is to keep only the allowed columns with array_intersect_key(). The column names that reach the SQL text come from your own constant, which is why this is safe.

whitelist-update.php
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE contacts (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    message TEXT NOT NULL,
    is_admin INTEGER NOT NULL DEFAULT 0
)');
$pdo->exec("INSERT INTO contacts (name, message) VALUES
    ('Aung', 'Hello'), ('Su', 'Need a quote')");

const EDITABLE_COLUMNS = ['name', 'message'];

function updateContact(PDO $pdo, int $id, array $input): int
{
    // Keep only the columns this form is allowed to change.
    $changes = array_intersect_key($input, array_flip(EDITABLE_COLUMNS));
    if ($changes === []) {
        throw new InvalidArgumentException('Nothing to update');
    }

    $assignments = [];
    foreach (array_keys($changes) as $column) {
        $assignments[] = "$column = :$column";
    }
    $sql = 'UPDATE contacts SET ' . implode(', ', $assignments) . ' WHERE id = :id';

    $stmt = $pdo->prepare($sql);
    $stmt->execute($changes + ['id' => $id]);
    return $stmt->rowCount();
}

// Imagine this array came from a form that an attacker edited.
$submitted = ['message' => 'Updated text', 'is_admin' => 1, 'id' => 2];
echo 'Rows changed: ' . updateContact($pdo, 1, $submitted) . "\n";

try {
    updateContact($pdo, 1, ['is_admin' => 1]);
} catch (InvalidArgumentException $e) {
    echo 'Rejected: ' . $e->getMessage() . "\n";
}

$sql = 'SELECT id, name, message, is_admin FROM contacts ORDER BY id';
foreach ($pdo->query($sql) as $r) {
    echo "#{$r['id']} {$r['name']}: {$r['message']} (is_admin={$r['is_admin']})
";
}
text
Rows changed: 1
Rejected: Nothing to update
#1 Aung: Updated text (is_admin=0)
#2 Su: Need a quote (is_admin=0)

The submitted array carried is_admin and id, yet only message changed, and Aung's is_admin stays 0. When no allowed column is left, the function refuses with an exception instead of running an empty UPDATE.

rowCount() on SQLite versus MySQL

The script below tries three cases: writing the same value, writing a new value, and writing to a missing id. The output shows SQLite's behaviour. SQLite counts a row that matched WHERE even when you wrote the same value back.

rowcount.php
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE contacts (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    message TEXT NOT NULL
)');
$pdo->exec("INSERT INTO contacts (name, message) VALUES ('Aung', 'Hello')");

$stmt = $pdo->prepare('UPDATE contacts SET message = :message WHERE id = :id');

$stmt->execute(['message' => 'Hello', 'id' => 1]);       // same value as before
echo 'Same value, row exists:   ' . $stmt->rowCount() . "\n";

$stmt->execute(['message' => 'Hello again', 'id' => 1]); // different value
echo 'New value, row exists:    ' . $stmt->rowCount() . "\n";

$stmt->execute(['message' => 'Hello', 'id' => 42]);      // no such row
echo 'No row with that id:      ' . $stmt->rowCount() . "\n";
text
Same value, row exists:   1
New value, row exists:    1
No row with that id:      0

There is no MySQL server here, so I cannot show MySQL's output. According to the MySQL manual, the default for UPDATE is the number of rows that were actually changed, which means the first line would be 0 on MySQL. The snippet below is the connection option that asks for matched rows instead. It needs a MySQL server, so it is not run here.

mysql-connection.php
<?php
// MySQL only. Host, database and credentials are placeholders.
$pdo = new PDO(
    'mysql:host=localhost;dbname=thutatech_demo;charset=utf8mb4',
    'app_user',
    'secret',
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        // rowCount() now reports rows MATCHED by WHERE, not rows CHANGED
        PDO::MYSQL_ATTR_FOUND_ROWS => true,
    ]
);

Two people editing the same row

Two editors open the same article at once and both see version 1. If the first saves, fine. If the second saves afterwards, they silently overwrite the first person's work. Optimistic concurrency writes the UPDATE as WHERE id = :id AND version = :seen and bumps version = version + 1 in SET. For the second editor no row matches any more, so rowCount() is 0 and the conflict is detected. Because the version bump makes every real edit change the row, this also works with MySQL's default row counting.

optimistic-update.php
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE articles (
    id INTEGER PRIMARY KEY,
    title TEXT NOT NULL,
    version INTEGER NOT NULL DEFAULT 1
)');
$pdo->exec("INSERT INTO articles (title) VALUES ('Draft title')");

function saveTitle(PDO $pdo, int $id, string $title, int $versionSeen): bool
{
    $stmt = $pdo->prepare(
        'UPDATE articles SET title = :title, version = version + 1
         WHERE id = :id AND version = :seen'
    );
    $stmt->execute(['title' => $title, 'id' => $id, 'seen' => $versionSeen]);
    return $stmt->rowCount() === 1;
}

// Two editors open the same article; both see version 1.
$first = saveTitle($pdo, 1, 'Title from editor A', 1);
$second = saveTitle($pdo, 1, 'Title from editor B', 1);

echo 'Editor A saved: ' . ($first ? 'yes' : 'no') . "\n";
echo 'Editor B saved: ' . ($second ? 'yes' : 'conflict, reload and retry') . "\n";

$sql = 'SELECT title, version FROM articles WHERE id = 1';
$row = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
echo "Stored: {$row['title']} (version {$row['version']})\n";
text
Editor A saved: yes
Editor B saved: conflict, reload and retry
Stored: Title from editor A (version 2)

In real projects

In real projects

Profile pages, order status changes, marking a message as read and editing product prices all run on UPDATE. For status changes it is common to write WHERE id = :id AND status = 'pending'. If the order is no longer pending, rowCount() is 0, which stops the same order from being processed twice.

When a user may edit only their own data, add the owner to the condition: WHERE id = :id AND user_id = :user_id. Even if someone changes the id in the URL, the row belongs to somebody else, nothing matches, and rowCount() is 0. Most production projects also set an updated_at column in every UPDATE and log who changed what and when.

Common mistakes

Common mistakes

Forgetting WHERE, or using a non-unique column

Without WHERE every row changes. WHERE name = 'Su' still changes every person called Su. Use a unique key such as id and check rowCount().

Treating rowCount() === 0 as "not found" on MySQL

With MySQL's default, saving an identical value also returns 0. A user who presses Save without editing anything would get a wrong "this record does not exist" error. Check with a SELECT first or use the FOUND_ROWS option.

Building SET from the keys of $_POST

A user can add fields that should not exist (is_admin, price, role) to the request. Define the whitelist of editable columns in your own code.

Pasting the id into the SQL string

Writing "... WHERE id = $id" makes whatever is inside $id part of the query, which is SQL injection. Bind the id with a placeholder even when it comes from a URL.

Mini challenge

Change prices safely

Write two functions that edit prices in a products table. setPrice() selects one product by id and gives it a new price; if the price is not above zero it must refuse without touching the database. discountCategory() lowers the price of a whole category by a percentage and returns how many products changed.

  • Bind every value with a placeholder
  • setPrice() returns a "rejected" line without running the UPDATE when the price is <= 0
  • setPrice() checks rowCount() and tells "not found" apart from "updated"
  • discountCategory() returns the affected row count; use ORDER BY when printing rows
challenge.php
<?php
declare(strict_types=1);

// $pdo already has: products(id, name, category, price_cents)

function setPrice(PDO $pdo, int $id, int $priceCents): string
{
    // TODO: refuse prices <= 0 before touching the database
    // TODO: UPDATE exactly one product, selected by id, with bound parameters
    // TODO: return a message that depends on rowCount()
}

function discountCategory(PDO $pdo, string $category, int $percent): int
{
    // TODO: lower price_cents by $percent for every product in the category
    // TODO: return how many products were changed
}

Expected: The first call reports the new price, the second is rejected and the third says the product was not found. The paper discount touches 2 rows and the garden discount touches 0. Final prices: Notebook 2250, Pen 450, Lamp 4000.

Show hint

A percentage discount can be computed inside SQL as price_cents * (100 - :pct) / 100. In setPrice(), check if ($priceCents <= 0) first and return before preparing anything.

Show solution
challenge.php
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE products (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    category TEXT NOT NULL,
    price_cents INTEGER NOT NULL
)');
$pdo->exec("INSERT INTO products (name, category, price_cents) VALUES
    ('Notebook', 'paper', 2000), ('Pen', 'paper', 500), ('Lamp', 'office', 4000)");

function setPrice(PDO $pdo, int $id, int $priceCents): string
{
    if ($priceCents <= 0) {
        return "rejected: price must be positive (got $priceCents)";
    }
    $stmt = $pdo->prepare('UPDATE products SET price_cents = :price WHERE id = :id');
    $stmt->execute(['price' => $priceCents, 'id' => $id]);

    return $stmt->rowCount() === 1
        ? "product #$id now costs $priceCents"
        : "no product with id $id";
}

function discountCategory(PDO $pdo, string $category, int $percent): int
{
    $stmt = $pdo->prepare(
        'UPDATE products SET price_cents = price_cents * (100 - :pct) / 100
         WHERE category = :category'
    );
    $stmt->execute(['pct' => $percent, 'category' => $category]);
    return $stmt->rowCount();
}

echo setPrice($pdo, 1, 2500) . "\n";
echo setPrice($pdo, 2, 0) . "\n";
echo setPrice($pdo, 77, 100) . "\n";
echo 'Discounted ' . discountCategory($pdo, 'paper', 10) . " paper product(s)\n";
echo 'Discounted ' . discountCategory($pdo, 'garden', 10) . " garden product(s)\n";

foreach ($pdo->query('SELECT id, name, price_cents FROM products ORDER BY id') as $row) {
    echo "#{$row['id']} {$row['name']}: {$row['price_cents']}\n";
}

Quick quiz 1 / 3

The contacts table has 3 rows with different messages. What happens when you run $pdo->exec("UPDATE contacts SET message = '[hidden]'") with no WHERE?

Quick quiz 2 / 3

What is the main problem with $pdo->exec("UPDATE users SET role = 'admin' WHERE email = '$email'")?

Quick quiz 3 / 3

On a default MySQL connection, id 1 already has the message "Hello". After UPDATE contacts SET message = 'Hello' WHERE id = 1, rowCount() returns 0. What does that 0 mean?

What to remember

  • Always write WHERE in an UPDATE, use a unique column such as the primary key, and bind it as a parameter
  • Check rowCount(), but remember that 0 can mean "identical value" on MySQL's default
  • Define the whitelist of editable columns in your own code
  • A version column with WHERE id AND version catches two people editing the same row

PDO Prepared Statements — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

UPDATE Data | Thuta Learning