PHP Need help with MYSQL DB and dates - php

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)

Related

PHP count mysql row with changed date format

I have next problem:
My table date format was: LIKE 2017-01-08 18:50:25 (with time).
When i use sql query like
'SELECT date FROM table WHERE date = "2017-01-08"'
My row was empty, i need COUNT all row with same (today) date WITHOUT TIME.
Note, i will not change INSERT date time!
Use DATE() to get the date portion of the datetime field and compare it to today. Use COUNT() to get the number of records that match your query.
SELECT count(*) FROM table WHERE DATE(date) = CURDATE()
You can also replace CURDATE() with NOW(), CURRENT_DATE(), and CURRENT_DATE
You can also use it in the following way
'SELECT date FROM table WHERE date_format(date,'%Y-%m-%d') = "2017-01-08"'
the date_format is mysql function which return date according to your pattern the above pattern only return the Y-m-d from the datetime
I hope it will help you
plz change your statement equal operator to greater than
'SELECT date FROM table WHERE date > "2017-01-08"'
as by default if time portion is not present then it is putting 00:00...

Show all results from database where mm/dd/yy date is "today" or greater

I am using HTML input type="date" to allow users to input appointment dates.
Now I want to query the database and show all appointments that are "today" and in the future.
Not dates that have already passed.
Here is my SQL Script
$today = date('d-m-Y');
$sql = "SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF('$today', `date`) >= 0
ORDER BY `id` DESC";
Can someone guide me as to how I can achieve this?
I have seen several directions online but I want to have the sorting done at the moment of query.
I have solved the issue!
My date() format was incorrect because HTML input type="date" inserts YYYY-MM-DD into the database =/
$today = date('d-m-Y');
should be
$today = date('Y-m-d');
My operator >= should have been <= to show today and future dates.
Thanks everyone for the help. I should have tried fixing it for 5 more minutes before posting.
Why are you using PHP to compare dates in the database? I assume its a date field so you can use MySQL to do it for you:
SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF(date_format(now(), '%Y/%m/%d'), `date`) >= 0
ORDER BY `id` DESC
None of the responses have specified sargable predicates. If you perform an operation on a column in the where clause, there is no discernible stopping point.
where ... some_function( some_field ) = some_constant_value ...
Even if some_field is indexed, a complete table scan must be performed because there is no way to know if the output of the operation is also ordered.
From my understanding the date column is in a sortable form -- either a date field or a string in lexically sortable format 'yyyy-mm-dd'. That being the case, don't do any operation on it.
where ... some_field >= now() ...
Thus the system can use the result of now() as a target value to find exactly where in the index to start looking. It knows it can ignore all the rows with indexed values "down" from the target value. It has to look only at rows with indexed values at or "up" from the target value. That is, it performs an index seek to the correct starting point and proceeds from there. This could mean totally bypassing many, many rows.
Or, to put it bluntly, ditch the datediff and do a direct comparison.

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

Getting wrong answer with mysql date query

Here is my table
I am executing a query that give me result of fields whose item_valid_from must be greater than today's date and item_valid_to must be less than today.
My query is
select *
from tbl1
where item_valid_from >= CurDate()
and item_valid_to < CurDate()
Any Solution?
I would advise you to change item_valid_* field formats to DATE field format. You will save you a lot of trouble in the future.
But ok, if you don't want to do that, then you can use STR_TO_DATE() function:
SELECT *
FROM `table`
WHERE CURDATE() BETWEEN STR_TO_DATE(`from_field`, '%d-%m-%Y') AND STR_TO_DATE(`to_field`, '%d-%m-%Y')
demo
Assuming the datatype item_valid_from and item_valid_to is DATE, TIMESTAMP, etc, then you have your operators backwards. Think of the time as seconds since 1970, since this is how it is stored in unix time. That means that item_valid_from is going to be smaller than item_valid_to, and you want it to display when today is somewhere between them. You want the item_valid_from to be less than or equal to now, and the item_valid_to to be greater than now (not in the past).
SELECT *
FROM tbl1
WHERE item_valid_from <= CURDATE() AND item_valid_to > CURDATE()
See this SQL Fiddle for an example, only 2-4 are valid and show up in the results being valid from a date in the past and expiring on a date in the future.
You have to use following query which change current date format then compare date and fetch result :
SELECT *
FROM tbl1
WHERE date_format(item_valid_from,'%d-%m-%Y') >= date_format(CurDate( ),'%d-%m-%Y')
AND date_format(item_valid_to,'%d-%m-%Y') < date_format(CurDate( ),'%d-%m-%Y')
Please Check this :http://sqlfiddle.com/#!2/561d0/2

Time date comparsion in PHP

I have a table in my database that stores user input as a start date and end date after that, my users will have to select a time range and I have to display those records in the table that are within this time range?
Tried stritotime(); and many other unctions but somehow I can't get the right results..
Any possible solution would be appreciated.
Thank you!
May be with:
SELECT count(*) FROM `table`
where
created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 06:42:50';
or use between:
SELECT count(*) FROM `table`
where
created_at between '2011-03-17 06:42:10' and '2011-03-17 06:42:50';
it depends on your record what u want to display because i didnt see your table and an exemple what you you really to do so just change count(*) and get whatrecords you want.
EDIT:
if the users will select a range of time then they will be variables
then it will be something like that
SELECT records FROM `table`
where
created_at >= '".$var_start_time."' and ended_at <= '".$var_end_time."';
you can use in mysql query BETWEEN ... AND ... comparasion operator
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
You can simply do this in your SQL, which is the recommended approach. If you have these start and end times stored in your database table as native DateTime types, for example, you can use your DBMS' Date functions to select the range as a UNIX timestamp (if that's what what you want).
SELECT UNIX_TIMESTAMP(`start_time`), UNIX_TIMESTAMP(`end_time`) FROM `table` WHERE `start_time` > INTERVAL -1 DAY AND `end_time` < NOW();
That's one example (assuming you're using MySQL) where you select all rows in the table where the column start_time is within the past 24 hours and the end_time column is up to the current server time.
To get the formatted date and then do the conversion to a UNIX time-stamp in PHP use:
SELECT `start_time`, `end_time` FROM `table` WHERE `start_time` > INTERVAL -1 DAY AND `end_time` < NOW();
and then in PHP you can do:
$result['start_time'] = strtotime($result['start_time']);
$result['end_time'] = strtotime($result['end_time']);
Keep in mind that strtotime expects the formatted date to comply with PHP's date parsing rules found here.
P.S: The function in PHP you're looking for is strtotime not stritotime.

Categories