Syntax sql error

Asked

Viewed 302 times

0

I’m trying to make an insert in the database but I’m having a syntax problem, I still can’t identify the error.

$sql='INSERT INTO tabela   
    (
        nome, 
        nit, 
        rg, 
        cpf, 
    )
    VALUES';

foreach($dados as $linha_bd)
{
$sql=$sql."('"
'".$linha_bd['nome']."',
'".$linha_bd['nit']."',
'".$linha_bd['rg']."',
'".$linha_bd['cpf']."')";

}

  • 2

    Remove the comma in cpf,, to concatenate strings use .= in place of = which makes a new assignment every turn of the foreach.

  • My dear, I’m in another trouble now, the mistake has changed this time, (SQLinv¡lido: 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 '( '00000439020154036304', '0006660000', 'MARCOS DE ALMEIDA', '08782952833', ' at line 44)

1 answer

1


Remove the comma after Cpf

$sql = 'INSERT INTO tabela(nome, nit, rg, cpf,) VALUES ';
 --------------------------------------------^

The concatenation here is reversed

$sql=$sql."('"'".$linha_bd['nome']."','".$linha_bd['nit']."','".$linha_bd['rg']."','".$linha_bd['cpf']."')";

wrong:

$sql."('"'".$linha_bd['nome']."'
-----^   | 
abriu    |  
         |essa aspa simples ficou da concatenação

To eliminate the php syntax error you can do so:

$sql .= "('{$linha_bd['nome']}'"

Another way to correct syntax error with sprintf, use appropriate parameters for each type of data %s is for strings.

foreach($arr_entrada as $linha_bd){
    $sql .= sprintf("('%s', '%s', '%s', '%s'),", $linha_bd['nome'],$linha_bd['nit'], $linha_bd['rg'], $linha_bd['cpf']);
}
$sql = substr($sql, 0, -1); //remove a ultima virgula se o objetivo é gerar um insert com varios VALUES

phpfiddle - example

  • Thank you my dear, now it’s working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.