Home > front end >  PHP repeated results
PHP repeated results

Time:08-10

I'm having hard time with this issue I have multiple queries some data appear in other results...

$query = "SELECT * FROM `hotels`";
$result=mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0) {
    while($row=mysqli_fetch_array($result)) {       
        $hotelname = $row['hotel_name'];

    $queryPhotos="SELECT * FROM hotel_photo WHERE hotel_id = ".$row['id']." ";
        $resultPhotos=mysqli_query($connect,$queryPhotos);
            while($rowPhotos=mysqli_fetch_assoc($resultPhotos)) {
                        $photos[] = array(
                         "imgUrl"   =>  $rowPhotos['img_url'],
                         "hotel_id" =>  $rowPhotos['hotel_id']
                        );
            }
            
    $apiResult[] = array(
            'hotel_name' => $hotelname,
            'hotel_photos' => $photos,
        );
    }


header('Content-type: application/json');
echo json_encode($apiResult, JSON_NUMERIC_CHECK);

}

This is my hotel database enter image description here

and my hotel_photos database enter image description here

Why I'm still seeing 'hotel_id 1' in dubai hotel...? enter image description here

Thank you so much for your help.

CodePudding user response:

You aren't empting the $photos array in every new iteration for a new hotel. Hence, the previous results also exists in the array. You need to fix as below:

<?php

    while($row = mysqli_fetch_array($result)) {       
        $hotelname = $row['hotel_name'];
        $photos = []; // add this line
  • Related