AJAX 数据库
核对前端下拉框 onchange 触发 AJAX 查询、PHP 接收整型 ID 查询 Websites 表并返回 HTML 表格的完整链路及参数化防注入改进。
学完这一章,你能够
- 核对前端下拉框 onchange 触发 AJAX 查询、PHP 接收整型 ID 查询 Websites 表并返回 HTML 表格的完整链路及参数化防注入改进。
AJAX 与数据库交互架构及表结构
AJAX 可让前端界面按用户选择异步查询后端数据库并实时渲染结果,无需整页刷新。经典案例基于包含 `id`、`name`、`url`、`alexa`、`country` 五列的 `Websites` 表,用户从下拉框选择站点后即时显示详情表格。
示例表内置 5 条记录(ID 1 至 5,含 Google、淘宝、微博、Facebook 等站点信息)。来源页附带的 `websites.sql` 下载链接已按停采约束登记在私有附件清单中且未发起网络请求;本站离线实测在 PHP 8.4.27 SQLite 内存库中独立重建同构 `Websites` 表以验证完整查询逻辑。
前端 HTML 下拉触发与 showSite() 流程
前端页面中 `<select onchange="showSite(this.value)">` 提供 5 个站点选项,选中变更后调用 `showSite(str)`:先检查是否选中有效值(为空则清空 `#txtHint` 并返回);随后创建 `XMLHttpRequest` 对象、注册 `onreadystatechange` 回调更新 `#txtHint`,并把下拉选项值作为查询参数 `q` 拼入 `getsite_mysql.php?q=` 异步发送。来源页面的内联演示 `<script>`、`<form>`、`<select>` 及 6 个 `<option>` 元素均已静态登记且不执行。
PHP 后端查库渲染与参数化防注入实测
服务端 `getsite_mysql.php` 先用 `intval($_GET['q'])` 将输入转为整数并在为空时返回提示 `请选择一个网站`;随后连接数据库、设定 `utf8` 字符集防中文乱码、按 `id` 查询记录,并将字段拼装成 `<table border='1'>` 返回给前端占位符。生产代码应使用 PDO 预处理语句(`WHERE id = :id`)而非拼接 SQL 字符串,同时对输出单元格执行 `htmlspecialchars()` 转义。本站 PHP 8.4.27 实测验证:`q='1'` 与 `q='4'` 分别输出含 `Google` 与 `微博`/`CN` 的 2 行表格;空值、`0` 与非数字 `abc` 均被拦截返回 `请选择一个网站`;注入串 `1 OR 1=1` 在严格参数绑定下返回 `0` 行(经 `intval` 强转仅查 ID=1 的 `1` 行),不存在的 `id=999` 返回仅有表头的 0 数据行表格。
运行 PHP 8.4 AJAX 数据库 ID 查询、空值拦截与防注入表格输出实测
展开查看收起
<?php
declare(strict_types=1);
$cases = [];
function add_case(array &$cases, string $name, mixed $expected, mixed $actual): void {
$cases[] = [
'name' => $name,
'passed' => ($actual === $expected),
'expected' => $expected,
'actual' => $actual,
];
}
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE Websites (id INTEGER PRIMARY KEY, name TEXT, url TEXT, alexa INTEGER, country TEXT)');
$ins = $pdo->prepare('INSERT INTO Websites (id, name, url, alexa, country) VALUES (?, ?, ?, ?, ?)');
foreach ([
[1, 'Google', 'https://www.google.com/', 1, 'USA'],
[2, '淘宝', 'https://www.taobao.com/', 13, 'CN'],
[3, '蓝色天空网', 'https://www.mbsky.com/', 4689, 'CN'],
[4, '微博', 'https://weibo.com/', 20, 'CN'],
[5, 'Facebook', 'https://www.facebook.com/', 3, 'USA'],
] as $row) {
$ins->execute($row);
}
$handleGetSite = static function (PDO $db, ?string $rawQ): string {
$q = ($rawQ !== null) ? intval($rawQ) : 0;
if (empty($q)) {
return '请选择一个网站';
}
$stmt = $db->prepare('SELECT id, name, url, alexa, country FROM Websites WHERE id = :id');
$stmt->bindValue(':id', $q, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$out = "<table border='1'><tr><th>ID</th><th>网站名</th><th>网站 URL</th><th>Alexa 排名</th><th>国家</th></tr>";
foreach ($rows as $r) {
$out .= '<tr>'
. '<td>' . htmlspecialchars((string) $r['id'], ENT_QUOTES, 'UTF-8') . '</td>'
. '<td>' . htmlspecialchars((string) $r['name'], ENT_QUOTES, 'UTF-8') . '</td>'
. '<td>' . htmlspecialchars((string) $r['url'], ENT_QUOTES, 'UTF-8') . '</td>'
. '<td>' . htmlspecialchars((string) $r['alexa'], ENT_QUOTES, 'UTF-8') . '</td>'
. '<td>' . htmlspecialchars((string) $r['country'], ENT_QUOTES, 'UTF-8') . '</td>'
. '</tr>';
}
$out .= '</table>';
return $out;
};
// Case 1: Lookup by valid integer ID returns formatted HTML table
$html1 = $handleGetSite($pdo, '1');
$html4 = $handleGetSite($pdo, '4');
add_case(
$cases,
'websites_table_lookup_by_id',
[
'id1_has_google' => true,
'id1_tr_count' => 2,
'id4_has_weibo' => true,
'id4_has_cn' => true,
],
[
'id1_has_google' => str_contains($html1, '<td>Google</td>'),
'id1_tr_count' => substr_count($html1, '<tr>'),
'id4_has_weibo' => str_contains($html4, '<td>微博</td>'),
'id4_has_cn' => str_contains($html4, '<td>CN</td>'),
]
);
// Case 2: Empty or non-numeric ID returns prompt without querying DB
add_case(
$cases,
'empty_or_invalid_id_guard',
[
'empty' => '请选择一个网站',
'zero' => '请选择一个网站',
'alpha' => '请选择一个网站',
],
[
'empty' => $handleGetSite($pdo, ''),
'zero' => $handleGetSite($pdo, '0'),
'alpha' => $handleGetSite($pdo, 'abc'),
]
);
// Case 3: Parameterized query & intval() block SQL injection payload
$sqliHtml = $handleGetSite($pdo, '1 OR 1=1');
$strictStmt = $pdo->prepare('SELECT COUNT(*) FROM Websites WHERE id = :id');
$strictStmt->execute([':id' => '1 OR 1=1']);
$strictCount = (int) $strictStmt->fetchColumn();
add_case(
$cases,
'parameterized_query_blocks_sqli',
['intval_handler_data_rows' => 1, 'strict_string_param_rows' => 0],
['intval_handler_data_rows' => substr_count($sqliHtml, '<tr>') - 1, 'strict_string_param_rows' => $strictCount]
);
// Case 4: Non-existent numeric ID produces header-only table (0 data rows)
$missingHtml = $handleGetSite($pdo, '999');
add_case(
$cases,
'missing_id_empty_table_rows',
['header_only_tr_count' => 1, 'td_count' => 0],
['header_only_tr_count' => substr_count($missingHtml, '<tr>'), 'td_count' => substr_count($missingHtml, '<td>')]
);
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
预处理语句能形成纵深防御,避免后续修改字段类型(如改为字符串键)时引入注入风险;htmlspecialchars 则可防止数据库内容包含 HTML 特殊字符时在前端 innerHTML 触发 XSS。