添加特殊字符时出现MySQL错误,特别是符号,即使使用mysql_real_escape_string()方法也是如此

时间:2011-08-30 22:58:19

标签: php mysql insert special-characters

我正在努力建立一个带有mysql数据库的用户系统。我试图使用以下php代码在表中插入一行:

$UserCreateQueryText = "INSERT INTO  users (
Username, Password, FirstName, LastName, eMail, ID, ClearanceLevel)
VALUES (
" . $User . ", " . $Password . ", " . $FirstName . ", " . $LastName . ", " . $eMailToUse . ", NULL, 1)";

$UserCreateQuery = mysql_query($UserCreateQueryText) or die(" User creation query error: " . mysql_error());

我使用的变量定义如下:

$User = mysql_real_escape_string($_GET["Username"]);
$Password = mysql_real_escape_string($_GET["Password"]);
$FirstName = mysql_real_escape_string($_GET["FirstName"]);
$LastName = mysql_real_escape_string($_GET["LastName"]);
$eMail = mysql_real_escape_string($_GET["eMail"]);

我使用了$ _GET,所以我可以看到变量实际上是正确传递的。

所以,如果我插入一个eMail(example@domain.com),$ UserCreateQueryText的结果将是:

INSERT INTO  users (
Username, Password, FirstName, LastName, eMail, ID, ClearanceLevel)
VALUES (
username, password, Name, LastName, , NULL, 1)

这样就可以清除eMail字段,并且会抛出错误:

User creation query error: 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
' NULL, 1)' at line 4

-Ric Del(foxtailgames.com.mx

1 个答案:

答案 0 :(得分:2)

您需要引用字符串值:

INSERT INTO ... VALUES ('String', 'string', ...)

目前你不是:

INSERT INTO ... VALUES(Foo, Bar@baz.com, ...)

这会产生语法错误。