【发布时间】:2014-09-19 04:10:57
【问题描述】:
我有一个准备好的 mysqli 插入语句,但是当我尝试用引号或双引号插入数据时,我收到了这个错误:Prepare failed: (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 'Ask me in six months.' We don’t have six months to wait," he said. "I have a p' at line 1
当我在尝试插入的文本周围使用mysqli_real_escape_string 时,它会作为空数据插入到我的数据库中。
有没有更好的方法来处理单引号或双引号?还是我的代码有问题?
$connection = new mysqli("localhost", "username", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!($stmt = $connection->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES ('" . $title . "', '" . $date . "', '" . $preview . "', '" . $description . "','" . $image . "', '" . $detailImage . "', " . $showDetailedImage . ")"))) {
echo "Prepare failed: (" . $connection->errno . ") " . $connection->error;
}else{
$stmt->execute();
echo 'Press has been added <br>';
}
我尝试过使用mysqli_real_escape_string($title), mysqli_real_escape_string($preview) & mysqli_real_escape_string($description),但就像我说的它会将其作为空字符串插入数据库:(
【问题讨论】:
-
既然你使用的是
prepare()/execute(),你也应该使用be usingbind_param()。这样做完全避免了这个引用问题,同时也确保了 SQL 注入的安全性。 -
我有点明白,但我不明白这个:
$stmt->bind_param('sssd', $code, $language, $official, $percent);sssd是什么意思?