PHP and MariaDB: Update a row without overwriting newer edits
To update a MariaDB row from PHP, read its current values with GET, then bind validated POST values to a prepared UPDATE. This example saves only when the ID and the version originally loaded both match, so a stale form cannot overwrite a newer edit.
Prepare the practice table and connection
You need mysqli, mbstring, and a MariaDB database named learning. See the mysqli connection guide for the connection. Run the SQL in a database without production data. If the table already exists, use a separate practice database. The setup account needs CREATE and INSERT. The application needs SELECT and UPDATE on this table.
USE learning;
CREATE TABLE employees_update_demo (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
version INT NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO employees_update_demo (id, name) VALUES
(1, 'Original name'), (2, 'Comparison row');
Edit ID 1 and use ID 2 for comparison. Create public in the practice folder and save the configuration as database-config.php outside it. Fill in your practice connection details. Keep this file out of public deployments and version control.
<?php
return [
'host' => '127.0.0.1',
'username' => 'learning_user',
'password' => 'REPLACE_WITH_YOUR_PRIVATE_PASSWORD',
'database' => 'learning',
'port' => 3306,
];
Open the form and save a name
Save the complete example as UTF-8 in public/employee-edit.php. Run php -S 127.0.0.1:8000 -t public from the practice folder and open http://127.0.0.1:8000/employee-edit.php?id=1. Allow cookies and save the PHP file without a BOM or whitespace before the opening tag.
<?php
session_start(['use_strict_mode' => true, 'cookie_httponly' => true, 'cookie_samesite' => 'Lax']);
header('Content-Type: text/html; charset=UTF-8');
if (!extension_loaded('mysqli') || !extension_loaded('mbstring')) {
http_response_code(500);
exit('The mysqli and mbstring extensions are required.');
}
$isPost = $_SERVER['REQUEST_METHOD'] === 'POST';
$source = $isPost ? $_POST : $_GET;
$rawId = $source['id'] ?? null;
$id = is_string($rawId) ? filter_var($rawId, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 2147483647]]) : false;
if ($id === false) {
http_response_code(400);
exit('Enter a valid ID.');
}
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$message = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);
$name = '';
$version = 0;
$found = false;
$errors = [];
$redirect = false;
if ($isPost) {
$token = $_POST['csrf'] ?? null;
if (!is_string($token) || !hash_equals($_SESSION['csrf'], $token)) {
http_response_code(403);
exit('Open the form again and resubmit it.');
}
$rawVersion = $_POST['version'] ?? null;
$version = is_string($rawVersion) ? filter_var($rawVersion, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 2147483646]]) : false;
$name = is_string($_POST['name'] ?? null) ? trim($_POST['name']) : '';
if ($version === false || !mb_check_encoding($name, 'UTF-8') || $name === '' || mb_strlen($name, 'UTF-8') > 50) {
http_response_code(422);
$errors[] = 'Check the version and name. The name must be 1–50 UTF-8 characters.';
}
}
function escapeText($value): string {
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$link = $stmt = null;
if ($errors === []) {
try {
$c = require dirname(__DIR__) . '/database-config.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect($c['host'], $c['username'], $c['password'], $c['database'], $c['port']);
mysqli_set_charset($link, 'utf8mb4');
if ($isPost) {
$stmt = mysqli_prepare($link,
'UPDATE employees_update_demo SET name = ?, version = version + 1 WHERE id = ? AND version = ?');
mysqli_stmt_bind_param($stmt, 'sii', $name, $id, $version);
mysqli_stmt_execute($stmt);
$changed = mysqli_stmt_affected_rows($stmt);
if ($changed !== 0 && $changed !== 1) {
throw new RuntimeException('Unexpected affected row count');
}
if ($changed === 1) {
$_SESSION['flash'] = 'Changes saved.';
$_SESSION['csrf'] = bin2hex(random_bytes(32));
$redirect = true;
} else {
http_response_code(409);
$errors[] = 'Another request updated or deleted this row. Reload the current value.';
}
} else {
$stmt = mysqli_prepare($link, 'SELECT name, version FROM employees_update_demo WHERE id = ?');
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name, $version);
$fetched = mysqli_stmt_fetch($stmt);
if ($fetched === false) {
throw new RuntimeException('Could not read the result');
}
$found = $fetched === true;
if (!$found) {
http_response_code(404);
$errors[] = 'No employee has that ID.';
}
}
} catch (Throwable $e) {
http_response_code(500);
error_log('Employee update failed. Code: ' . $e->getCode());
$errors[] = 'The request failed. Check the server log.';
} finally {
if ($stmt instanceof mysqli_stmt) {
mysqli_stmt_close($stmt);
}
if ($link instanceof mysqli) {
mysqli_close($link);
}
}
}
if ($redirect) {
header('Location: employee-edit.php?id=' . $id, true, 303);
exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Employee editing demo</title>
</head>
<body>
<h1>Edit employee: <?= escapeText($id) ?></h1>
<?php if ($message !== ''): ?><p><?= escapeText($message) ?></p><?php endif; ?>
<?php foreach ($errors as $error): ?><p><?= escapeText($error) ?></p><?php endforeach; ?>
<?php if ($found || ($isPost && http_response_code() === 422)): ?>
<form action="employee-edit.php" method="post">
<input type="hidden" name="csrf" value="<?= escapeText($_SESSION['csrf']) ?>">
<input type="hidden" name="id" value="<?= escapeText($id) ?>">
<input type="hidden" name="version" value="<?= escapeText($version) ?>">
<p><label>Name <input name="name" maxlength="50" required value="<?= escapeText($name) ?>"></label></p>
<button type="submit">Save</button>
</form>
<?php endif; ?>
<p><a href="employee-edit.php?id=<?= escapeText($id) ?>">Reload the current value</a></p>
</body>
</html>
Enter a new fictional name and save. A 303 redirects to a GET for the same ID, where the updated name and a confirmation appear. Refreshing does not repeat the POST. In production, authenticate users and enforce row-level permission on the read and update. A user can change a hidden ID.
Validate SELECT and UPDATE inputs
GET reads one row by positive integer ID and gets the name and version using mysqli_stmt_bind_result(). POST checks the session cross-site request forgery (CSRF) token, ID, version, and that the trimmed name is valid UTF-8 and 1–50 characters long. Escape values displayed in the form as HTML. PHP Manual · mysqli_stmt_bind_result() PHP Manual · mysqli_stmt_fetch() PHP Manual · hash_equals()
SET changes the name and increments the version. WHERE compares the primary key and the previous version. The binding type sii sends the name as a string and the ID and version as integers. The demo accepts submitted versions up to 2147483646 so adding one stays within a signed INT. MariaDB Docs · UPDATE PHP Manual · mysqli_stmt_bind_param()
Use the version to detect conflicting edits
An ordinary UPDATE can report zero changed rows when the value stays the same. This example increments the version on every match, so the changed-row count is one even if the name is unchanged. Zero means the ID is missing or the version is stale, and results in HTTP 409. A database error returns HTTP 500. PHP Manual · mysqli_stmt_affected_rows() MariaDB Docs · ROW_COUNT()
Checking the version at save time is optimistic concurrency control. Every path that writes the same row must increment the version. After a conflict, reload the current value and compare it with your intended edit. The conflict page suppresses the stale save form.
Verify successful and conflicting saves
After the first save, the query below should show ID 1 with the new name and version 2, and ID 2 with its original name and version 1. Open ID 1 in two separate browser sessions, save in one, and submit the stale form in the other. Expect 409. An older tab in the same session may return 403 first because the token rotated.
SELECT id, name, version FROM learning.employees_update_demo ORDER BY id;
Expect 400 for an invalid ID, 404 for a missing row on GET, 403 for a bad token, and 422 when name or version validation fails. To restore a previous value, read the latest row and save it against the current version. Stop the local server with Ctrl+C.




