我将旧脚本转换为符合MySQLi并遇到问题...
$link = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$myQuery = "INSERT INTO table (name, description) VALUES ('$name', '$description')";
if (!mysqli_query($link, $myQuery)) {
printf('Error');
} else {
printf('Success');
}
mysqli_close($link);
这很好,没有错误。但是当我添加mysqli_real_escape_string()时,我收到一个错误......
$link = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$myQuery = "INSERT INTO table (name, description) VALUES ('$name', '$description')";
$myQuery = mysqli_real_escape_string($link, $myQuery);
if (!mysqli_query($link, $myQuery)) {
printf('Error');
} else {
printf('Success');
}
mysqli_close($link);
这会返回错误:
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 靠近' \#39; TestName \',\' TestDescription \'在第1行
我错过了一些简单的东西吗?行情?
答案 0 :(得分:3)
这一行:
$myQuery = mysqli_real_escape_string($link, $myQuery);
这是不对的。
您需要使用$name
变量而不是$myQuery
变量。这就是需要转义而不是整个查询本身。
$myQuery = mysqli_real_escape_string($link, $name);
但是,^ $myQuery
应该替换为用于插入的每个变量。
您的查询应该更像这样:
$name = "TestName";
$description = "TestDescription";
$name = mysqli_real_escape_string($link, $name);
$description = mysqli_real_escape_string($link, $description);
$myQuery = "INSERT INTO `table` (name, description) VALUES ('$name', '$description')";
if (!mysqli_query($link, $myQuery)) {
printf('Error');
} else {
printf('Success');
}
诺塔:
您可能希望使用mysqli
with prepared statements或PDO with prepared statements,使用它们更安全。
另外,只是为了争论; table
应该是MySQL reserved word,应该是实际的表名,并且需要进行转义:
$myQuery = "INSERT INTO `table`
mysqli
预备声明的示例:
$variable_1 = "Text";
$variable_2 = "More text";
$stmt = $link->prepare("INSERT INTO table_name
(column_1, column_2)
VALUES (?,?)");
$stmt->bind_param('ss', $variable_1, $variable_2);
$stmt->execute();
s
用于字符串PDO准备声明的一个例子:
$dbh = new PDO('mysql:host=localhost;dbname=your_DB', $user, $pass);
$var_1 = "Text";
$var_2 = "More text";
$stmt = $dbh->prepare("INSERT INTO table_name
(column_1, column_2)
VALUES (:var_1,:var_2)");
$stmt->execute(array(':var_1' => $var_1, ':var_2' => $var_2));