开发者

Inserting multiple rows with loop

开发者 https://www.devze.com 2023-01-04 14:24 出处:网络
Code: for($i = 1; $i <= $arr[\'var\']; $i++) { if($i == $arr[\'var\']): $insert .= \'(\'.$n_id.\', 12)\';

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)
                   VA开发者_运维百科LUES
                   '$insert'") or die(mysql_error());

Why it gives me a SQL syntax error? What am I doing wrong?


You're missing string concatentation in the INSERT statement:

$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 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:

    INSERT INTO `cars` (n_id, auto_id) VALUES $insert
    

tl;dr: remove the 's.


Using backticks (around cars) is incorrect when mixed with single quotes (around $insert), to the best of my knowledge, in mySQL. Pick one or the other - single quotes are probably recommended for standardization.


On General SQL Management it gives this example for an insert into:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消