Search code examples
phpmysqlinsertmysql-error-1064

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? What am I doing wrong?


Solution

  • 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.