[英]Inserting multiple rows with loop
Code: 码:
for($i = 1; $i <= $arr['var']; $i++) {
if($i == $arr['var']):
$insert .= '('.$n_id.', 12)';
else:
$insert .= '('.$n_id.', 12),';
endif;
}
$uz = mysql_query("INSERT INTO `cars`
(n_id, auto_id)
VALUES
'$insert'") or die(mysql_error());
Why it gives me a SQL syntax error? 为什么会给我一个SQL语法错误? What am I doing wrong?
我究竟做错了什么?
You're missing string concatentation in the INSERT statement: 您在INSERT语句中缺少字符串连接:
$uz = mysql_query("INSERT INTO `cars`
(n_id, auto_id)
VALUES "
. $insert .") or die(mysql_error());
That's assuming you aren't also having an issue with the trailing comma for tuple support. 假设您对元组支持的结尾逗号也没有任何疑问。
Your query, unexpanded, is this: 您的查询(未展开)是这样的:
INSERT INTO `cars` (n_id, auto_id) VALUES '$insert'
Then, with $insert
expanded, it probably looks something like this: 然后,随着
$insert
扩展,它可能看起来像这样:
INSERT INTO `cars` (n_id, auto_id) VALUES '(1,12),(2,12),(3,12)';
Those single quotes ( '
) around the data list should not be there, as single quotes delimit strings. 数据列表周围的单引号(
'
)不应存在,因为单引号分隔字符串。
Instead, you want: 相反,您想要:
INSERT INTO `cars` (n_id, auto_id) VALUES (1,12),(2,12),(3,12);
Re-collapsing that into your PHP, you end up with: 将其重新打包到您的PHP中,最终得到:
INSERT INTO `cars` (n_id, auto_id) VALUES $insert
tl;dr: remove the '
s. TL; DR:删除
'
秒。
Using backticks (around cars) is incorrect when mixed with single quotes (around $insert), to the best of my knowledge, in mySQL. 据我所知,在MySQL中,使用反引号(在汽车周围)与单引号(在$ insert左右)混合时是不正确的。 Pick one or the other - single quotes are probably recommended for standardization.
选择一个或另一个-建议使用单引号进行标准化。
On General SQL Management it gives this example for an insert into: 在常规SQL管理中,它给出了插入以下示例:
INSERT INTO [table]
( [field1], [field2], [field3] ) VALUES
( '[value1.1]', '[value1.2]', '[value1.3]' ),
( '[value2.1]', '[value2.2]', '[value2.3]' ),
( '[value3.1]', '[value3.2]', '[value3.3]' ),
etc.
You might have some syntax problems. 您可能有一些语法问题。 I recommend printing out
我建议打印出来
"INSERT INTO `cars`
(n_id, auto_id)
VALUES
'$insert'"
to see what you are sending. 看看你发送的是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.