MySQL语法错误 - 要查询的数组

时间:2011-10-09 00:19:35

标签: php mysql

我有一个从一些测试数据创建的预构建数组,因为我还没有设置一个帖子表单。该数组如下所示:

$ud = array('name' => 'name', 'username' => 'username', 'password' => 'password', 'location' => 'london', 'platform' => 'mobile', 'developer_or_designer' => 'developer', 'tags' => 'hello', 'paypal_email' => 'email@email.com', 'developer_or_client' => 'developer', 'email' => 'email@email.com');

foreach ($ud as $key => $value) {
    $value = mysql_real_escape_string($value);
}

从这个数组中,我尝试通过MySQL查询将数据插入到我的数据库中:

$query = mysql_query("INSERT INTO `Developers` (`Name`,`Email`,`Username`,`Password`,`Location`,`Platform`,`Developer_or_Designer`,`Tags`, `Paypal_Email`) VALUES (" . $ud['name'] . ", " . $ud['email'] . ", " . $ud['username'] . ", " .$ud['password'] . ", " . $ud['location'] . ", " . $ud['platform'] . ", " . $ud['developer_or_designer'] . ", " . $ud['tags'] . ", " . $ud['paypal_email'] . ")") or die(mysql_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 '@email.com, username, password, london, mobile, developer, hello, email@email.com)' at line 1

请告诉我我哪里出错了?

5 个答案:

答案 0 :(得分:1)

您需要在括号中的每个值周围引用

答案 1 :(得分:1)

两件事:

  1. As Jeff notes,你需要在字符串周围添加引号。
  2. 在为它们添加引号之前,您需要将每个字符串传递给mysql_real_escape_sring()

答案 2 :(得分:0)

$query = mysql_query("INSERT INTO `Developers` (`Name`,`Email`,`Username`,`Password`,`Location`,`Platform`,`Developer_or_Designer`,`Tags`, `Paypal_Email`) VALUES ('" . $ud['name'] . "', '" . $ud['email'] . "', '" . $ud['username'] . "', '" .$ud['password'] . "', '" . $ud['location'] . "', '" . $ud['platform'] . "', '" . $ud['developer_or_designer'] . "', '" . $ud['tags'] . "', '" . $ud['paypal_email'] . "')") or die(mysql_error());

尝试一下:)

答案 3 :(得分:0)

从列名称的声音中varchar列类型,所以你需要用引号包装你的值:

$query = mysql_query("INSERT INTO `Developers` (`Name`,`Email`,`Username`,`Password`,`Location`,`Platform`,`Developer_or_Designer`,`Tags`, `Paypal_Email`) VALUES ('" . $ud['name'] . "', '" . $ud['email'] . "', '" . $ud['username'] . "', '" .$ud['password'] . "', '" . $ud['location'] . "', '" . $ud['platform'] . "', '" . $ud['developer_or_designer'] . "', '" . $ud['tags'] . "', '" . $ud['paypal_email'] . "')") or die(mysql_error());

此外,如果值来自用户输入,则应通过mysql_real_escape_string运行每个值以帮助防止SQL注入攻击

答案 4 :(得分:0)

见:

VALUES(“。$ ud ['name']。”,

Nedd:

VALUES('“。$ ud ['name']。”',

对于其他列也是如此(如果不是数字)