Question regarding MySQL timestamp comparisons - php

I'll explain my goal first: I want the user to query the database, and return rows only if those rows have been updated since their last query. No sense returning data they'd already have. So I created a column called 'lastupdated', a timestamp type which autoupdates every time any content in the row is updated. This works fine. Now, I want to form the query correctly. The user will have their previous query's timestamp saved, and via php will use it to compare their previous query's time with the time each row has been updated. If the row was updated after their last query, the row should be returned.
I made something like this,
SELECT * FROM users WHERE '2011-02-26 01:50:30' <= lastupdated
but its obviously much too simple. I checked the MySQL manual and found this page MySQL Time/Date Page. I'm sure the answer is here, but I've read through it any nothing really makes sense. I have a timestamp in the same format used by the MySQL timestamp type, but I don't know how I will compare them. Thank you very much for your help.

That query is exactly how you'd do it. As long as a stringified date-time is in MySQL's preferred format (yyyy-mm-dd hh:mm:ss), then it will be internally converted into a datetime value, and the comparisons will go ahead.
You'd only need the date/time functions you found if you want to do something more complicated than simple "greater/less than/equal" type comparison, e.g. "any records that have a December timestamp".

As Marc said, your code should work. But you probably want to do this programmatically with a variable for the time instead of the literal.
If you don't have the date-time specified as a string, but rather as a timestamp (e.g. from using the php time() function), then you can use the following query:
$query = "SELECT * FROM users WHERE FROM_UNIXTIME(" . $timestamp . ") <= lastupdated";
The key is the FROM_UNIXTIME() MySQL function.

Related

MySQL timestamp is a datetime: shouldn't it be an integer? I need to pass it through the URL

I may be going about this the wrong way, but I have made "previous" and "next" buttons which take you to the next or previous product in the database by passing the index through the URL and getting it with PHP. But I need to accomplish this with the date the products were entered into the database (as indices will be reused if a row is deleted). The problem is I used datetime when I first built the database. I would like to convert all those datetimes to timestamps because I understood timestamps would be an integer representing the number of seconds from 1970 or something. An integer is easy to pass through the URL using get (no %20 in the URL). But I just tried it in a test database and timestamp isn't just an integer. Am I understanding this wrong? Am I going about it the wrong way?
EDIT: What I really need is a PHP function that will convert a MySQL datetime to a unix timestamp. That will solve my problem.
You're understanding it wrong. As a general rule, a SQL timestamp and a Unix timestamp are two different things.
To get a Unix timestamp from a MySQL datetime columns, use the unix_timestamp() function.

Store timestamp using PHP:date() or MySQL:FROM_UNIXTIME()?

This may be trivial, but when I want to store a timestamp value (returned by, say, time()) into a TIMESTAMP column in my MySQL table, which of these two are preferable:
function storeTime($timestamp) {
// Option one:
$query = "INSERT INTO faketable (datecol) VALUES (FROM_UNIXTIME(".$timestamp."))";
// Option two:
$query = "INSERT INTO faketable (datecol) VALUES (".date("YY-MM-DD HH:MM:II", $timestamp).")";
}
Is there even a difference?
EDIT: Sorry, meant date(), not strtotime()...
EDIT 2: NOW() doesn't cut the mustard, the actual timestamp is a paramater sent to my method. I don't know what it is in advance.
EDIT 3: I really shouldn't be asking questions at this time of night. The column in question is, in fact, a TIMESTAMP column, not a DATETIME column.
To answer your question; No there is no logical difference. They both return a string representation of a date https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime, which MySQL will happily convert to a DATETIME, or TIMESTAMP type. As for which is faster evidence would suggest MySQL; http://www.onextrapixel.com/2010/06/23/mysql-has-functions-part-5-php-vs-mysql-performance/, Faster to use MySQL's CURDATE() or PHP's date()?
Simplest is a FROM_UNIXTIME() in mysql. That'll be a single integer->date conversion. Doing it in PHP means integerr->string->datetime, which is far less efficient.
As well, your strtotime() is completely invalid. That's not now the function works. You'd end up with's in the database.
As for storing a "now" timestamp, why not just use a timestamp field type? it automatically sets itself to the current time when you insert/update a record.
How bout
INSERT INTO faketable (datecol) VALUES (UNIX_TIMESTAMP())
I think that's what you're looking for OP

Insert current date to MYSQL table, then echo back

It seems like there are too many complicated ways of doing this, so I'm looking for a clean, succinct answer to this issue.
I write a blog, I click submit, and the title, content, and timestamp INSERTS INTO my blog table. Later, the blog is displayed on the blogindex.php page with the date formatted as MM-DD-YYYY.
So this is my 3 step question:
What is the best column type to insert the date into? (ex: INT, VARCHAR, etc)
What is the best INSERT INTO command to use? (ex: NOW(), CURDATE(), etc)
When I query the table and retrieve this data in an array, what is the best way to echo it?
I'm new at PHP/MySQL, so forgive me if I don't know the lingo and am too frustrated reading 1000 differing opinions of this topic that do not address my issue specifically, or only cover one of the 3 questions...
Here is my opinion on your three questions:
Use the correct data type: Date or DateTime. I would choose for the DateTime type as you store the time as well (might be very handy if you want to have some kind of order, when you added the posts).
It all depends whether you just want the Date (use CURDATE()) or the Date + Time (use NOW()).
You fetch the data and format it how you want it. Don't format it yet in the query, just use the correct PHP functions for it (for example with DateTime). How you fetch the data, doesn't matter too much; you can use PDO or MySQLi or ...
Always store and process dates and times in UTC and perform timezone adjustments in your presentation layer - it considerably simplifies things in the long-term.
MySQL provides a number of different types for working with dates and times, but the only one you need to worry about is DATETIME (the DATE type does not store time information, which messes up time zone conversion as information is lost, and the TIMESTAMP type performs automatic UTC conversion (which can mess up programs if the system time zone information is changed) and has a smaller range (1970-2038).
The CURDATE() function returns only the current date and excludes time information, however this returns information in the local timezone, which can change. Avoid this. The NOW() function is an improvement, but again, returns data in the current time zone.
Because you'll want to keep everything in UTC you'll actually want to use the UTC_TIMESTAMP function.
To return the value you'll need to execute SQL commands in sequence with variables, like so:
SET #now = UTC_TIMESTAMP()
INSERT INTO myTable ( utcDateTimeCreatedOrSomething ) VALUES ( #now )
SELECT #now
Date would probably be the best type, although datetime will work as record more accurate as well.
There isn't a 'best insert into', but what do you really want and how accurate you want the date to be. For a blog, I would say make it datetime and use NOW(). so visitors can see quite accurate of when this post is made.
surely you can easily find huge to run sql and fetch a select query from sql using php by google, so I'll leave this easy work to your self.
For echo the date, you can use the php date format such as:
$today = date("m-d-y"); // 03-10-01
I think Styxxy has it pretty well right, but here is a links for your PHP date formatting part...
How to format datetime most easily in PHP?
(Supporting link: http://php.net/manual/en/datetime.format.php )
Basically it's
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))
... although, I think the strtotime is unnecessary as it should already have the type of datetime.
In terms of the MySQL, yes, do it as a datetime col, use NOW() as the SQL keyword, and depending on how you want to get it from the database you could...
SELECT CAST(col_name AS DATE) .... or .... SELECT CAST(col_name AS DATETIME) <-- this last one is implied due to the col type.
good luck! :)

How to input the current time into a mysql table from PHP

I'm using a mysql_query() in PHP to insert a value into a table in a database. One of the attributes of that table is "timestamp" which is supposed to be the current time that the query was made. How can I generate this? I tried using "time()" in PHP, but this is not inserting correctly in the query. When I insert what the time() function generates, it shows up as a default in my table, as: "0000-00-00 00:00:00". How can I generate the current time in order to input it into my table?
In your query, you need to set the value of that field to NOW() which is MySQL's function for getting a timestamp of the current time.
If you put your actual query in your question, I can help you with a more specific answer ;)
insert into table (datetime_field) values (now())
php function time() returns a unix timestamp that it's an integer value.
Go to php.net and view the codes for getting date and time and check whether you typed the codes correctly. If you did, then check if the format you are using in your code is similar to the one you are using in your table.

Comparing two time values from a MySQL database

I am trying to compare two sets of times in order to find out if they're overlapping. Here is what I have at the moment..
$sql = "SELECT * FROM schedule WHERE starttime>='$starttime' AND endtime<='$endtime' AND day='$updateday'";
Now this doesn't work as it appears you cant compare time values...so I am completely unsure how this can be done?
Datetime fields in MySQL are stored as (for example)
'2011-05-03 17:01:00'
so you should be able to do something like
$starttime = date('Y-m-d H:i:s', $timestamp);
where $timestamp is a timestamp of the time you are concerned about. Then continue with your query.
You can make timestamps by using mktime() or strtotime() (if starting from a string representation of a time, like from an earlier MySQL query), or just time() for the current time.
I understand that you are using "time" for your datatype. This shouldn't be a problem, since you CAN compare fields using the "time" type. You might want to set your error reporting level to maximum or output your $sql statment just before mysql_query to doublecheck that you are constructing query which can return results at first place. Also check that you have valid dataset for your query in database (has happend to me once while debugging).
Why don't you use use unix timestamp to compare?
$sql = "SELECT * FROM schedule WHERE UNIX_TIMESTAMP(starttime)>=$starttime AND UNIX_TIMESTAMP(endtime)<=$endtime AND day='$updateday'";
Also I think you're comparing strings, which I'm not sure if it would work.
Assuming that you're using the TIME type, your format of "10:00:00" should work.
Not to sound like your mother, but be sure to parameterize your query after you get it working.
I did run the SELECT statement on the phpmyadmin on the sql before trying to do it on the webpage and was great, the thing is to use it and be thinking in this before:
CAST('the_value_you_want_to_be_compared', AS the_type_you_want_to_compare)
example:
If you want to compare the date of a day and your table name is activities:
SELECT * FROM activities WHERE date = CAST('2015-10-29', AS date)
and so on...

Categories