Reputation: 246
I have a site that is based on requests, users can request items, I want to restrict some of the requests during certain hours of the day.
For example the user can request item5
only between say 5pm and 8pm. The rest of the time it's unavailable.
My site is in PHP with a MySQL backend.
Ideally, I would love a function I could call with an item id, the function would check time values from the database and return a true or false value.
It would be much appreciated if someone has some example code, I've tried reading up on time in PHP but its fried my head.
Upvotes: 0
Views: 738
Reputation: 2617
time()
, date()
, and maybe mktime()
is what you need. Simply compare time at the moment with time range that you allow/disallow viewing content
PHP date() manual - this is really a powerful function
there is also a timezone issue, that you might consider
Upvotes: 1
Reputation: 33542
You can pop in a startTime and endTime field intot he database using a time() datatype. Into these fields, enter the time they are available from and when they have to be back.
Then, it is a simple matter for a query to get the available items back.
tableAvailability
|--------------------------------|
| id | availStart | availEnd |
|--------------------------------|
| 1 | 15:00:00 | 18:00:00 |
| 2 | 12:00:00 | 12:30:00 |
|--------------------------------|
$startTime='15:30:00';
$requiredTime=2; // Showing Hours for example
$sql="
select
id
from
tableAvailability
where
".$startTime." >= availStart
and addTime('".$startTime."', '".$requiredTime.":00:00')<availEnd";
Upvotes: 0
Reputation: 248
This assumes the database has two columns in the item table called available_start
and available_end
. Both of these are assumed to be DATETIME.
function isItemAvailableNow(item_id){
# Globals are bad but this gets the point across
global $db;
# Get the item from the database
$result = mysql_query("SELECT * FROM items WHERE id = " . mysql_real_escape_string(item_id, $db) . ";");
$row = mysql_fetch_assoc($result);
# Pull the beginning and ending availablity time out of the database result
$available_start = $row['available_start']
$available_end = $row['available_end']
# Get the current time in the same format as the MySQL DATETIME type
$now = date('%Y-%m-%d %H:%i:%s');
return ($now >= $available_start) && ($now <= $available_end);
}
This code has not been tested and I have made a few assumptions (like you're using MySQL) but this should get you started.
You'll also want to consider timezones but that's another discussion.
Upvotes: 1