PHP 与 MariaDB:用 INSERT 保存表单数据
把 PHP 表单写入 MariaDB 时,先在服务端验证输入,再将值绑定到 INSERT 的占位符。示例保存名、姓和入职日期,然后通过 HTTP 303 转到 GET,并显示新 ID。
准备练习表和连接配置
需要 mysqli、mbstring 和 MariaDB 的 learning 数据库。连接设置见 mysqli 连接设置指南。在新的练习数据库中执行一次 SQL。若表名已被使用,请换一个练习库。建表账户需要 CREATE,应用账户只需相应的 INSERT 权限。
USE learning;
CREATE TABLE employees_insert_demo (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
hire_date DATE NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
MariaDB 用 AUTO_INCREMENT 生成 id。名和姓各最多 50 个字符,入职日是 DATE。创建 database-config.php 和 public 目录,替换示例配置。配置文件应放在 public 之外,并排除在版本管理和公开部署之外。
<?php
return [
'host' => '127.0.0.1',
'username' => 'learning_user',
'password' => 'REPLACE_WITH_YOUR_PRIVATE_PASSWORD',
'database' => 'learning',
'port' => 3306,
];
打开表单并保存员工数据
以 UTF-8 保存为 public/employee-add.php。在练习目录执行 php -S 127.0.0.1:8000 -t public,再打开 http://127.0.0.1:8000/employee-add.php。允许会话 Cookie,PHP 开始标记前不要有 BOM 或任何输出。
<?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('需要 mysqli 和 mbstring 扩展。');
}
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$message = $_SESSION['flash'] ?? '';
unset($_SESSION['flash']);
$errors = [];
$firstName = $lastName = $hireDate = '';
function escapeText($value): string {
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$token = $_POST['csrf'] ?? null;
if (!is_string($token) || !hash_equals($_SESSION['csrf'], $token)) {
http_response_code(403);
exit('请重新打开表单并提交。');
}
$firstName = is_string($_POST['first_name'] ?? null) ? trim($_POST['first_name']) : '';
$lastName = is_string($_POST['last_name'] ?? null) ? trim($_POST['last_name']) : '';
$hireDate = is_string($_POST['hire_date'] ?? null) ? $_POST['hire_date'] : '';
foreach ([$firstName, $lastName] as $name) {
if (!mb_check_encoding($name, 'UTF-8') || $name === '' || mb_strlen($name, 'UTF-8') > 50) {
$errors[] = '姓名字段各需 1 至 50 个有效的 UTF-8 字符。';
break;
}
}
$date = preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/D', $hireDate)
? DateTimeImmutable::createFromFormat('!Y-m-d', $hireDate) : false;
if (!$date || $date->format('Y-m-d') !== $hireDate || $hireDate < '1000-01-01') {
$errors[] = '请输入有效的 YYYY-MM-DD 入职日期。';
}
if ($errors !== []) {
http_response_code(422);
} else {
$link = $stmt = null;
$saved = false;
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');
$stmt = mysqli_prepare($link,
'INSERT INTO employees_insert_demo (first_name, last_name, hire_date) VALUES (?, ?, ?)');
mysqli_stmt_bind_param($stmt, 'sss', $firstName, $lastName, $hireDate);
mysqli_stmt_execute($stmt);
$id = mysqli_insert_id($link);
$saved = mysqli_stmt_affected_rows($stmt) === 1;
if (!$saved) {
throw new RuntimeException('Unexpected affected row count');
}
} catch (Throwable $e) {
http_response_code(500);
error_log('Employee insert failed. Code: ' . $e->getCode());
$errors[] = '保存失败,请查看服务器日志。';
} finally {
if ($stmt instanceof mysqli_stmt) {
mysqli_stmt_close($stmt);
}
if ($link instanceof mysqli) {
mysqli_close($link);
}
}
if ($saved) {
$_SESSION['flash'] = '已保存。新 ID:' . $id;
$_SESSION['csrf'] = bin2hex(random_bytes(32));
header('Location: employee-add.php', true, 303);
exit;
}
}
}
?>
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>员工录入示例</title>
</head>
<body>
<h1>添加员工</h1>
<?php if ($message !== ''): ?><p><?= escapeText($message) ?></p><?php endif; ?>
<?php foreach ($errors as $error): ?><p><?= escapeText($error) ?></p><?php endforeach; ?>
<form action="employee-add.php" method="post">
<input type="hidden" name="csrf" value="<?= escapeText($_SESSION['csrf']) ?>">
<p><label>名 <input name="first_name" maxlength="50" required value="<?= escapeText($firstName) ?>"></label></p>
<p><label>姓 <input name="last_name" maxlength="50" required value="<?= escapeText($lastName) ?>"></label></p>
<p><label>入职日期 <input type="date" name="hire_date" required value="<?= escapeText($hireDate) ?>"></label></p>
<button type="submit">保存</button>
</form>
</body>
</html>
填写虚构的姓名和 2025-03-01。保存成功后,表单会显示新 ID。自动编号可能有间隔。正式应用还应根据需要实施登录、操作授权和 HTTPS。
了解输入验证与预处理 INSERT
浏览器的 required 和 maxlength 用于辅助填写。服务器检查字符串类型、有效的 UTF-8 和 1 至 50 个码点。日期验证要求四位年份且从 1000 年开始,并比较重新格式化后的值,以拒绝 2025-02-30 之类会被自动调整的日期。PHP Manual — DateTimeImmutable::createFromFormat()
VALUES (?, ?, ?) 有三个值占位符。sss 绑定三个字符串。姓名里的单引号作为数据传入,表名和列名则写在 SQL 语句中。SQL 参数需要绑定,表单重新显示时也要对 HTML 特殊字符进行转换。PHP Manual — mysqli_stmt_bind_param() PHP Manual — Prepared statements
执行后立即在同一个连接上调用 mysqli_insert_id()。另查最大 ID 可能读到其他请求的行。此处还检查单行 INSERT 是否恰好影响一行。PHP Manual — mysqli_insert_id() PHP Manual — mysqli_stmt_affected_rows()
检查 CSRF 并在保存后转到 GET
为防止跨站请求伪造(CSRF),使用 hash_equals() 比较表单令牌和会话里的随机值。令牌缺失或不符时,在连接数据库前返回 403。已登录用户的操作权限另行检查。PHP Manual — session_start() PHP Manual — hash_equals()
成功后保存一次性提示、更新令牌,并在输出之前发送 303。刷新随后的 GET 页面不会重发 INSERT。旧标签页需要重新打开表单。若业务禁止重复记录,应使用唯一键或请求标识。PHP Manual — header()
在数据库中验证成功与失败情况
SELECT id, first_name, last_name, hire_date
FROM learning.employees_insert_demo
ORDER BY id DESC LIMIT 5;
通过 SQL 核对姓名、日期和新 ID。无效输入应返回 422,缺少令牌的 POST 应返回 403,二者都不会新增记录。数据库错误返回 500 和通用消息。到限制访问的日志中查看错误编号,结束后按 Ctrl+C 停止服务器。




