i have a simple question, that just needs verification, it's about how time is stored in mysql, here is how i store it:
if(isset($_SESSION['user']))
{
$u_id=$_SESSION['user'];
//insert current time to db, i set the type of time to TIME
$query="INSERT INTO time(id,u_id,time) VALUES('NULL','".$u_id."',CURTIME())";
mysql_query($query);
}
that is how i store it, now i would also need to compare it to a value, later on:
//set current time
$curr_time=time();
//set maximum time to 5min
$max=300;
//get previous time from db
$query="SELECT * FROM time";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$prev_time=$row['time'];
//get difference in time
$diff=$curr_time-$prev_time;
//if max time is surpassed
if($diff>$max)
{
echo "maximum time surpassed!";
}
that's the simple code, first of all, is the syntax for inserting the time to the table okay(the CURTIME() thing), also is the comparison fine, will the result stored in $diff yield seconds?thank you, and sorry if you think this question is a waste of time.
CURTIME() will only give you the time, you likely want NOW() which is the date and time. Then you will need to use strtotime to convert the saved value from the database to seconds since epoch.
Do it in your query:
$query = "SELECT id FROM time WHERE time + INTERVAL 5 MINUTES > NOW()";
is there are no results, time has passed.
MySQL has terrific time and date handling functions. Use them.
(I'd also add some extra parts in the WHERE clause, if you have more than one record, you'll be looking at the wrong one probably.)
Since CURTIME is only on a daily basis and I suspect you want your function to cover the span over days I'd suggest you use NOW() instead as it gives you this format instead:
2012-11-06 09:39:34
also is the comparison fine, will the result stored in $diff yield seconds?
You can't directly compare mysql CURTIME() with time() function in PHP.
For example:
In MySql:
CURTIME() will return only time.
select CURTIME();
+-----------+
| CURTIME() |
+-----------+
| 14:15:11 |
+-----------+
In PHP
time() will return current Unix timestamp.
echo time();
1352191547
Look at sberry's answer for compassion.
Related
I am trying to run a counter from the time user is entered into database
I got this fiddle
http://jsfiddle.net/brkp1sa2/
which starts timer from 08/24/2012 while i need to start it from user date which i enter into database as timestamp at the time of signup
How I can do it as I fetch val from database like
<?php $timd = $db->fetchVal("select ts from users where id = ?", $id);
if (!empty($timd)) {
$timdl = $timd->ts;
}
Not know php pr jquery much so a code example answer can help me better
How to use this value into jquery so time start from given time stamp
Javascript timestamps are Javascript numbers representing Unix time in milliseconds. MySQL uses its UNIX_TIMESTAMP() function to generate Unix timestamps (in seconds) from various kinds of date / time datatypes.
So, the query
select UNIX_TIMESTAMP(ts) * 1000.0 AS ts from users where id = ?
will generate a Javascript timestamp value.
Now, Javascript timestamps and Unix timestamps are, by design at least, in the UTC time zone. Depending on how your table's ts values were stored, your results may come out in local time.
I want to limit my users to only (be able to) post something every 15 minutes.
So in my SQL query I select NOW() to get the current date and time, and also the user's last post date date_added. I want to compare the two dates and if the difference between now() and date_added is less than 15 minutes, then the user cannot yet post. If it's greater then he can. If less than 15 minutes then I'd like a message like 'Please wait x minutes and y seconds.' So I need some kind of date manipulation/comparison.
How should I approach this. In MySQL or PHP?
You could simply convert the mysql timestamp into a php-date and compare from there
$time = date ("Y-m-d H:i:s", $mysqltime);
You will find lots of useful snippets how to compare dates on the functions documentation: http://php.net/manual/de/function.date.php
Edit: pozs anwser nails it ...
In MySQL: DATE_ADD() or DATE_SUB(), then compare.
In PHP: DateTime->diff().
Something like
SELECT count(*) FROM posts WHERE last_post > DATE_SUB(NOW(), INTERVAL 15 minute);
This will be done with PHP.
I basically want to get the number of rows that were inserted 30 minutes ago.
I have a time field on my table which is type TIMESTAMP and on update it's set to CURRENT_TIMESTAMP.
The date is stored in this format:
2011-05-27 04:29:17
My query is supposed to look something like this, however i just can't do it
SELECT COUNT(*) FROM mytable WHERE UNIX_TIMESTAMP(time) < '.time().'-1800
Where time() is PHP's function that fetches the UNIX time.
What it should basically do is print me the number of rows inserted from now to 30 minutes ago, but i just can't seem to make it work.
Can somebody help?
Small edit:
Another problem i am seeing is that php's function time() displays the unix time which is UTC. The time stored in mysql is probably GMT i.e whatever my computer's time/timezone is set to.
You can easily get rows stored from now to 30 mins ago by simply using:
SELECT count(*) FROM mytable WHERE `time` >= DATE_SUB(UTC_TIMESTAMP, INTERVAL 30 minute)
Usage of UTC_TIMESTAMP is just an example if you're storing your date/time data as UTC_TIMESTAMP(), you can probably use NOW() if necessary, depends on what you're storing really.
**EDIT**
Removed bad pointers and fixed example :)
Do you really need your computer's timezone to be different than UTC? why not just set it to UTC & save yourself the confusion? If that doesn't work, just use dateadd() on mysql to convert your mysql timestamp to UTC when checking?
My suggestion would be to write a small function to convert the mysql timestamp to your PHP timestamp format & load it into mysql. Then all you need to do is to call tmstamp(time_stamp) instead of time_stamp in your query. You can do the reverse too i.e. Convert PHP's "30 minutes ago" timestamp to mysql format and rerun your query (probably easier).
Usually it's just a formatting issue. It's not standardized across programs.
I am trying to create a script for quiz. I have stored current timestamp in MySQL DB as quiz start time, and want to check after each quiz how much time is left.
I have the idea that I will add 30 mins to saved time stamp and subtract this value from current time. That will be the time left. But I don't know the exact way of doing this.
My time stamp is saved in DB in format 2010-08-24 20:08:59. Any one have the idea.
Please let me know if someone have done it, or know how to get it.
Adding 30 mins to time stamp and showing the user how much time is left.
I am using the now() function to store the timestamp in DB.
Thanks
I would personally store the output of PHP time() in the database.
If you a human readable format from this value, you could use date('Y-m-d H:i:s', $fromdatabase);.
You want to store an actual UNIX timestamp in the database, not a string in that format.
You may or may not be doing this already, it depends on the type of column you're using. For MySQL, you should be using TIMESTAMP, which allows you to retrieve the timestamp with
SELECT UNIX_TIMESTAMP(column_name) ...
To store the current time + 30 minutes, all you have to do is:
INSERT INTO table (column_name) VALUES(UNIX_TIMESTAMP() + 1800)
You can know if the time has expired by comparing time() against the value of the column.
I need to keep a field in a data-base and update it with a time somehow, then later I need to check that time to see if it was over 30 minutes ago or not, and if not, how minutes left until 30?
I am going to be doing this with PHP+MySql can anyone tell me the simplest way to do this?
Thanks!!
Let's assume you want to know how long ago the last update/insert in the table occurred.
You can set up a table with a timestamp field with an on update clause
CREATE TABLE foo (
id int auto_increment,
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
primary key(id),
key(ts)
)
and then query the record with the largest value in ts
SELECT
TIMEDIFF(Now()-Interval 30 Minute, ts)
FROM
foo
ORDER BY
ts DESC
LIMIT
1
edit: This also works if you want to get all records that have been inserted/modified within e.g. the last 12 hours.
SELECT
TIMEDIFF(Now()-Interval 30 Minute, ts)
FROM
foo
WHERE
ts > Now()-Interval 12 hour
ORDER BY
ts DESC
edit2: there's also an off chance you might be interested in http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html:SHOW TABLE STATUS returns the following fields:
...
Update_time
When the data file was last updated. For some storage engines, this value is NULL. For example, InnoDB stores multiple tables in its tablespace and the data file timestamp does not apply. For MyISAM, the data file timestamp is used; however, on Windows the timestamp is not updated by updates so the value is inaccurate.
I could wrap all you insert and update MySql calls in a function something like the following:
function MySqlQuery($query, $res){
$result = mysql_query($qs, $res);
if($result === false){
mysql_query("QUERY STRING TO UPDATE FIELD IN DATABASE WITH NEW TIME", $res);
}
return $result;
}
Replace the "QUERY STRING TO UPDATE FIELD IN DATABASE WITH NEW TIME" with an actual update query and you should be good to go.
What I do is, put a Time Stamp on the latest record. Pull the latest record with a MySQL Query and then use the mysql fetch array function to get the time of that last record. This goes the same for using a database that is updated with the time only.
You would be able to manipulate that time with a function that compares the current time to the time on the record. From there you can display the time since last posting, and if it is over 30 minutes you can make it echo a message.
$currenttime = /* PHP Time Formatting you wish to use. */
$query = mysql_query("SELECT time FROM database");
$row = mysql_fetch_array($query);
echo "Last Record Posted #" . $row['time'];
$timesince = $currenttime - $row['time'];
echo "Time Since Last Post:" . $time - $row['time'];
if($timesince >= "30"){
echo "Over 30 Minutes!";
}
Let me know if you have any questions. The above code should give you an idea of how it would work, but it is a rough example.
Best of Luck!!
EDIT:::
Sorry, I misread the question, You would still need to enter the time into the database. You can still use the above code to pull the time and see if it is greater than 30 minutes or not.
For the Time Stamp check out the PHP Time Manual. You will want to pick the same time format for both the MySQL Input and the code I posted above.