PHP MYSQL Question on comparing dates in a Query - php

I am trying to construct a mysql query string to pull out certain records but only if the date in the database is greater than the current date.
So I have this so far and I am not sure if this is a legal syntax...
date_default_timezone_set('America/Los_Angeles');
$current_date = date("Y-m-d");
$sql = "SELECT * FROM `coupons` WHERE status = 1 AND end_date > '$current_date'";
Thanks for your help.

It's legal syntax. You can use one.

I use CURRENT_TIMESTAMP in general, i.e.:
SELECT * FROM `coupons` WHERE status = 1 AND end_date > CURRENT_TIMESTAMP
Do you have a need to compare to the LA timezone? CURRENT_TIMESTAMP will use the local MySQL server time (but that should technically be what the date values are stored as, as well).

Related

MySQL query: Date > Date not working

Hi there please help me if you can. Here is my senario:
I have a MySQL database with a column that holds a date in the form of a varchar. The format of the date is the following 29/05/2014 (i.e. d/m/Y).
I'm trying to compare the value of this column with todays date and return any rows where the date is earlier than todays date.
I'm using a php variable to store todays as follows:
$date = date("d/m/Y");
Here is my SQL query:
SELECT * FROM patients WHERE last_seen < '$date'
What gets returned
So what is returned is very unusual (to me). All records where the last_seen "day" is less than todays "day". It seems to be overlooking the month and year. So in other words if I last_seen = "30/05/2014" and todays date is "29/05/2014" this record is still returned.
Does anyone have any ideas what I might be doing wrong here?
Thanks
You really, really shouldn't store dates in a varchar field - use date or datetime or timestamp data type.
That said, sometimes you don't have control over the database and you have to deal with somebody else's bad design decision. In this case, to compare dates, convert the varchar strings to dates and compare them that way. So, in your case, you can have something like this:
$date = date("d/m/Y");
and then
SELECT * FROM patients WHERE str_to_date('last_seen', '%d/%m/%Y') < str_to_date('$date', '%d/%m/%Y')
or simpler
SELECT * FROM patients WHERE date(last_seen) < current_date
This way you are actually comparing dates and not strings containing dates. Naturally, this assumes that all dates are stored in the same format.
EDIT: I just tested the last option - and, apparently, date('30/05/2014') returns NULL on my system (mysql 5.5 on linux), hence I suggest the best way is
SELECT * FROM patients WHERE str_to_date('last_seen', '%d/%m/%Y') < current_date
You need to store your date as DATE or DATETIME in your database.
Then you can use:
SELECT * FROM patients WHERE DATE(last_seen) < CURRENT_DATE

Search date in database PHP

When I was a start up student in PHP I made my database to store dates the date and time together, now I have a big problem, I have already in the database over 3000 orders but when I want to make a search with dates am I in big trouble because the dates and time is together in one field, I tried to make the query like where date LIKE '%$date' but I'm getting no results, has anybody any idea what I can do now?
And also how can I change the whole database it should be all dates and time separately and it should not effect my database?
UPDATE:
The data in the database looks like, 10/16/2012 5:00pm
Appreciate any help.
Why %$date? You should do the opposite.
WHERE date LIKE "".$date."%"
In response to the sections of your question:
1. Finding the dates you need in the current schema.
Based on your edits, use:
<?php
$query = "SELECT * FROM table_name WHERE `date` LIKE '{$date}%'";
?>
A query similar to what you posted should help you:
<?php
$query = "SELECT * FROM table_name WHERE `date` LIKE '%{$date}%'";
?>
Please note that your use of % in your question ( '%$date' ) will only match values that end with $date, while the pattern in my example ( '%{$date}%' ) will match values that have $date anywhere in them. Alternatively, you could use '{$date}%' to match date at the beginning of the value -- not sure which you want.
2. Updating your schema to split date and time into two columns.
The first step you should take here, is to add two columns ( date_only and time_only ) to your table. Next, update your code to process and store this information in addition to the 'all-in-one' date column your are currently using; you don't want to break your current codebase by switching over in one step. Once you can verify that date/time data is being written the way you want it to be, the third step is to read (and log) from the new date/time columns along with your production reads to date. Once you can verify that the reads are working as planned, switch over your dev environment to read from the new columns and test until you are confident that everything works.
You can do the following:
$date = "2012-03-08";
$sql = "SELECT * FROM table WHERE date => '$date 00:00:00' AND date =< '$date 23:59:59'
Edit: Seeing your edit, this does not work anymore. You will need to convert your date column to a proper MySQL datetime or TIMESTAMP type.
At the current database design you could use something like this:
date
$date = "10/16/2012";
$sql = "SELECT * FROM table WHERE date LIKE '$date%'
time
$time = "5:00pm";
$sql = "SELECT * FROM table WHERE date LIKE '%$time'
If it's a DATETIME field, you can use
WHERE DATE(datetime_field) = '01-01-2012';
or (better, as it can use indexes)
WHERE datetime_field >= '01-01-2012 00:00:00' AND datetime_field <= '01-01-2012 23:59:59';
this is what worked for me
$date = "2018-05-13";
"SELECT * FROM $username WHERE reg_date LIKE '%$date%'";

Mysql Unix Timestamp Store?

I got a bit of a problem here. My database stores unix timestamps as a string 2011-09-01 20:22:36 and I need it as a Unix Timestamp ########### so I can compare it using a > then symbol. But I also need to have it automatically set the timestamp on update (ON UPDATE CURRENT TIMESTAMP) as well as have a default of the timestamp which is not really that important cause I can do that in PHP if I need to.
How can I do this? timestamp is now a date/time combo string and not a integre so I cannot compare it?
My comparison string is
$sql = sprintf("SELECT nid, field_date_value, field_movie_location_value FROM content_type_mobile_event WHERE updated<'%s'", $vid);
Incase anyone is wondering.
Use the UNIX_TIMESTAMP() function to convert it inside your query. If you must compare it to a Unix timestamp from PHP, it is easiest to allow MySQL to handle the column's conversion on its end.
$sql = sprintf("SELECT nid, othercols FROM content_type_mobile_event WHERE UNIX_TIMESTAMP(updated) < '%s'", $vid);
You can compare DATETIME columns with operators like > or <, so I don't see what the problem is. For example, you can do this :
SELECT *
FROM table
WHERE your_column > NOW() - INTERVAL 2 HOUR;
If you really need unix timestamps (you shouldn't, it's a bad habit PHP users have), you can use the function UNIX_TIMESTAMP :
SELECT UNIX_TIMESTAMP(your_col)
FROM table;
You can also use FROM_UNIXTIME to convert a unix timestamp to a valid date :
SELECT *
FROM table
WHERE your_column > FROM_UNIXTIME($data)
This is what I would use if I really had to use a unix timestamp, but most of the time, you can do without.

PHP Need help with MYSQL DB and dates

I have two fields in the DB stating the start-time and end-time, and another field that may or may be not set that is called 'date'.
Upon SELECT, I need to know if I am in or out of the time range, and if the date is set if I am in the time range only if the date is today.
What is the best way to do that in PHP ?
Thanks!
My original answer was not answering your question at all I realised. Hopefully this will.
$query = "SELECT IF(".date('H-m-s')." BETWEEN start-time AND end-time,
'inRange', 'notInRange') WHERE `date` == CURRENT_DATE OR `date` IS NULL";
If date('H-m-s') from PHP is in the range it will return the string "inRange" otherwise it will return the string "notInRange" and will match it on the records in your db where date is either NULL, or the current date.
You could also make the SQL statement like this:
SELECT IF(TIME(CURRENT_TIMESTAMP) BETWEEN start-time AND end-time, 'inRange',
'notInRange') WHERE myDate == CURRENT_DATE OR myDate IS NULL;
Upon SELECT, I need to know if I am in or out of the time range
SELECT (NOW() BETWEEN date_min AND date_max) is_happening_now
FROM your_table
is_happening_now contains a boolean containing true if NOW() is between date_min and date_max. Obviously, that would create a separate column that you might not need, you can put the condition in the WHERE clause if necessary.
if the date is set if I am in the time range only if the date is today.
I didn't really understand this part, but you can extract the date from a DATETIME with the DATE function (for example : current_date = DATE(some_date)

Get records from the current data

I need to list the records from the current day, in the db the date is in format 02/02/11
Database
09/01/11
13/01/11
18/02/11
19/02/11
20/02/11
...
Question:
How to do using SQL command + PHP?
Current (working...)
$today = date("Y/m/d");
$sql = SELECT * FROM places WHERE STR_TO_DATE(data, '%d/%m/%y') >= '".$today."' ORDER BY DATE_FORMAT(data, '%d/%m/%y') ASC LIMIT 8";
But all records are listed
I would strongly recommend updating your stored values to the standard MySQL date field type - this will greatly simplify any queries you write and enable you to use all the standard MySQL date and time functions.
You can follow the answer here Converting a date in MySQL from string field to find out how to convert your data.

Categories