Update table using PDO with 2 foreachs

0

Hello,

public function update($idsimages, $dir_images)
{
try {

   $stmt = $this->db->prepare("UPDATE images SET
   dir_images = :dir_images
   WHERE id_images = :id_images");


foreach ($idsimages as $idsimage) { 


     foreach ($dir_images as $item){

        $stmt->bindParam(":id_images", $idsimage);
        $stmt->bindParam(":dir_images", $item); 

     } //end foreach dir_images 

    $stmt->execute();

} // end foreach idsimages


   return true;
  }
  catch(PDOException $e) {
  echo $e->getMessage(); 
  return false;
 }
}

The%% variables (contains ids that will be updated) and $idsimages (contains urls) are arrays, the two arrays have the same number of keys

It turns out that it is not doing the upcoming, I put echo in the two variables and after the submit it repeatedly prints, several times, the images and ids.

I tried to change foreachs several times and also insert if isset not to repeat, but I could not

PRINTS

print_r ($ idsimages);

Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 )

print_r ($ dir_images);

Array ( [0] => uploads/images/image5.jpg [1] => uploads/images/image6.jpg [2] => uploads/images/image7.jpg [3] => uploads/images/image8.jpg)

If you insert echo into the function:

$stmt->bindParam(":id_images", $idsimage);
echo $idsimage;
$stmt->bindParam(":dir_images", $item); 
echo $item;

returns:

5 image5.PNG 5 image6.jpg 5 image6.jpg 5  image6.jpg
6 image5.PNG 6 image6.jpg 6 image6.jpg 6 image6.jpg
7 image5.PNG 7 image6.jpg 7 image6.jpg 7 image6.jpg
8 image5.PNG 8 image6.jpg 8 image6.jpg 8 image6.jpg
    
asked by anonymous 29.03.2016 / 21:41

1 answer

0

It seems better to change the logic, ie to perform the update inside the internal foreach and not as described in the comment.

foreach ($idsimages as $idsimage) { 
   foreach ($dir_images as $item){
      if(!$stmt->execute(array(':id_images' => $idsimage, ':dir_images' => $item))){
         echo '<pre>';
         print_r($stmt->errorInfo());
      }
    } //end foreach dir_images 
} 
    
29.03.2016 / 21:56