I am writing a PHP site, in which I use some Mysql to access a DB.
I have a table named travel, which used to have a field named date from type Date (according to phpMyAdmin), and also I have a PHP variable $date from type string which stores a date in the format "Y-m-d"
when I needed to get all the elements from the table where the date was the same as the specified in $date, I was able to do it with a simple query like this:
"SELECT * FROM travel WHERE date=$date"
Now the problem is, I needed to change the date field data-type on the DB, from Date to DateTime, to also store hours and minutes.
On this particular query I am not interested on hours and minutes. I just need to get all the elements from the table where the date is the same as the specified in $date without considering the hours and minutes stored in the DB field.
what i am suposed to change to achieve this?
For example:
$date = "2030-12-25"
and
database
ID (int) date (DateTime)
1 1994-05-30 12:25:00
2 2030-12-25 15.20:00
3 2030-12-25 10:30:00
I need to get elements with ID 2 and 3.
PS: I know there are similar questions to this, but none of them were useful to me for different reasons
Edit:
The mistake that was preventing me to make this query work properly was also present on the old implementation without the time part.
I was omitting single quotes on the $date variable, and it caused the DBMS to not identify the date as a string.
old query:
"SELECT * FROM travel WHERE date=$date"
"SELECT * FROM travel WHERE date='$date'" fixed adding single quotes on $date
Also as KIKO Software answered the new one should include quotes too:
"SELECT * FROM travel WHERE DATE(date) = '$date';"
Simply change:
"SELECT * FROM travel WHERE date=$date"
to:
"SELECT * FROM travel WHERE DATE(date) = '$date';"
The function DATE() gets the date part from the column date.
you can use preg_match to get a substring of the date.
for example:
preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)
You need to format the datetime field in database by using Date function.
SELECT * FROM travel WHERE DATE(date) = '2018-07-15'
Related
I have a table called reports in MySQL(MariaDB) . There is a one(out of 5) column named logdate which is is of type datetime .columns stores the the date and time (in 24hr format) .
for ex here is sample value from that column
2021-04-10 09:35:00
I have to find all reports between a given date and time .
I get 4 variables from form data in PHP
$fromdate= $_POST['fromdate'];
$todate= $_POST['todate'];
$fromtime= $_POST['fromtime'];
$totime= $_POST['totime'];
$fromtime and $totime are just integers with value from 0-23 for hours.
For example the condition may be like get all data between 4th April 2021
from 5 o'clock To 8 April 2021 18 o'clock
i.e. From 2021-04-04 03:00:00 to 2021-04-08 18:00:00. There will be never condition on minutes and seconds .
My question is how to construct a datetime in PHP compatible with MySQL types so I can have good(efficient, there are millions of records in table ) search speed?
for ex
$select = "select * from reports where logdate between ? and ? ";
P.S: I tried saving date and time as integer as unixtime stamp. But when i convert from and to date received using strttotime() I facing time format issue due to bug in my code which so can use datetime only.
If you have any suggestion to improve efficiency of DB please suggest.Thanks
Hi this link may be of help in optimizing date comparison
MySQL SELECT WHERE datetime matches day (and not necessarily time)
This one below, will help you in formatting your strtotime() by using strptime()
https://www.php.net/manual/en/function.strptime.php
Also check your spelling or typo; you wrote "strttotime()" instead of "strtotime()" yours has an extra 't' in str"tto"time, it should be str"to"time, though without the double qoutes
Though I can't say for sure this is the most effective way but you can use hour(logdate) to compare with $fromdate and $todate
$select = "select * from reports where hour(logdate) between ? and ? ";
But it will only compare hour part. Please mention how you are getting date part to compare?
It is not a good idea to make a calculation on a field in the WHERE CLAUSE. In this case MySQL / MariaDB must calculate the value from this field to comapare it to see
if this ROW has this condition. So MySQL must read the whole table FULL TABLE SCAN and CANT use any INDEX.
A better way to do this is to store the calculation on fix site. Then MySQL calculated it only one time and can use a Index ( if there one) .
you can easy use a query like this:
$select = "SELECT * FROM reports where logdate between date(?) + INTERVAL ? HOUR AND date(?) + INTERVAL ? HOUR ";
to test see:
SELECT date('2021-04-05') + INTERVAL 16 HOUR;
result:
2021-04-05 16:00:00
Here is what is working for me after using Bernds solution .
I constructing datetime string in php
$fromstr ="$fromdate"." "."$fromtime".":00:00";
$tostr="$todate"." "."$totime".":00:00";
here is my query looks like for date of 7th April to 10th April
$ select = "SELECT * FROM reports where logdate >= '$fromstr' and logdate <= '$tostr' order by logdate";
after echoing it
"SELECT * FROM reports where logdate >= '2021-04-07 3:00:00' and logdate <= '2021-04-10 5:00:00' order by logdate";```
However I am not sure if can use index for logdate column and utilize it with above query.
I have events in my MySQL database wich all have a date. When I perform a SQL query to get all the events in the future, I get an error... Although, the date of the events are in the future. When I change my SQL request to select dates in the past, I get those from the future...
The SQL statement below has worked before, but for some reason it stopped working...
I use this SQL request:
$sql = "SELECT * FROM calendar WHERE date >= CURDATE() order by `date`";
I get an empty array as result...
However if I change the query to this, I get all the events in my database:
$sql = "SELECT * FROM calendar WHERE date <= CURDATE() order by `date`";
This is my database data. In my opinion, all data are in the future...
The format of the date table is a default date-type:
When I ask my server about the time echo date("Y-m-d"); I get todays date as result...
So where do I make a mistake?
You may be checking the wrong date field. Do you have a created date as well as a scheduled date?
I could be crazy from the cold medicine I am on at the moment, but your date table can't possibly be the date of your calendar items, the id filed is only an int(2), that seems kind of small.
maybe something simplier? I notice the column name in your table is date, which also is the name of a function date() that returns the date part of a datetime value. If thats the case
$sql = "SELECT * FROM calendar c WHERE c.`date` <= CURDATE() order by `date`";
would do the trick. Even if not mysql itself, the gui app youre using (seems like phpmyadmin to me) might get confused.
(btw, you forgot the closing tick of date in the order by clause)
getting an empty set is meaning nothing is found matching. I would look at your formatting of your date. The only other thing i was thinking is that it is comparing an unmatched type so just returns an empty set.
use DATEDIFF :
DATEDIFF
WHERE DATEDIFF(date, CURDATE) > 0
Before you make your query, run this one:
SET time_zone = '-2:00'; // or whatever your time zone is.
Don't ask me how or why, but I've truncated my table and re-inserted some data and my query seems to work just fine:
$sql = "SELECT * FROM `calendar` WHERE `date` >= CURDATE() order by `date`";
So, despite the fact the problems seems to be solved by truncating my table, I would like to know the answer to the why-question... Anyone can provide me with it?
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%'";
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...
I have a php page which allows a user to sort pieces of information by several factors. A new requirement is to sort by "all items which have been registered in the last 15 days". I store my dates in the MYSQL table as mm/dd/yyyy.
The information is passed and picked up on the same page using the $_GET variable but I am unable for some reason to get the code to work. I have looked on numerous website but am unable to find a solution that works.
Ultimately, the script would work as follows:
select all persons who's KDATE is within 15 days of today's date (e.g., if today is 8/19/2010, everybody who registred from 8/04/2010 and on would appear).
My script so far (which does not work) is:
if (isset($_GET['date'])) {
$query = "SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= KDATE
ORDER BY KDATE ASC";
}
Update 1:
KDATE IS TEXT - i apologize but the KDATE is stored as TEXT
Update 2:
The answer provided by Colin solved my issue. I will look into trying to convert the data into datetime format but am hoping the group can provide realistic benefits of doing so.
Thank you all again
First of all, it's a really bad idea to use VARCHAR instead of DATE if you want a collumn with dates only.
If you want to use a string as a date, you'll need to convert it with STR_TO_DATE() and you might wan't to use those instructions to correctly format your date.
This should do it:
SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= STR_TO_DATE(KDATE, "%c/%d/%Y")
ORDER BY STR_TO_DATE(KDATE, "%c/%d/%Y") ASC
Because kdate is VARCHAR, you need to use STR_TO_DATE to change it to a DATETIME.
You need to fix kdate data that does not fit that pattern (mm/dd/yyyy) before running this:
SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= STR_TO_DATE(KDATE, 'm/%d/%Y')
ORDER BY STR_TO_DATE(KDATE, 'm/%d/%Y') ASC
This means that an index on kdate is useless, because of having to change the data type.
Once it's a DATETIME, you can use DATE_FORMAT to change the format as you like.