Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP repeated results

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading