我有一个准备好的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)
,但就像我说它会将其作为空字符串插入数据库:(
答案 0 :(得分:1)
正如迈克尔在comment
由于您mysqli
使用了prepare()
&amp; execute()
你最好利用bind_param()
$stmt = $mysqli->prepare("INSERT INTO `in-the-press` (title, `date`, preview, description, image, detailImage, showDetailImage) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param('sssssss', $title, $date, $preview, $description, $image, $detailImage, $showDetailedImage);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
上面只是一个例子,我不知道您的数据库架构/结构是什么样的
故障:
s
表示字符串。d
表示加倍。您可以在上面i
链接中详细了解类型(s
,d
,b
,bind_param
)。