简体   繁体   中英

php mysql search for room availability need help for better sql query

my mysql database is:

BOOKING_ID, FROM_DATE, TO_DATE,
R1,R2,R3,R4,R5,R6,R7,R8,R9,R10,R11,R12,R13,R14,R15,R16,R17 

where R1=room1...R17=room17, if room1 booked, than R1 will set to 1.

below is my current working sql query,i never learn sql before, i need help for better sql query!

for($room=1;$room<=$total_room;$room++)
{
  $result = mysql_query("
    SELECT COUNT(`BOOKING_ID`) AS num 
    FROM $search_for_db_table
    WHERE (    (FROM_DATE <= $search_to_date   AND TO_DATE >= $search_to_date )
            OR (FROM_DATE <= $search_from_date AND TO_DATE >= $search_from_date)
            OR (FROM_DATE >= $search_from_date AND TO_DATE <= $search_to_date )
          ) 
      AND R$room=1 
  ") or die(mysql_error());


  $row = mysql_fetch_assoc($result);

  $numUsers[$room] = $row['num']; 
}

//$numUsers[$room]=="0" means room available for booking...

Please learn more about designing your database. Instead of using a column for every room just use multiple tables to get the information, that way it is much more organized.

So make a table called 'rooms' in that table you make let's say 15 rows. With a column 'room_number' for the room number and a column 'available' with your 1 or 0. A simple SQL statement then show what rooms are available.

Then you can use:

SELECT 'room_number' FROM rooms WHERE available = '0'

Yet, if you don't like to modify this "ugly" data model you can go with 1 query and not with 17 queries. Simply use SUM( for all 17 fields. So the SELECT clause would be:

SELECT SUM(R1) AS sr1, SUM(R2) AS sr2, ...., SUM(R17) as sr17
FROM
WHERE [only with the date restictions]

Then if the respective column of the result set is 0 then it is available, otherwise it is occupied.

But again, this is an "ugly" solution for the wrongly designed data model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM