我的数据库不存储具有特定字符的$title。我能做什么?在我的 php 代码下面:
<?php
require "init.php";
$user_name = $_POST["user_name"];
$title = $_POST["title"];
$author = $_POST["author"];
$urlImage = $_POST["urlImage"];
preg_match("/^['p{L}'p{N} '.-]+$/", $title);
$sql_query = "insert into user_info_book values('$user_name', '$title', '$author', '$urlImage');";
?>
提前谢谢你
特殊字符可能会破坏您的 SQL 查询,因此要解决此问题,请使用预准备语句或使用 mysqli_real_escape_string()
函数。
mysqli_real_escape_string()
函数需要两个参数,第一个是连接对象,第二个是要转义的字符串,下面是一个示例
$title = mysqli_real_escape_string($conn, $title);
但是,更好的方法是改用预准备语句。下面给出了一个例子
if ($stmt = $conn->prepare("INSERT INTO user_info_book VALUES (?, ?, ?, ?)")) {
$stmt->bind_param("ssss", $user_name, $title, $author, $urlImage);
$stmt->execute();
$stmt->close();
} else {
// echo mysqli_error($DB_H); // Errors should only be shown in development
}
代码中任何位置都$conn
是已创建的连接对象。
- http://php.net/manual/en/mysqli.real-escape-string.php
- http://php.net/manual/en/mysqli.prepare.php
$title = mysql_real_escape_string($title);
mysql_real_escape_string() 转义字符串中的特殊字符以在 SQL 语句中使用。