Mysql checking for avaliable time between opening times - php

I am desperate, I read many posts but couldn't quite find a solution...
I have a table called reservations.
In there I have 5 fields
ID(int)
room(TEXT)
date(DATE)
from(TIME)
to(TIME)
lets say in PHP I have 4 variables:
$room = "sauna";
$date = "2015-03-03";
$open_from = "09:00:00";
$open_to = "15:00:00";
I don't know how to make this Query which tells me whether there is still time for use between the opening times or not
I read many threads but I couldn't find anything which has this exact thing.
All I need is a '0' or '1' as a return value so I can simply dynamically remove the "add reservation" button from the page if there's no time left where one could put in a reservation anyways...
Please help me :(
Sincerely
Depth

Related

Getting data from MySQL for every day of the week

I need to get stats from my site for every day of the week example.
$str_sqlQuery = 'SELECT COUNT(DISTINCT (CASE WHEN (orders.status_id = 1
AND DAYOFWEEK(orders.datetime_ordered) = 1) THEN orders.id
ELSE NULL END)) AS cnt_items_bought_sunday';
I am getting the count for every order made on a sunday where it was successfull. Would it be better to get the orders to PHP and count them there or continue it like this.
I am trying it like this but it seems a little too resource intensive for my server.
First of all check your table was properly made (primary key and indexes used in the correct way, following standards), if it's not, fix that, thanks to that tiny standards you can get a great change in performance.
advice: Let the client (PhP) do the operative part(counting in this case, but operations in general)so you evade the memory hungry part from you sql query execution.
Hope this helps.
Good luck!

Dynamic end date for countdown

Im currently trying to sort out a system on my website (with limited coding experience) that doesnt have many references out there, it would seem.
I currently have paypal IPN integration (untested), that i then use to update the database to give the user "time" on their account. i also have a "stop/start" function in their account that allows them to stop and start their time, with the idea being when they "start" their time will start to count down. conversely, whilst they are "stopped", their countdown will not count down. i guess its similar to pausing an active subscription, but mine is over a short term period.
mysql_query("UPDATE `table` SET
`user_id`=$user_id,
`timeadded`=$timeadded,
`amountpaid`=$mc_gross,
`token`=$txnId,
`currtime`=TIMESTAMP()");
^ that is the snippet i am using to update the mysql table.
$new_time = date('H:i', strtotime('+$timeadded'));
this is what im currently working with to allow me to calculate an end date WITHOUT the start/stop feature i mentioned above. im unsure as to how to proceed from here to integrate that feature though, as obviously the end date would need to be dynamically changing based around other variables than the currentdate.
Ive also referenced this which i think might lead me along the correct track but ive been unsuccessful as of yet.
//time when start clicked
$first = new DateTime
//time when stop clicked
$second = new DateTime
//when start is clicked
exec(mysql_query("UPDATE `newtable` SET `userid`=$userid, `start`= $first"));
//when stop is clicked
exec(mysql_query("UPDATE `newtable` SET `userid`=$userid, `end`= $second"));
//use array to select all entries from newtable where userid=$userid (can fill this in if wanted).
$elapsed = $first->diff( $second );
$timeleft = (strtotime($timeadded) - strtotime($elapsed));
$updateelapsed = mysql_query("UPDATE `newtable` SET `userid`=$userid, `elapsed`=$elapsed")
$allelapsed = mysql_query("SELECT * FROM newtable WHERE userid=$user_id");
$allelapsedarray = mysql_fetch_array($allelapsed);
$timeelapsed = array_sum($allelapsedarray);
//so now i have my total time spent "started", i should be able to compare that to the amount of time they bought. if its more than that, they are rejected, otherwise can continue as normal.
so thats what i have thus far for the start/stop feature to be included. this was just done on the fly after coming across the second link i gave above, and i feel its a more fruitful way of going forward than the potential method i mentioned in the first few paragraphs.
to the below comment - it wont update my database with regards to the start/stop time, nor the elapsed time column. given those things it wont bar people from accessing those areas that need "time", but i assume that that will fix itself when the above is sorted. this method ive developed also seems long winded so i might be overlooking a far simpler way of coding this semmingly straightforward task. thanks in advance for any tips.

MySQL Queries before NOW

Now I've read on this fantabulous site about how to check if the timestamp that is in your database is before now(), and that answers part of my question.
But the remainder of my question still eludes me:
How can you not only check for timestamps BEFORE now(), but also put a cap on how many before now are queried?
I have a database that is acting as a guestbook, and the output is a flash piece that looks like a post-it board. you fill out a form, and the submission immediately "tacks" itself to the post-it board. The problem is that when you first load the page, it will load every single post starting from id-0 to id-5,000,000 and so on and so forth.
I would like to put a cap on how many are loaded so the query looks at the following things:
What's the current timestamp?
Go back in time (for example) 10 entries ago
Post from THAT point on
The fields I have in my database are: id, comments, timestamp
EDIT
I'm looking at some of the answers, and I would like to ask about the LIMIT. If I put a limit on the queries, will I still be able to query posts that are PAST now?
Example: Say there are two people viewing the site at the same time. One visitor posts a comment into the database. I want person 2 to still be able to the see that comment pop up on his end.
The flash post-it area runs off a php script that queries the database and exports it into an XML format that Flash can read. Every 5 seconds, the flash re-queries the database to check for more posts.
If I put the Limit on the query, will I still be able to grab NEW entries on the fly? I just want the LIMIT to generate a starting point offset from ground zero
I think what you are looking for is called Limit
You just put it at the end of your statement and the query will return the amount of results you wanted
YOUR QUERY LIMIT 0,10
This will return 10 first results
SELECT * FROM
(SELECT ... WHERE dt<NOW() ORDER BY dt DESC LIMIT 10) a
ORDER BY a.dt ASC
or
SELECT ... WHERE dt<NOW() ORDER BY dt DESC LIMIT 10
check which is the more suitable for you.

Allow access to a game every few hours using mysql and php without long code?

I have some games I have programmed for members to play. I usually allow members to play games every day, and I have a cronjob resetting the value at midnight to allow access to the games again the next day.
I constructed a new game, and I wanted it to allow members to play every 2 hours. I realize I cannot do this with a cronjob, because members will play the game at different times.
I know this probably sounds bad, but I'm not very familiar with timestamps, so I really don't know where to start. I haven't really had any reason to look into it until now. I'm guessing that the time or now function will accomplish this when compared, but again I cannot find the relevant situation in the manual about doing this with mysql and successfully submitting that data in the same format.
I've seen examples of other programmers doing this in a certain way, but it seemed they went to unnecessary lengths to make it work. The example I've seen would add a lot of lines to my code.
If this is a repeat question, I apologize, but I don't know what keywords to search for in this situation. All I have gotten is javascript countdowns.
Well the first thing that you're going to need is a way to determine when each member has played the game. So you will need to create a table with the following information:
MemberID
GameID (In case you want to support more than just 1 game in the future using this model)
DateTimePlayed
So now the first problem you have to solve is "Has player X played game Y in the last 2 hours?" That can be solved with a simple query:
SELECT * FROM MemberGameHistory WHERE MemberID = X and GameID = Y and DateTimePlayed > DATE_SUB(NOW(), INTERVAL 2 HOURS)
If you're happy that they haven't played it and decide to let them in, then you need to insert a row so that the next time you run the query you'll see that they've done it:
INSERT INTO MemberGameHistory (MemberID, GameID, DateTimePlayed) VALUES (X, Y, NOW())
Does that solve your problem?

Method for preventing a visitor from making more than 2 posts per day (PHP MySQL)

I've been searching for hours for a solution and either I can't find the right words to describe what I need in the search engines, or I'm just bad at finding things.
Here's the situation:
I'm currently making a website and I have a section where visitors can post messages, kind of like a "guestbook". However, I want to limit an IP address to 2 posts per day. I thought it'd be easy at first, just insert the IP address, date, and time along with all the other data into the mysql table and then do a comparison of the times and dates from each ip. Something like that.... Then as I got to working on it, so many questions came to mind. How would I compare the entries if the IP has posted more than 2 messages over a number of days? How would you even start comparing the date and time accurately? What's the best time and date format for comparison? Is there a better way such as self expiring data that you can compare to? And so on.. Sorry if this seems like such a simple task but I am having a hard time finding the answers. Tried googling everything such as "mysql php time limit", "php mysql prevent spam timer", "php mysql timer like megavideo" etc.
Just to clarify, I need a good method for preventing a visitor from posting more than 2 message per day. This is a "guestbook" kind of thing so any visitor can post. No logins.
Thank you in advance!
Create a table called exceptions with structure id, ip, date
and when user posts something, execute a query like :
$ip = $_SERVER['REMOTE_ADDR'];
$query = "insert into exceptions set ip = '{$ip}',date = 'NOW()'";
and before let user post something add this:
$ip = $_SERVER['REMOTE_ADDR'];
$count = mysql_num_rows(mysql_query("select count(*)
from exceptions where ip = '{$ip}'
and date > DATE_SUB(NOW(), INTERVAL 24 HOUR)"));
if($count> 2) {
echo 'You have exceeded posting limits, please try again in 24 hours';
exit;
}
something like this:
posts_in_last_24_hours = select count(*) from posts where ip=? and date>(NOW()-86400) -- 24 hours ago
if that is 2:
fail
else:
post message
If you record in your database the IP on every post, you can check if it has posted more than 2 times in the last X days with a query counting the number of records with that IP in the last X days, something like this:
SELECT COUNT (IP) FROM posts_log WHERE IP = 'the_user_ip' AND post_date > (NOW() - (X * (60 * 60 * 24)))
Using a trigger
Record the IP and store that in the guestbook table.
Then create a trigger like so:
DELIMITER $$
CREATE TRIGGER bi_guestbook_each BEFORE INSERT ON guestbook FOR EACH ROW
BEGIN
DECLARE posts_today INTEGER;
SELECT COUNT(new.ip) INTO posts_today FROM guestbook
WHERE ip = new.ip AND postdate = new.postdate;
IF posts_today > 1 THEN BEGIN
//Force error by selecting from non-existing table
//this will prevent the insert from happening.
SELECT no_more_than_2_post_per_day_allowed
FROM before_insert_guestbook_error;
END; END IF;
END$$
DELIMITER ;
Now you can just do inserts in you php code with worrying about the daily limit.
The trigger will take do the checking for you automatically.
Using insert .. select
If you don't want to use triggers, use an insert ... select statement.
First make sure that field ip is defined in the table definition as NOT NULL with no default.
This will make the following insert fail when trying to insert a null value into the guestbook table.
<?php
$name = mysql_real_escape_string($_GET['name']);
$post = .....
$ip = ....
$query = "INSERT INTO guestbook (id, name, post_text, ip, postdate) SELECT
NULL AS id
, '$name' AS name
, '$post' AS post_text
, IF(guestbook.count(*)>=2,null,ip) AS ip
, CURDATE() AS postdate
FROM guestbook WHERE ip = '$ip' AND postdate = CURDATE()";
Of course you can put the IF(count(*) >= 2,null,...) in the place of any column that is defined as NOT NULL in the table definition.
Links:
select...insert: http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
triggers: http://dev.mysql.com/doc/refman/5.1/en/triggers.html
You could implement this simply with cookies. Anyone determined enough to get round the posting limit would be able to get round an IP block anyway, since proxies and dynamic IPs make it really easy. So blocking by cookie or by IP are about as useful as each other (not especially), but cookies are easier to implement:
If you store a counter in the cookie and set the expiry date to be 24 hours in the future.
You can then increment the counter when the user posts an entry, and simply check the counter to see if they've reached their limit.
That way you don't have to worry about mucking about with a database and any performance issues it can introduce.
Building upon Neville K's captcha point. If spam is your main concern, try out a negative captcha - it doesn't impact the user's experience since they never see it.
You've already got plenty of reasonable looking answers, so I won't add anything to that - but I do think you need to be careful using IP address as the unique identifier of the visitor. It's not a reliable way of identifying users - for instance, most people within a single company/university/government installation will appear to come from the same IP address, so this implementation would limit everyone within that structure to 2 posts per day.
The best way of avoiding spam is to include CAPTCHA - it's a pain in the backside for users, but it reliably foils robots; unless your site is super high value, spammers won't be motivated enough to have human beings post spam.

Categories