sql语法中的php mysqli转义字符串错误

标签 php mysql sql mysqli mysql-real-escape-string

<分区>

我正在尝试转义从表单发布的字段。通过注释掉对字符串进行转义的代码,我可以成功地插入到 SQL 数据库中。

收到的错误是:

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 '\"test\",\"0123456789\",\"test@test.com\",\"1\",\"1\",\"fgsdfdfndfndfndfndfndfn\' at line 1

这是我使用的代码:

$Name= $_POST['fullname'];
$Phone = $_POST['phone'];
$email = $_POST['email'];
$inBuilding = $_POST['inbuilding'];
$floor = $_POST['floor'];
$inRoom = $_POST['inroom'];
$majorDescription = $_POST['majorcategory'];
$description = $_POST['desc'];

$query = "INSERT INTO `problem`.`reports` (`Name`, `PhoneNumber`, `EmailAddress`, `inBuilding`, `inRoom`, `Description`, `MajorDescription`) VALUES (";
$query .= '"' . $Name. '","' . $Phone . '","' . $email . '","' . $inBuilding . '","' . $inRoom . '","' . $description . '","' . $majorDescription . '");';


$query = mysqli_real_escape_string($connect, $query);

我也试过:

$query = mysqli_escape_string($connect, $query);

同样的错误。

根据关于堆栈溢出的其他示例,我将 INSERT INTO 代码更改为以下内容:

$query = "INSERT INTO `problem`.`reports` (Name, PhoneNumber, EmailAddress, inBuilding, inRoom, Description, MajorDescription) VALUES ('$Name', '$Phone', '$email', '$inBuilding', '$inRoom', '$description', '$majorDescription')");

这段代码给了服务器 500 错误。

MySQL 已完全更新。

感谢任何帮助!

MikeW 的解决方案奏效了。还意识到我在打开数据库之前试图转义字符串,使 mysqli_real_escape_string 返回 null。先连接数据库,($connect= new connect("server","user","password");)解决了这个问题。希望这会帮助其他遇到同样问题的人。

最佳答案

您应该使用单引号,而不是双引号。此外,mysqli_real_escape_string() 应该在每个变量上调用,而不是在整个查询上调用。你应该得到这样的东西:

$Name= mysqli_real_escape_string($connect, $_POST['fullname']);
// more variables, similarly escaped.

$query = "INSERT INTO `problem`.`reports` (`Name`, `PhoneNumber`, `EmailAddress`, `inBuilding`, `inRoom`, `Description`, `MajorDescription`) VALUES (";
$query .= "'$Name','$Phone','$email','$inBuilding','$inRoom','$description','$majorDescription')";

但是,对于这种查询,您应该考虑使用准备好的语句。

关于sql语法中的php mysqli转义字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21394423/

相关文章:

php - PDO:在哪里声明数据库连接?

php - 导入 LOAD DATA INFILE 时将我的 php 变量连接到 csv 数据

mysql - 如何导出 SQL 数据库

mysql - 获取MySQL数据库前N行的运行频率分布

sql - 在 SQL 中将两列值显示为两行

sql - PostgreSQL - 按数组排序

PHP FTP 递归目录列表

php - 在 mysql 中使用条件更新记录

mysql - 在不使用自连接的情况下显示详细信息

mysql - 为什么这个 MySQL 语句不起作用?