PHP and MariaDB: Delete one row with a prepared statement
To delete a specific MariaDB row from PHP, bind its primary key to DELETE … WHERE id = ?. Validate the ID and confirmation on the server and use the affected-row count to report the outcome. Opening the list with GET only reads data.
Prepare the practice table and connection
You need the mysqli extension and a MariaDB database named learning. See the mysqli connection guide. Run the SQL in a fresh practice database without real employee data. If the table already exists, use a different practice database. The setup account needs CREATE and INSERT. The application needs SELECT and DELETE on the table.
USE learning;
CREATE TABLE employees_delete_demo (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO employees_delete_demo VALUES
(1, 'Row to delete'), (2, 'Row to keep');
Save the settings in database-config.php and replace the host, account, and password placeholder with practice values. Keep the file outside the public document root, public deployment, and version control.
<?php
return [
'host' => '127.0.0.1',
'username' => 'learning_user',
'password' => 'REPLACE_WITH_YOUR_PRIVATE_PASSWORD',
'database' => 'learning',
'port' => 3306,
];
Select a row and delete it through POST
Save the full example as public/employee-delete.php. Allow the session cookie and save as UTF-8 without leading output before the PHP tag. Run php -S 127.0.0.1:8000 -t public from the practice directory and open http://127.0.0.1:8000/employee-delete.php.
<?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')) {
http_response_code(500);
exit('The mysqli extension is required.');
}
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$message = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);
$isPost = $_SERVER['REQUEST_METHOD'] === 'POST';
$id = null;
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 submit it.');
}
$rawId = $_POST['id'] ?? null;
$id = is_string($rawId) ? filter_var($rawId, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 2147483647]]) : false;
if ($id === false || ($_POST['confirm'] ?? null) !== '1') {
http_response_code(400);
exit('A valid ID and deletion confirmation are required.');
}
}
function escapeText($value): string {
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$rows = [];
$error = '';
$redirect = false;
$link = $stmt = null;
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, 'DELETE FROM employees_delete_demo WHERE id = ?');
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
$deleted = mysqli_stmt_affected_rows($stmt);
if ($deleted !== 0 && $deleted !== 1) {
throw new RuntimeException('Unexpected affected row count');
}
$_SESSION['flash'] = $deleted === 1
? 'Deleted the row with ID ' . $id . '.'
: 'No row matched. It may already have been deleted.';
$_SESSION['csrf'] = bin2hex(random_bytes(32));
$redirect = true;
} else {
$result = mysqli_query($link, 'SELECT id, name FROM employees_delete_demo ORDER BY id LIMIT 20');
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
mysqli_free_result($result);
}
} catch (Throwable $e) {
http_response_code(500);
error_log('Employee operation failed. Code: ' . $e->getCode());
$error = 'The operation 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-delete.php', 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 deletion example</title>
</head>
<body>
<h1>Employee deletion example</h1>
<?php if ($message !== ''): ?><p><?= escapeText($message) ?></p><?php endif; ?>
<?php if ($error !== ''): ?>
<p><?= escapeText($error) ?></p>
<?php elseif ($rows === []): ?>
<p>No employees to display.</p>
<?php else: ?>
<table>
<thead><tr><th scope="col">ID</th><th scope="col">Name</th><th scope="col">Delete</th></tr></thead>
<tbody>
<?php foreach ($rows as $row): ?>
<tr>
<td><?= escapeText($row['id']) ?></td>
<td><?= escapeText($row['name']) ?></td>
<td><form action="employee-delete.php" method="post">
<input type="hidden" name="csrf" value="<?= escapeText($_SESSION['csrf']) ?>">
<input type="hidden" name="id" value="<?= escapeText($row['id']) ?>">
<label><input type="checkbox" name="confirm" value="1" required>Confirm deletion of this row</label>
<button type="submit">Delete</button>
</form></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</body>
</html>
Check the box for ID 1 and click that row’s delete button. ID 1 should disappear and ID 2 should remain. In production, verify sign-in and row-level deletion permission on the server. Hidden IDs can be changed, so enforce ownership or tenant scope in the read and delete queries.
Use the primary key and check affected rows
filter_var() validates an integer from 1 to 2147483647. Then bind_param() uses i to bind it as an integer. The primary key limits the statement to at most one match. Omitting WHERE can remove multiple rows. PHP Manual · filter_var() PHP Manual · mysqli_stmt_bind_param() MariaDB Docs · DELETE
mysqli_stmt_affected_rows() returns 1 when a row was deleted. It returns 0 when no row matched at execution, and the example shows a separate message. A database failure sends HTTP 500 with a generic message. Read the error code in the restricted server log. PHP Manual · mysqli_stmt_affected_rows()
Check the CSRF token and redirect to the list
To prevent cross-site request forgery (CSRF), use hash_equals() to compare the submitted token with the session token. A missing or different token gives 403. An invalid ID or confirmation gives 400. In both cases the deletion is skipped. PHP Manual · hash_equals()
After processing, the example rotates the token and sends an HTTP 303 redirect to the GET list. Refreshing that list does not repeat the deletion. Reload the list to get a fresh form in another tab.
Verify the deletion and understand recovery
Use the query below to check that ID 1 is gone and ID 2 remains. The single example deletion runs with default autocommit. If ID 1 is absent, the following insert recreates the known sample row.
SELECT id, name FROM learning.employees_delete_demo ORDER BY id;
INSERT INTO learning.employees_delete_demo (id, name) VALUES (1, 'Row to delete');
With InnoDB, rollback applies to changes before commit. Recovery after commit needs a mechanism such as a backup or soft deletion. Check foreign key rules on real tables because a reference can block deletion or cascade it. Stop the local server with Ctrl+C when finished. PHP Manual · mysqli_begin_transaction() MariaDB Docs · FOREIGN KEY




