sql >> Base de Datos >  >> RDS >> Mysql

Insertos múltiples con PDO

Varias cosas:

  1. Elimine la segunda declaración de preparación dentro de for bucle
  2. Agregue parámetros enlazados en VALUES() de sentencia sql
  3. Indexar las $images matriz con for iterador de bucle o use foreach

Ver for bucle:

$stmt = $this->db->prepare("INSERT INTO images (category_id, dir_image) 
                            VALUES (:category_id, :dir_image)");

$stmt->bindParam(":category_id" ,$lastId); 
$stmt->bindParam(":dir_image", $image);
for ($i = 0; $i < count($images); $i++){
    $image = $images[$i];
    $stmt->execute();
} 

Alternativamente con foreach bucle (asumiendo una matriz unidimensional) :

$stmt = $this->db->prepare("INSERT INTO images (category_id, dir_image) 
                            VALUES (:category_id, :dir_image)");

$stmt->bindParam(":category_id", $lastId); 
$stmt->bindParam(":dir_image", $item);
foreach ($images as $item){
    $stmt->execute();
}