我有一个3列的表:id、food_name和category。例如,我有$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());我猜“阿马兰斯谷物,熟食”中的逗号是个问题,但我解决不了。我尝试了str_replace(',', '\,', $food_name)和mysql_real_escape_string(),但没有成功。我可能没有正确地使用它们。
提前谢谢。
编辑:我确实回显了$category,它既不为空也不为空(值为“谷物”)。
当我打印而不是使用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(不同的表只是不同的表,我希望将行插入到其中)
发布于 2014-08-12 09:17:01
查询中没有任何问题,因为有逗号。由于要将记录插入到不同的表中,因此需要使用query-separator或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在这个示例中,我用一个semi-colon将每个查询分隔开,并且没有问题地插入了查询。
请参阅Fiddle此处:http://sqlfiddle.com/#!2/ec94bc/1
发布于 2012-05-18 20:42:39
只要字符串被用引号包装(就像这里的单引号一样),那么您就可以在字符串中使用逗号。实际错误可能与以下事实有关:$category似乎是空字符串或空字符串,因为它说:
VALUES ('Amaranth grain, cooked', )确保您响应了sql查询,以确保所有这些都与您预期的完全相同。
发布于 2014-08-11 18:52:19
您可以使用php函数addslashes或mysql_real_escape_string将斜杠放在mysql中任何有意义的字符前面。
https://stackoverflow.com/questions/10659397
复制相似问题