Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda