$unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
用户可以输入诸如 value'); DROP TABLE table;-- 之类的内容,使查询变为:
1
INSERT INTO `table` (`column`) VALUES('value'); DROPTABLEtable;--')
这可能导致数据库数据被篡改、泄露或删除等严重后果。
实现步骤
使用PDO(适用于任何受支持的数据库驱动)
1 2 3 4 5 6
$stmt = $pdo->prepare('SELECT * FROM users WHERE name = :name'); $stmt->execute([ 'name' => $name ]);
foreach ($stmtas$row) { // Do something with $row }
使用MySQLi(适用于MySQL)
PHP 8.2+
1 2 3 4
$result = $db->execute_query('SELECT * FROM users WHERE name = ?', [$name]); while ($row = $result->fetch_assoc()) { // Do something with $row }
PHP 8.1及以下
1 2 3 4 5 6 7
$stmt = $db->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies variable type 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // Do something with $row }