PHP PDO错误1064
问题描述:
我有一个小问题,当我提出我的论坛数据我得到这个错误:PHP PDO错误1064
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 'Explain, Country, IP, Hostname)
我的代码是这样的:
$STH = $DBH->prepare("INSERT INTO `Applications` (`Username`, `Email`, `Age`, `Reason`, `Explain`, `Country`, `IP`, `Hostname`) VALUES ($username, $email, $age, $reason, $explain, $country, $ip, $hostname)"); $STH->execute();
我不能似乎找到了问题。
答
你没有正确使用PDO,创造大量的SQL注入的问题。放入SQL的值需要正确转义。
的placeholder method使然做这种方式:
$STH = $DBH->prepare("INSERT INTO `Applications` (`Username`, `Email`, `Age`, `Reason`, `Explain`, `Country`, `IP`, `Hostname`) VALUES (:username, :email, :age, :reason, :explain, :country, :ip, :hostname)");
$STH->bindParam(':username', $username);
$STH->bindParam(':email', $email);
... (remaining columns) ..
$STH->bindParam(':hostname', $hostname);
$STH->execute();
这是为了确保你的SQL是properly escaped的最佳途径。
这是奇怪的。从显示的消息,它看起来像这个问题是在解释 - 这是一个保留字,所以它必须被包裹成'backtick'符号。然而它被封装在显示的查询中。 – raina77ow 2013-04-05 20:48:22
是的,你要引用所有这些值(不是'$ username',但'$ DBH->报价($用户名)') – raina77ow 2013-04-05 20:50:02
请不建议使用'$ DBH->报价()直接'。 – tadman 2013-04-05 20:51:59