$months = array('January', ... , 'December');
$sql='
SELECT *
FROM `residencies`
WHERE `Year` = 2010
ORDER BY array_search($months,`MonthFrom`) `DayFrom`';
Doesn't work (i already feared that), it's supposed that the elements are sorted by first the position of MonthFrom in the array $months, and those who have the same position should be sorted by DayFrom. I know there are other way's to treat dates but for this query i am bound to this date structure, any help is appreciated
$month_arr = array("January","February","March");
$months = implode("', '", $month_arr);
$query="SELECT * FROM residencies WHERE year = 2010 ORDER BY FIELD('MonthFrom', '$months'), `DayFrom`;
$sql='
SELECT *
FROM `residencies`
WHERE `Year` = 2010
ORDER BY DATE_FORMAT(`MonthFrom`,"%M") `DayFrom`';
But this will sort them according to the alphabetical order of the name of the month ? Do you really need that ?
You can also sort them according to MonthFrom and them convert it to text in your php code."
It looks like you're trying to use a PHP function within an SQL statement. If you need to sort by MonthFrom, which is the name of the month, try something like this:
SELECT *
FROM `residencies`
WHERE `Year` = 2010
ORDER BY FIELD(`MonthFrom`, 'January', ..., 'December'), `DayFrom`;
(you can fill in the rest of the months)
I presume from the question that you have a month field in the database which is stored in string format, which would, as other commenters have said, make sorting tricky, hence why you were trying to put the months in order using the array.
Others have come up with valid ways to achieve this given that constraint (I think luckytaxi's answer is probably the best so far), but I would say that if you do have months stored in the database in string format, then you definitely have a poor database design, and if you have the option, you should consider changing it.
MySQL can store full dates using the DATE or DATETIME data types, so if you're storing your days, moths and years separately at the moment as it appears, you should change to storing them together in a single field. You can still query them separately, eg if you just need the month, or in any combination - MySQL has very powerful date handling features (and so does PHP for that matter).
Related
I have a PHP scirpt that is always querying all the data from a database table and it's getting pretty slow. I really just need the data of a specific month and year.
Is there a simple way to get only those entries? For example, everything from February 2013?
The column that stores the dates in my table is of type datetime, if that applies to the solution.
You can add that condition in the WHERE clause of your select statement. I would recommend using BETWEEN operand for two dates:
SELECT myColumns
FROM myTable
WHERE dateColumn BETWEEN '2013-02-01' AND '2013-02-28';
If you mean to say you want everything beginning with February 2013, you can do so using the greater than or equal to operator:
SELECT myColumns
FROM myTable
WHERE dateColumn >= '2013-02-01';
EDIT
While the above are my preferred methods, I would like to add for completeness that MySQL also offers functions for grabbing specific parts of a date. If you wanted to create a paramaterized query where you could pass in the month and year as integers (instead of a start and end date) you could adjust your query like this:
SELECT myColumns
FROM myTable
WHERE MONTH(dateColumn) = 2 AND YEAR(dateColumn) = 2013;
Here is a whole bunch of helpful date and time functions.
You should index the datetime field for added efficiency and then use Between syntax in your sql. This will allow the mysql engine to remove all records that you are not interested in from the returned data set.
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 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)
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 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.