MySQL Update Data

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 203 of 255

Changing Existing Rows

In simple terms: Data changes all the time: a customer moves to another city, an order is paid, a product's stock goes down when it is sold. The SQL UPDATE statement changes values in existing rows, and the WHERE clause decides which rows are changed.

Technically: UPDATE table SET column = value, ... WHERE condition modifies every row matching the condition. Values can be constants, parameters, or expressions based on the current values (stock = stock - 1). After execution, affected_rows reports how many rows were actually changed. Like DELETE, an UPDATE without WHERE affects every row.


Syntax

UPDATE customers
SET city = ?
WHERE id = ?;

Warning: UPDATE products SET price = 10; changes the price of every product. Always include a precise WHERE clause.


A Basic Update

<?php
require __DIR__ . '/src/db.php';

$db = db();

$db->execute_query('UPDATE customers SET city = ? WHERE id = ?', ['Puducherry', 4]);
echo "Changed rows: {$db->affected_rows}\n";

$db->execute_query('UPDATE customers SET city = ? WHERE id = ?', ['Puducherry', 4]);
echo "Changed rows: {$db->affected_rows}\n";

$customer = $db->execute_query('SELECT name, city FROM customers WHERE id = ?', [4])->fetch_assoc();
echo "{$customer['name']} now lives in {$customer['city']}\n";

Output

Changed rows: 1
Changed rows: 0
Dev D'Souza now lives in Puducherry

affected_rows Counts Changed Rows

The second update found the row, but the city was already Puducherry, so nothing changed and affected_rows is 0. This matters when interpreting results:

affected_rowsMeaning
> 0That many rows were changed
0No row matched or matching rows already had the new values

To distinguish "not found" from "no change", mysqli::$info shows both numbers after an UPDATE sent with query():

<?php
$db->query("UPDATE customers SET city = 'Puducherry' WHERE id = 4");
echo $db->info . "\n";

Output

Rows matched: 1  Changed: 0  Warnings: 0

Updating Several Columns

<?php
require __DIR__ . '/src/db.php';

function updateCustomerProfile(mysqli $db, int $id, array $input): bool
{
    $editable = ['name', 'city'];   // allow-list of columns users may change
    $sets = [];
    $params = [];

    foreach ($editable as $column) {
        if (array_key_exists($column, $input)) {
            $sets[] = "$column = ?";
            $params[] = $input[$column] === '' ? null : trim((string) $input[$column]);
        }
    }

    if ($sets === []) {
        return false;
    }

    $params[] = $id;
    $db->execute_query('UPDATE customers SET ' . implode(', ', $sets) . ' WHERE id = ?', $params);

    return $db->affected_rows > 0;
}

var_dump(updateCustomerProfile(db(), 5, ['name' => 'Elango R', 'city' => 'Tiruchirappalli', 'email' => 'hacker@example.com']));

Output

bool(true)

How It Works

  1. Only columns in the $editable allow-list can be updated. The email field sent along with the form is ignored, so users cannot change fields they are not supposed to (for example, is_admin or email without verification). This prevents mass assignment vulnerabilities.
  2. Column names in the SQL come only from the allow-list; all values are parameters.
  3. Empty strings become NULL for optional fields.
  4. The customer's ID is the last parameter, matching the final ? in WHERE id = ?.

Relative Updates: Let the Database Calculate

To change a value based on its current value — reducing stock, increasing a view counter — compute it inside the SQL statement:

UPDATE products SET stock = stock - 2 WHERE sku = 'LAMP-01';

Reading the value into PHP, calculating, and writing it back is a race condition: two simultaneous requests can both read 8 and both write 6, losing one sale. An update like stock = stock - ? is performed atomically by the database.

Preventing Overselling

Adding a condition to the WHERE clause makes the update succeed only if enough stock is available:

<?php
require __DIR__ . '/src/db.php';

function reserveStock(mysqli $db, string $sku, int $quantity): string
{
    $db->execute_query(
        'UPDATE products SET stock = stock - ? WHERE sku = ? AND stock >= ?',
        [$quantity, $sku, $quantity]
    );

    if ($db->affected_rows === 1) {
        $left = $db->execute_query('SELECT stock FROM products WHERE sku = ?', [$sku])->fetch_column();
        return "Reserved $quantity × $sku ($left left)";
    }

    return "Cannot reserve $quantity × $sku: not enough stock";
}

$db = db();

echo reserveStock($db, 'LAMP-01', 2) . "\n";
echo reserveStock($db, 'BAG-02', 1) . "\n";
echo reserveStock($db, 'LAMP-01', 10) . "\n";

Output

Reserved 2 × LAMP-01 (6 left)
Cannot reserve 1 × BAG-02: not enough stock
Cannot reserve 10 × LAMP-01: not enough stock

Why This Is Safe

  1. Checking and decrementing happen in one atomic statement; no other request can change the stock in between.
  2. If the stock is insufficient, the WHERE condition matches no row and nothing changes (affected_rows = 0).
  3. Two customers buying the last Desk Lamp at the same moment cannot both succeed: MySQL locks the row during the update, so the second update sees the new stock.

(After this example, the Desk Lamp's stock is 6.)


Updating a Status Only From an Expected State

The same idea protects workflows: an order should only become "paid" if it is currently "pending":

<?php
require __DIR__ . '/src/db.php';

$db = db();

$db->execute_query("UPDATE orders SET status = 'paid' WHERE id = ? AND status = 'pending'", [501]);
echo $db->affected_rows === 1 ? "Order 501 marked as paid\n" : "Order 501 was not pending\n";

$db->execute_query("UPDATE orders SET status = 'paid' WHERE id = ? AND status = 'pending'", [501]);
echo $db->affected_rows === 1 ? "Order 501 marked as paid\n" : "Order 501 was not pending\n";

Output

Order 501 marked as paid
Order 501 was not pending

If a payment confirmation arrives twice (payment providers often retry webhooks), the second update changes nothing, and the application can avoid sending a second confirmation email.


Automatic Timestamps

The products.updated_at column was declared with ON UPDATE CURRENT_TIMESTAMP (see MySQL Create Table), so MySQL updates it automatically whenever a product row actually changes. No PHP code is needed — and it cannot be forgotten.


Updates That Belong Together

When an operation updates several rows or tables — reducing stock for every item in an order and marking the order as paid — wrap the updates in a transaction, so they succeed or fail together (see PDO Transactions).


Common Mistakes

Missing WHERE Clause

Effect: Every row is changed.

Fix: Always write a precise WHERE clause; test it with a SELECT first.

Read-Modify-Write in PHP

Effect: Lost updates under concurrent requests.

Fix: Use relative updates (stock = stock - ?) and conditions in WHERE.

Updating Columns Chosen by the User

Effect: Mass assignment — users change fields they should not.

Fix: Allow-list editable columns.

Misreading affected_rows

Effect: "No change" is mistaken for "not found".

Fix: Check existence separately, or inspect $db->info.


Best Practices

  • Update with prepared statements and precise WHERE clauses.
  • Let the database perform calculations atomically.
  • Add state conditions (AND stock >= ?, AND status = 'pending') to enforce business rules safely.
  • Allow-list the columns that can be updated from user input.
  • Group related updates in transactions.

Official reference: https://www.php.net/manual/en/mysqli.query.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about MySQL Update Data and get answers drawn from it.

Signed-in readers only.