2

我有一个包含 3 列的表:idfood_namecategory。例如,我有$food_name = "Amaranth grain, cooked"(有一个逗号)和category = "Cereals".

我无法插入值并出现以下错误:

Could not connect: 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 ')
      VALUES ('Amaranth grain, cooked', )' at line 1

我的 SQL 查询是:

$results1 = mysql_query("
  INSERT INTO " . $table . " (food_en, category)
  VALUES ('" . $food_name . "', '" . $category . "')"
)or die(mysql_error());

我的猜测是“Amaranth grain,cooked”中的逗号有问题,但我无法解决。我试过了str_replace(',', '\,', $food_name)mysql_real_escape_string()但没有成功。我可能没有正确使用它们。

提前致谢。

编辑:我确实回显了 $category,它既不是 null 也不是空的(值是'谷物')。

当我打印而不是使用 mysql_query 时,我得到:

INSERT INTO calories (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta')
      INSERT INTO carbohydrates (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta')
      INSERT INTO fats_and_fatty_acids (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta')
      INSERT INTO protein_and_amino_acids (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta')
      INSERT INTO vitamins (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta')
      INSERT INTO minerals (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta')
      INSERT INTO sterols (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta')
      INSERT INTO other (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta')Could not connect: 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 ')
      VALUES ('Amaranth grain, cooked', )' at line 1

(不同的表只是我希望将行插入的不同表)

4

3 回答 3

3

由于逗号,您的查询没有问题。由于您要将记录插入到不同的表中,因此您需要使用query-separatoror分隔每个查询query-delimiter

INSERT INTO calories (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta'); <-- Notice semi colon at end of query

INSERT INTO carbohydrates (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta'); <-- Notice semi colon at end of query

INSERT INTO fats_and_fatty_acids (food_en, category)
      VALUES ('Amaranth grain, cooked', 'Cereal Grains and Pasta'); <-- Notice semi colon at end of query

在示例小提琴中,我用 a 分隔每个查询,semi-colon并且查询插入时没有问题。

在此处参考小提琴:http ://sqlfiddle.com/#!2/ec94bc/1

于 2014-08-12T09:17:01.007 回答
0

只要字符串用引号括起来(就像你在这里用单引号一样),那么你的字符串中就可以有逗号。实际错误可能与 $category 似乎是空字符串或 null 的事实有关,因为它说:

VALUES ('Amaranth grain, cooked', )

确保您回显了 sql 查询,以确保它完全符合您的预期。

于 2012-05-18T20:42:39.390 回答
-1

您可以使用 php 函数 addlashes 或 mysql_real_escape_string 将斜杠放在 mysql 中每个有意义的字符之前。

于 2014-08-11T18:52:19.543 回答