PHP+MySQL add time countdown and check its done - php

I'm basically looking for something that follows:
Player completes transaction
System updates MySQL with 10 min countdown
Player is unable to complete more transactions until countdown finishes
Continued..
Imagine it would work something like this:
mysql_query("UPDATE `players` SET `time`= 10:00 WHERE `id`=$player[id] LIMIT 1");
and
if ( 0 <$player['time']) {
$error='yes';
Also what field type do I give the MySQL field, that's what confuses me most. How it's stored and if it needs to be 'translated' back for the php.

Thought I'd post my answer for future people with the same problem and only complex answers.
All you have to use is time()+900 or $timePlus = time()+900 which inputs the current time + 10 minutes, as an integer into the MySQL field. You can then use time() or $time = time() whilst verifying against the 'time' field to see if 10 minutes is up. Example below:
$player['time'] > time() // where the time stored in 'time' is greater than the actual time causes an error.
Hope I explained that right and credit to #flyingeagle413 for also suggesting this method (although admittedly a bit late) :P

Related

How to change the status from 0 to 3 in database table automatically after 1 month using php-mysql [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to add a new feature in my website, i.e I want to fix the time limit of 1 month and after that it expires that means the status of that user will change from 0 to 3.
I have many fields in my table including
id
status
today_date.
In this, today_date stores the time and date of registration and by default the status is 0.
Is this possible using php-mysql? If possible, please help me out.
Thanks in advance.
You should take another approach to achieve this.
You already have registration date in DB right, so when user enters valid credentials in the login form, compare the current date with the registration date, if that difference is more than 30 days then update the status columns with 0 and also do not allow that user in at that time.
How to calculate number of days between two dates in php:
$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24)); // This will be number of days. Store it in a variable and set a condition on it.
If you have a page to process the Login POST data, then build your sql query to fetch the column containing the user's time of registration.
Take $time_of_reg as user's time of registration.
What ever timestamp you're using, convert it to a UNIX
timestamp using strtotime() function.
Now adding 30 Days to the user's time of registration $time_of_reg_plus_30 = strtotime('+30 Days',$time_of_reg)
Now use an if condition to perform an update query if the current time is greater than or equal to 30 Days + users time of registration. This way you can perform an update query to your status column, only if the user has been registered for 30 or more days.
if(time()>=$time_of_reg_plus_30)
{ //perform sql update query}
(having these values in a UNIX timestamp, makes it easier to compare)
<?//perform sql query to fetch user's time of registration, '$time_of_reg' in this case.
$time_of_reg = strtotime($time_of_reg); //Convert to UNIX timestamp
$time_of_reg_plus_30 = strtotime('+30 Days',$time_of_reg); // Add 30 Days To Registration Time
if(time()>=$time_of_reg_plus_30)
{ //perform sql update query if user has been registered for 30 Days or More
}
Remember to place this in the page that handles your Login POST data, this is a good way to achieve your objective without a cron job, as the user's status is updated whenever the user attempts to Log In.
Cron job is the best solution for this. Think you don't want to apply cello tape on balloon.
If you would like follow the steps below:
Create a PHP script & save in a file e.g. myCron.php
If you have Linux server with Centos create a scheduler script with bash How to create a cron job using Bash automatically without the interactive editor?
If you have cPanel go to cron jobs, set the file path & time to run.

PHP DateTime Subtraction and Conversion

It's hard to articulate the problem I'm having in the title, but here's the scenario: I'm working the backend of a 3-tiered exam taking website. I'm currently updating my function used for when students request an exam. The exam has start and end dates and times, as well as a time limit. What I want to do is specific to the case when the amount of time left in the exam period is less than the time limit for the exam, For example, the exam period ends at 5:00PM. The time is now 4:30PM. The exam time limit is an hour and a half. I want to replace the hour and a half time limit with 30 minutes. To do that, there are 3 dates I need, and I will explain how I get each:
Timestamp for my function page. When the controller calls my page, after I open the session, I set the default timezone to America/New York (my region). To get the timestamp, I use the code:
$date = date('Y-m-d H:i:s');
$currenttime = date('H:i:s', strtotime($date));
I use a function call to my database to acquire the time limit and the time the exam ends (I also use the dates for other comparisons to check exam availability). The exam end time is stored in resultant array $res[10] and the time limit is in $res[11].
Assuming the due date for the exam is equal to the date of the timestamp, and it is in the exam period (2 checks I perform before), I want to check if the difference between the current time and the end of the exam is less than the time limit. If the time until the exam ends is less than the time limit, I want to set that amount of time as the new time limit. My front end expects my result in the form HH:mm:ss (php's equivalent is H:i:s). So if there is 30 minutes until the exam ends and the time limit is an hour and a half, I want the new time limit to be 30 minutes (or 00:30:00). My code is currently not working as desired. I am meeting the criteria for the if statement, which is my desired result. When I am converting it to the form H:i:s is where the problem seems to be (I keep getting a result around 19:00:00). Every article I've read suggests to do it this way, but I may be missing something.
$compareTime = strtotime($res[10]) - strtotime($currenttime);
if(compareTime < strtotime($res[11]){
$timelimit = date('H:i:s', $compareTime);
}else{
$timelimit = $res[11];
}
If there is a better way of doing this, I'd be much obliged to know. I'm fairly new to php, and admittedly I realize this may be a strange problem, but that's the way the group decided to go.
Maybe it's because the databse and PHP server are using different timezones. Check it out by printing these variables to see their values.

time count after registry

I saw some website that after you have registered, you can use the service like posting a comment immediately.
You may have to wait for 5 or 10 minutes to be able to start, like this StackOverflow website.
Once you have asked question, you have to wait 20 minutes to select your answer.
If I want to do it in JavaScript or PHP can anyone show me how to do it? I assume you have to compare the time with current time-stamp, but don't know how to exactly implement it. Thanks in advance!
Assuming you have a datetime string stored in a variable, you could do something like:
// TODO: get a datetime string into $time
$minutes = 5;
if (strtotime($time) + $minutes * 60 < time()) {
// It's been 5 minutes since $time
}
In PHP:
$wait_time = 10*60; //10 minutes * 60 seconds
if(time() > $start_time + $wait_time) {
}
sure, you'll want to compare the date of posting, with the current date, but then formulate the conditions that will validate a new post or the selection of the same.
Each question that is posted will require server side storage, if not exclusively in a db then there will need to be at least a record in a table linking the question to the user.
Once a question has been posted you could either have the server side script that loads the question carry out the following tasks.
Get the question entry
Is the person that posted the question the current requesting user
[yes]
Is the request time minus the post time greater than (number of mins * 60)
[yes]
Include select answer buttons (html objects or buttons)
Alternatively you could always show the buttons and carry out the above logic and return some indication that the user must wait x minutes before they can select an answer.
You have to store the creation time (of whatever object or saving) along with the item being created in the database. So for example, if you create a question on SO, they probably store the time you posted the question. Then when you go to view your question, they probably get the difference between the current time and the time stored.
So say that you want to implement a 20 minute wait after posting a question before you can select an answer. Then you upload a question at 5:00 PM. When you attempt to view your question at 5:05PM the same day, the difference in time is 5:05PM - 5:00PM, which is 5 minutes. Take 20 minutes - 5 minutes to get the time the user must wait, and send that back to the page.
From javascript you can get that time limit (15min), and create a setTimeout method to "unlock" the answer feature. The code would look something like this:
<input type="hidden" id="waitfor" value="15">
$(document).ready(function () {
var waitfor = $('#waitfor').val();
timer = setTimeout(function () {
// let the user know they can post an answer
}, waitfor * 60 * 1000);
});
Also, I'd let the user post an answer whenever they'd like, but prevent it being submitted on the client side if it hasn't been 20 minutes.

Online or offline function PHP

I'm working on a "community". And of course I would like to be able to tell if a user is online or offline.
I've created so that when you log in a row in my table UPDATE's to 1 (default is 0) and then they're online. And when they log out they're offline. But if they don't press the Log out button, they will be online until they press that button.
So what I would like to create is:
After 5 minutes of inactivity the row in my database should UPDATE to 0.
What I'm looking for is how to do this the easiest way. Should I make an mysql_query which UPDATE's the row to 1 every time a page is loaded. Or is there another way to do it?
Instead of using a boolean "Online" field, use a DateTime. When a user makes a request to the page, update the DateTime to NOW(). When you are gathering your list of current users online, your WHERE clause would be something like WHERE lastSeen > DATE_SUB(NOW(), INTERVAL 5 Minutes)
Update: To retrieve individual online status.
select if(lastSeen > date_sub(now(), interval 15 minutes), 1, 0) as status from table where userid=$userid
This tutorial is quite handy: Who Is Online Widget With PHP, MySQL & jQuery
Well, if you don't want to set up a cron job, that would execute some code every 5 minutes, you have no options. But, actually, I think the following approach would be much more efficient:
Change your 1/0 column to timestamp
On each user request update that timestamp to current DateTime.
When checking for active users, check if that timestamp is less than 5 minutes from now
This way you'll be having actual data on users and no recurring queries - just one additional update per request
If you will update the row only on page load, then some of information would be incorrect.
Let's assume that user have opened page and is writing really long text or something. He is doing it for half an hour now. And your database ny now is already updated and he is counted as offline user.
I would write javascript that pings you back each 5 minutes, if opened tab is active.
This ping updates database field 'last_activity' to NOW(). And to count online users, or check if user is online you'll need to compare 'last_activity' to NOW() minus five minutes.
Simpliest ways (IMHO):
You can count sessions in session_save_path() dir.
you can store last visit timestamp in DB, and count rows with (timestamp > current_timestamp - somedelay).

PHP MySql Storing Data for 24 hours

I'm building a toplist for my site and instead of recording in and out hits and emptying the database every 24 hours I would like to record in and out hits "within the last 24 hours", this way the toplist will always look busy no matter what time you look at it, while still acurately ranking sites.
So basically I'll have to add a record to the database logging an 'in' hit (for example) and the remove it around 24 hours later, or simply not consider it when ranking the sites.
I want to know the most efficient way of doing this, I have some ideas but they all seem really resource heavy. I hope you understand what I'm trying to achieve :) Any help would be appreciated.
You don't necessarily have to delete "old" data all the time. You can also limit the data set to records within the last 24 hours when querying data.
WHERE
site='xyz'
AND hit_datetime > Now()-Interval 24 hour
see http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
I would delete the data that is older than 24 hours with a simple
DELETE...WHERE hit_time < now() - interval 24 hour
The other question is - when to call it? The tradeoff is between performance and stale data. The more often you call it, the less "stale" data there will be, but the server load will grow.
I see several approaches, pick one that suits your needs most:
Call it at the start of every script. This can be optmized by calling it only if the script will do something with the hit data. That way every script will always run with "correct" data. However this will have the maximum load.
Schedule a cron job and call it once every 1h/2h/24h/etc. This way there will be a little bit of "stale" data, but the overhead will be reduced to a minimum.
Do it like PHP does it with sessions - on every script startup give it a x% (x is configurable) chance of being run. That is, take a value from 0 to 100, and if it is smaller than x, execute the DELETE.
You can also invent some other schemes - for example, run it once per user session; or run it only if the execution time is evenly divisable by, say, 7; or something else. Either way you trade off performance for correctness.
Write a Stored Procedure that deletes records older than 24 hours. Then write a trigger that runs on every INSERT statement and calls the SP.
you could store the timestamp with each "hit" and then call a query like
$time = time()-86400;
mysql_query("DELETE FROM xxx WHERE timestamp < $time");
or you could same thing within the SELECT statement, depends on if you still need the hits afterwards, etc
If the time-constraint is not really hard (e.g. you'll loose money or are really annoying your users if the data is kept in the the db longer than 24 hours), I'd use use PHP's register_shutdown_function like this:
function cleanup() {
// open db-connection etc.
$query = 'DELETE FROM <yourtable> ' .
'WHERE UNIX_TIMESTAMP(<timstampfield>) < ' . (time() - 86400);
mysql_query($query);
// close connection
}
register_shutdown_function('cleanup');
The above code assumes, <timestampfield> is of one of the the MYSQL-date-datatypes (TIMESTAMP, DATE, DATETIME).

Categories