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%'";
Related
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'
I'm trying to set up a query that will search a MYSQL database and only pull in the rows from the database who's expiry_date is after todays date.
I would also like to be able to work out how many days or weeks there are remaining from todays date to the expiry date of the rows in the database that match the above query.
I think that in order to get the current date I would have to set up a variable of $date = time(); which I will then later be able to use to compare against the expiry_date column in the database. However I am now stumped as what to do to achieve the required result. I'm not exactly a PHP noob but I'm not an expert either, so please go easy on me ;)
Thanks in advance!
If the Column you want to check is a DATE(TIME), try
$sql="SELECT column FROM table WHERE expiry_date > CURDATE()";
If you saved the UNIX timestamp, you can simply use
$sql="SELECT column FROM table WHERE expiry_date > '".time()."'";
If you use the first with "NOW()" or the second, you'll proably get results for the current day.
If this is not acceptable, try "mktime(0, 0, 0)" instead of time();
Use this query
$query = "select timestampdiff(days,'$exipry_date','$now')";
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.
i've run into the following problem:
I had to migrate a database from MS SQL Server where some fields contained date values that weren't stored as such. For example there was a field "offers" with an "validfrom" and "validto" field. Sadly, they used text fields (varchar) for that type of input and im having a hard time now to filter it properly by date. An example as follows :
datefrom = "21.01.2012"
dateto = "21.05.2012"
Now im trying to sort out the old entries by date using
$curDate = date('d.m.Y'); // Outputs 19.03.2013
in my PHP PDO i use the following query
$query = "SELECT * from mytable where validtill >= '$curDate'"
which would output
$query = "SELECT * from mytable where validtill >= '19.03.2013'"
still i am getting old entries with date entries from 2011. I think i am missing something - maybe i cant compare strings as "date". I tried changing the field from vharchar to date but when i do, the whole imported data gets messed up.
Any advice?
Thanks!
In your question, you say you had to migrate from MS Sql Server -- what database did you migrate to? You need to convert the varchar field to a date to do a date comparison.
Assuming MySQL, then you could use str_to_date. Something like this should work:
select str_to_date(dtfield, '%d.%m.%Y')
from yourtable
where str_to_date(dtfield, '%d.%m.%Y') > str_to_date('1/20/2012', '%m/%d/%Y')
SQL Fiddle Demo
Assuming you're still in SQL Server, then you'd have to strip out each part of the date to put the date in a format SQL Server understands and then use CONVERT to change its datatype to a date:
SELECT CONVERT(datetime,RIGHT(dtfield,4)+SUBSTRING(dtfield,4,2)+LEFT(dtfield,2))
FROM yourtable
WHERE CONVERT(datetime,RIGHT(dtfield,4)+SUBSTRING(dtfield,4,2)+LEFT(dtfield,2)) > '1/20/2012'
More Fiddle
Right. That will do a string comparison and seems like you have the DAY first. Which means march 21, 2013 is greater than march 19, 2014... because the first thing it compares to sort is the day.
This text string comparison would work if you could rearrange the data to Y.m.d, that way 2013 > 2012 > 2011, and 2013-02-xx > 2012-02-xx...
My advice would be to make a new column in your database, and you can use a PHP script to convert and store the new correct values as dates.
Maybe that:
$query = "SELECT CAST(m.field as date) as field, m.* from mytable as m where m.field >='" . date('Y-m-d') . "';";
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?