Comparing two time values from a MySQL database - php

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...

Related

Date insert php

I guess I have it partially working, but it inserted a random year,day & month rather than the actual date now.
This is in my "Post Article" .php file.
<?php
$date = date('Y-m-d', $timestamp);
What I have setup for my SQL table is this:
however it ends up showing this date:
any ideas?
If you don't pass a second parameters to date() it defaults to now.
$date = date('Y-m-d');
It would be even easier to do this in your SQL (and simultaneously make your PHP code simpler and easier to maintain). You can use several MySQL functions like NOW() and CURDATE():
INSERT INTO tablename (date) VALUES(NOW())
INSERT INTO tablename (date) VALUES(CURDATE())
FYI, I can't say for sure since I can't see your code, but I suspect $timestamp doesn't exist in your code. That will cause you to get the value you see in your database.

Using Yii Framework to query the database for a field with datetime type. I need to query by date only

Im trying to avoid reworking a bunch of code. Keep in mind im using the yii framework. I have a table in mysql database that has one field name datetime is the type is datetime. So it holds something like this.
2014-01-31 09:20:00
I need to query that table with only the date along to find all records for that date.
$date = 2014-01-31
$app = Appointments::model()->findAllByAttributes(array('datetime'=>$date));
My problem is that it will not return anything because the time is also included in the datetime record. Is there a way for me to either add a universal time that mysql will read and select anytime or can I do some kind of query that will just ignore the time and just select the dates?
You can use a condition datetime BETWEEN '2014-01-31 00:00' AND '2014-01-31 23:59'. (By the way, consider a better name for that column.)
But you cannot express that with findAllByAttributes, you will need something like this:
$date = '2014-01-31'; // the date
$start_time = $date . ' 00:00:00';
$end_time = $date . ' 23:59:59';
$apps = Appointments::model()
->findAll('datetime BETWEEN :start_time AND :end_time', array(
':start_time' => $start_time,
':end_time' => $end_time,
));
Edit: I see other answers recommending a different approach - asking MySQL to convert its stored value to match your format. That does not scale! If you have thousands of records, this does not make a significant difference, but if you get a few orders of magnitude more than that, you'll see nasty delays.
If you just ask MySQL to match a value without converting it like I suggested, you can put an index on this column and get answers very quickly.
If you ask MySQL to convert the stored values, it has to convert each record in the table to determine if it's a match. Other databases can put an index on the converted value, but MySQL cannot, therefore each time this query is run, it has to convert each record again...
$sql = ".........where date_format(datetime,'%Y-%m-%d')={$date}";
$app = Appointments::model()->findAllBySql($sql );

Query The Table Using PHP Substr() Function

I have a case to query the table using WHERE clause in which I just want to use a 'piece of string' from the field to compare to my string as a condition for selecting.
In the picture, I just want to use month and year from date field to compare with $indicator = 03/2013.
Any idea how can performing the query, so the result would look like:
Any help will appreciated. Thank you in advanced.
Most likely, you aren't dealing with strings in the table, as it's most likely dates. If you are dealing with strings, it's
SELECT * FROM table WHERE DATE LIKE '%03/2013';
where % is a wildcard like * in the old dos days
For actual date fields, (which you would be better off using), it's a simple between
SELECT * FROM table WHERE DATE BETWEEN '01/03/2013' AND '31/03/2013'
Note that you need to follow proper date formatting for your engine, for something like MySQL you'd be better off using '2013-03-01' and '2013-03-31'
The hardest part will be coming up with the first and last day, but for that, I'd look at strtotime(), which allows you to put in things like 'Last day of the month' and such. You'd have to format it correctly, and play with the strings, but it's rather trivial with what strtotime() can do.
USE LIKE in your mysql query instead of =
Reference : (source)

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! :)

Question regarding MySQL timestamp comparisons

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.

Categories