我正在使用phpmyadmin
为作业创建一个表格,我正在试图弄清楚如何防止SQL注入,但我得到了一些奇怪的错误,我不知道为什么。我正在尝试使用quote
方法来修复它,但它无法正常工作。这是我的代码
try {
$conn = new PDO("mysql:dbname=*removed*;host=*removed*", "*removed*", "*removed*");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$firstName = $conn->quote($_POST["first_name"]);
$lastName = $conn->quote($_POST["last_name"]);
$house = $conn->quote($_POST["house"]);
$sql = "INSERT INTO my_table (last_name, first_name, house)
VALUES ('$lastName', '$firstName', '$house')";
$conn->exec($sql);
echo "<h3 id=\"success\">New entry successfully created.</h3>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
我查看了我正在使用的教科书,它说使用$db->quote($_POST["var_name"]);
来清理数据,这正是我所做的,但由于某种原因,它不适合我。
编辑:我收到的错误消息说明了这一点:
"INSERT INTO my_table (last_name, first_name, house) VALUES (''Allen'', ''Barry'', 'House1')
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Allen'', ''Barry'', 'House1')' at line 2
知道为什么吗?