当我使用带有撇号的文本时,查询不起作用。
例句:这是本的聚会。
这是我使用的函数:
function text_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
这是html:
<textarea name="text" rows="20" cols="89"></textarea>
php脚本:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["text"])) {
$errors[] = "There is no text";
} else {
$text = text_input(mysqli_real_escape_string($con, $_POST['text']));
}
if(empty($errors) === true){
mysqli_query($con, "INSERT INTO texts (text) VALUES ('$text')");
exit();
}
你需要在所有其他事情之后做mysqli_real_escape_string
。否则,stripslashes将删除您刚刚加入转义的斜杠。
:
$text = mysqli_real_escape_string($con, text_input($_POST['text']));
你对stripslashes()
和htmlspecialchars()
的使用表明了很大的混淆。
-
trim()
是代码中唯一属于text_input()
的函数。 -
stripslashes()
几乎不应该被使用。相反,您应该使用为特定任务量身定制的函数转义输出。在文本输入中使用stripslashes()
只会在用户实际需要使用反斜杠时引起混淆。 -
htmlspecialchars()
应该是生成html输出之前使用的最后一个函数。如果您使用HTML转义所有内容,那么当您需要将数据库用于其他目的时,就会遇到麻烦。我见过很多在地址中带有HTML字符引用(&#xx;
)的物理邮件,甚至是手写的邮件! -
mysqli_real_escape_string()
应该是MySQL查询前使用的最后一个函数
换句话说:
$text = trim ($_POST['text']);
$text_h = htmlspecialchars ($text);
$text_m = mysqli_real_escape_string ($con, $text);
...
mysqli_query ($con, "INSERT INTO texts (text) VALUES ($text_m)");
...
echo "<p>'$text_h' added to database.n";