Having created an array of values using a MySQL query, I need to check if they are all at least equal to a given value. This is for checking room availability in a hotel.
First I do the the MySQL query:
foreach( $datearray as $value ) {
$query_avail = "SELECT cupo, ex_cupo.room_id FROM ex_cupo JOIN ex_rooms ON ex_cupo.room_id=ex_rooms.room_id AND ex_rooms.room_id = '$room_id' AND dt = '$value'";
$avail = mysql_query($query_avail, $MySQL_extranet) or die(mysql_error());
$row_avail = mysql_fetch_assoc($avail);
$availresult[] = $row_avail['cupo'];
}
"Cupo" is the number of rooms available for a given date, so $availresult will be an array of the number of rooms available across a range of dates.
Now if someone wants to book (say) 2 rooms for those dates, I need to ensure that each value in the array is at least 2. For example, if there are 5 dates in the range and they are 2, 2, 1, 2, 2, I need to return false, but if they are 2, 2, 2, 2, 2 or 2, 2, 3, 2, 2, I need to return true.
How do I do that? (I hope I explained it well enough.)
Obviously the choice of 2 is just an example. It will normally be a variable called $numrooms.
Add a WHERE cupo > 2
to your SQL code. Have the database give you only the results you want, rather than walking through the results to check that cupo>2 yourself.
If you need to be able to change it, use a parametrized query. See http://php.net/manual/en/security.database.sql-injection.php for details.
$testArray = array(2,2,2,2,1,2);
$valid = array_reduce(
$testArray,
function ($match, $value) {
return $match && ($value >= 2);
},
TRUE
);
var_dump($valid);
EDIT
How to pass $numrooms through:
$testArray = array(2,2,2,2,1,2);
$numrooms = 2;
$valid = array_reduce(
$testArray,
function ($match, $value) use ($numrooms) {
return $match && ($value >= $numrooms);
},
TRUE
);
var_dump($valid);
you should pass the number of rooms to your sql statement as a condition such as:
$query_avail = "SELECT cupo, ex_cupo.room_id FROM ex_cupo
JOIN ex_rooms ON ex_cupo.room_id=ex_rooms.room_id AND
ex_rooms.room_id = '$room_id' AND dt = '$value' WHERE cupo > 1";
as the number one could be your PHP passed value.
If you can do this at the SQL level (as Andy suggested), that would be the best option . However, if you need to do this in PHP, you could easily iterate over your array, and set a flag to false if any value is below your minimum amount allowed:
$minimum_val = 2;
$enough_rooms = true;
foreach($availresult as $item) {
if ($item < $minimum_val) {
$enough_rooms = false;
}
}
Thanks to everyone who answered. I think I have my solution now, and I'm pressing ahead. Happy Christmas, All.
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.