PHP MySQL Update Data
In this page:
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
mysqli_query($conn, $sql);
mysqli_affected_rows($conn); // how many rows changed
Basic UPDATE with a WHERE Clause
UPDATE tableName SET column = newValue WHERE condition changes the specified column, only on rows matching the condition -- UPDATE users SET status = inactive WHERE id = 5 changes exactly one user's status, leaving everyone else untouched.
Example: Basic UPDATE with a WHERE Clause
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER, status TEXT)");
$db->exec("INSERT INTO users VALUES (5, 'active')");
$db->exec("UPDATE users SET status = 'inactive' WHERE id = 5");
// Print "Updated" to the output
echo "Updated";
?>
Login to try C/C++/Java/PHP code in the editor
Updating Multiple Columns at Once
A single UPDATE statement can change several columns together by separating them with commas: UPDATE users SET name = ?, email = ?
WHERE id = ? updates both the name and email of one specific user in one query, rather than running two separate UPDATE statements.
Example: Updating Multiple Columns at Once
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER, name TEXT, email TEXT)");
$db->exec("INSERT INTO users VALUES (1, 'Old', '[email protected]')");
// Declare `$stmt`, set to `$db->prepare("UPDATE users SET name = :name, email = :email WHERE id = :id")`
$stmt = $db->prepare("UPDATE users SET name = :name, email = :email WHERE id = :id");
$stmt->bindValue(':name', 'Alice', SQLITE3_TEXT);
$stmt->bindValue(':email', '[email protected]', SQLITE3_TEXT);
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$stmt->execute();
// Print "Both columns updated in one query" to the output
echo "Both columns updated in one query";
?>
Login to try C/C++/Java/PHP code in the editor
Checking How Many Rows Were Updated
mysqli_affected_rows($conn) reports how many rows the most recent UPDATE actually changed -- worth checking to confirm an update matched the expected number of rows, or to detect that an ID did not exist at all (0 rows affected).
Example: Checking How Many Rows Were Updated
<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (id INTEGER, status TEXT)");
$db->exec("INSERT INTO users VALUES (1, 'active')");
$db->exec("UPDATE users SET status = 'inactive' WHERE id = 1");
echo $db->changes() . " row(s) updated"; // mysqli_affected_rows($conn) equivalent
?>
Login to try C/C++/Java/PHP code in the editor
Updating a Value Relative to Its Current Value
An UPDATE can reference a column's own current value within the SET clause, like UPDATE products SET stock = stock - 1 WHERE id = ?, which decreases the existing stock count by one -- useful for counters, running totals, and inventory adjustments without first reading the value into PHP.
Example: Updating a Value Relative to Its Current Value
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE products (id INTEGER, stock INTEGER)");
$db->exec("INSERT INTO products VALUES (1, 10)");
$db->exec("UPDATE products SET stock = stock - 1 WHERE id = 1");
// Declare `$result`, set to `$db->query("SELECT stock FROM products WHERE id = 1")`
$result = $db->query("SELECT stock FROM products WHERE id = 1");
// Print a human-readable dump of `$result->fetchArray(SQLITE3_ASSOC)`
print_r($result->fetchArray(SQLITE3_ASSOC));
?>
Login to try C/C++/Java/PHP code in the editor
Updating Multiple Rows That Share a Condition
Just like DELETE, an UPDATE's WHERE clause can match more than one row at once -- UPDATE orders SET status = expired WHERE created_at < ? updates every old order in a single statement, far more efficient than looping and updating each row individually.
Example: Updating Multiple Rows That Share a Condition
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE orders (id INTEGER, created_at TEXT, status TEXT)");
$db->exec("INSERT INTO orders VALUES (1, '2020-01-01', 'open'), (2, '2024-01-01', 'open')");
$db->exec("UPDATE orders SET status = 'expired' WHERE created_at < '2023-01-01'");
// Print `$db->changes() . " old order(s) expired"` to the output
echo $db->changes() . " old order(s) expired";
?>
Login to try C/C++/Java/PHP code in the editor
- Running UPDATE table SET column = value without a WHERE clause, which updates that column on every single row in the table.
- Building an UPDATE's SET or WHERE values from unvalidated, unbound user input, risking SQL injection just as with any other query type.
- Updating a row's value based on stale data read earlier in the script, overwriting a change another process may have made in between.
- UPDATE table SET col = newValue WHERE condition changes only the matching rows' specified columns.
- UPDATE without a WHERE clause updates every row in the table -- always double-check a WHERE clause is present.
- mysqli_affected_rows($conn) reports how many rows an UPDATE actually changed.
UPDATE is standard SQL and works identically across all MySQL and MariaDB versions PHP supports.
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- PHP MySQL Introduction
- PHP MySQLi Connection
- PHP PDO Introduction
- PHP CRUD Operations
- PHP Prepared Statements
- PHP Stored Procedures
- PHP Transactions
- PHP Error Handling in DB
- PHP MySQL Connect
- PHP MySQL Create DB
- PHP MySQL Create Table
- PHP MySQL Insert Data
- PHP MySQL Get Last ID
- PHP MySQL Insert Multiple
- PHP MySQL Prepared Statements
- PHP MySQL Select Data
- PHP MySQL Where
- PHP MySQL Order By
- PHP MySQL Delete Data
- PHP MySQL Update Data
- PHP MySQL Limit Data