0

I was wondering if it was possible to run a query inside a while loop which is used to display the content of a SQL table.

Here is the code if I'm not clear enough :

$sql="SELECT * FROM hotels WHERE rooms>0";
                        $req=$db->query($sql);

                        while($row=$req->fetch()){
                           //The second query to check how many place is left
                            $req2=$db->query('SELECT COUNT(*) FROM people WHERE idhotels='.$row["idhotels"].';');
                            echo "hey".$req2;
                            $left_rooms= $row["rooms"] -$req2;
                            echo '<option value="'.$row["idhotels"].'">'.$row["name_hotel"].' ('.$left_rooms.' rooms left)</option>';

                        }

What I'm trying to do here, is to display a list of hotels with the number of rooms left. The problem is I have to count how many rooms are taken before displaying the number of rooms left, hence the second request.

My code obviously doesn't work, but I can't figure out why. Can someone help me ?

Many thanks !

1
  • you should show us both table data Commented Jan 17, 2017 at 8:40

2 Answers 2

2

Why not using a join and a group by so you only have one query ?

$sql="SELECT h.idhotels,h.name_hotel,count(*) FROM hotels h inner join people p on h.idhotels = p.idhotels WHERE h.rooms>0 group by h.idhotels,h.name";
while($row=$req->fetch()){
    // Here do whatever you want with each row
}
Sign up to request clarification or add additional context in comments.

2 Comments

It works ! I'm not used to JOIN request, but I guess I have to give a try sometimes, thank you !
You welcome. Yes, you have to. It'll save you time and performance
0

Have you tried to calculate your left rooms in the database with a joined query like:

SELECT rooms - COUNT(*) AS left_rooms FROM hotels h WHERE rooms > 0 JOIN people p ON (p.idhotels = h.idhotels) GROUP BY h.idhotels, h.name ORDER BY left_rooms ASC;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.