我有一个包含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());
我的猜测是“Amaranth grain,cooked”中的逗号是一个问题,但我无法解决。我尝试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
(不同的表只是我希望插入行的不同表格)
答案 0 :(得分:2)
由于逗号,您的查询没有问题。
由于您要将记录插入到不同的表中,因此需要使用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
分开,插入的查询没有问题。
请参阅此处的小提琴:http://sqlfiddle.com/#!2/ec94bc/1
答案 1 :(得分:0)
只要字符串用引号括起来(就像你在这里用单引号一样),那么你可以在字符串中使用逗号。实际的错误可能与$ category似乎是空字符串或null的事实有关,因为它说:
VALUES ('Amaranth grain, cooked', )
确保回显sql查询以确保它完全符合您的预期。
答案 2 :(得分:-1)
您可以使用php函数addslashes或mysql_real_escape_string将斜杠放在每个在mysql中有任何意义的字符之前。