Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
My SQL request work in SQL but not in PHP

I'm trying to make an unique request to insert multiple element in my database to not make multiple request.

Here is my "generated" request, which work in SQL (tested in PHPMYADMIN).

INSERT INTO my_table (id, user) VALUES (1,2), (3,4)

Generated by this code.

$query = 'INSERT INTO my_table (id, user) VALUES ';

$data = array(
    array(1, 2),
    array(3, 4)
);

$request = '';

foreach($data as $data)
{
    $request .= '(' . implode(',', $data) . '), ';
}
$request = substr($request, 0, -2);

//Insert in DB
$req = $db->prepare($request);
$req->execute();

But I get this error in PHP

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 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 '1,2), (3,4)' at line 1 in testfonction.php:47 Stack trace: #0 testfonction.php(47): PDO->exec('(1,2), (3,4)') #1 structure_gc.php(32): require('/v...') #2 index.php(22): require('/v...') #3 {main} thrown in testfonction.php on line 47

Do you know why this request does not work when I try to use it with PHP ? Thanks !

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You have two variables: $request and $query. I propose:

$query = 'INSERT INTO my_table (id, user) VALUES ';

$data = [[1, 2],
         [3, 4]];

foreach($data as $data)
{
    $query .= '(' . implode(',', $data) . '), ';
}

$query = substr($query, 0, -2);

$stmt = $db->prepare($query);
$stmt->execute();

That is; Just one variable. This way you also include the first bit in the query you execute.

Note that in future queries, where data could potentially come from user input, it would be wise to use parameter binding.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda