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)
Related
I'm trying to query a database with a between 2 dates... The problem is the column that I am querying contains dates that are currently formatted like this "01/01/2014" (dd/mm/yyyy) with a column type of VARCHAR.
At the moment, I can't convert the column to a date type.
Basically when I query the table because it's not set to date type the between query doesn't return the correct rows...
Has anyone else come across this problem, is there something I can change within the query?
$this->db->where('IssueDate >=', '02/12/2013');
$this->db->where('IssueDate <=', '22/01/2014');
$query = $this->db->get('MYTABLE');
Thanks guys.
The solution is to use str_to_date():
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') >=", "'2013-12-92'");
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') <=", "'2014-01-22'");
$
You may not have any control over the database. But you do have control over your own constants. You should get used to the ISO standard YYYY-MM-DD for such constants -- unambiguous and accepted correctly by most databases.
I might suggest creating a view on the table in the database that transforms the string date columns you have into the following format... YYYYMMDD
That format is sortable and can easily be compared versus other similar formatted dates - you can even do date arithmetic with it.
Keep in mind that a view does not copy the table or add any performance overhead. It is often a good idea to access any table through a view even if initially you do not need to perform any manipulations on the underlying table - it will help if you later find you do need to perform them.
use BETWEEN clause with STR_TO_DATE(). Check below code:-
$wh = STR_TO_DATE(`IssueDate`,'%d/%m/%Y')." between '02/12/2013' and '22/01/2014'";
$this->db->where($wh);
Expect it'll give You perfect result.
I am creating a mysql db with a php frontend. The data it will use is extracted from another larger db and contains a date/time field which looks like this - 20120301073136 - which records when an event happened.
I understand that this might be a UNIX timestamp? Not sure.
I want to be show this field in the tables in my PHP webpage as a readable date and time -
ie something like 01-Mar-2012 07:31:36 or similar
Should I try and convert it with SQL command or let PHP format it? And, what is the code to do so?
BTW, it is important that I can sort the data (in SQL and in the PHP table) into date order - ie in the order that these events happened.
Thanks in advance for your help - Ive learnt a lot here already
J
You can convert it to a datetime directly in your SQL query. Example:
select cast(20120301073136 as datetime)
You can also order that with no need to convert it since it is a number in the format YYYYMMDDHHmmss
select * from yourTable
order by yourDateTimeField
You should make use of the MYSQL DATE functions. Check the docs before asking simple questions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html.
Also you can sort the dates directly in your query using ORDER BY.
I have a DB table with relation 1: N where N represents multiple dates for one event. The column with the dates is DateTime type, and I would like to keep the Time option for later use, but it won't be so bad if I have to change it to Date type.
The problem comes when I have to show those multiple dates in some GUI. I get the dates with the GROUP_CONCAT function which means that in JavaScript I operate with a string with comma-separated values representing the different dates, which by now is in the default SQL DateTime format - YYYY-mm-dd hh:mm:ss.
I use the split(',') function to get each date-time value and what I can do is to change the type of the SQL column to Date so when I split the string in JavaScript to end up with YYYY-mm-dd values. Which should be reversed to dd-mm-YYYY for the GUI.
I'm not sure how to proceed here. I have in mind two main options:
First: Maybe there's a way to use dd-mm-YYYY format in SQL which will solve all the problems.
Second: some kind of (complex?!?) String manipulation in JavaScript to split the string of dates into an array with multiple elements and then try to format each element the way I need.
Honestly - I want to avoid the second option, but don't know if the first is possible, and maybe, there's another way that I haven't think of.
Try this..
SELECT GROUP_CONCAT(DATE_FORMAT( date_time_column, '%d-%m-%Y' )) FROM test_table;
First of all I advise to use the native Date/DateTime-format everywhere in your code and only use localized variations like dd-mm-yyyy only where you really want to display it. First reason: it is consistent in your code. Second reason: Sorting.
Example:
2012-03-01 > 01-03-2012
2012-05-12 > 12-05-2012
2012-01-03 > 03-01-2012
Sorted by the native format you'll get...
1: 2012-01-03
2: 2012-03-01
3: 2012-05-12
Sorted by the output format dd-mm-yyyy it will look like this...
1: 01-03-2012
2: 03-01-2012
3: 12-05-2012
...and I doubt this is what most people want.
Adjusting the output via SQL
You can change the output in your SELECT-query , most RDBMS offer functions for this. For example, in MySQL it is DATE_FORMAT, which looks like this:
SELECT DATE_FORMAT(NOW(), '%d-%m-%Y');
Adjusting the output via SQL
You can also change the output using php, which is explained here.
Adjusting the output via JavaScript
It isn't hard to do this in JavaScript, too: Here is a great SO post which explains it in detail.
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'll explain my goal first: I want the user to query the database, and return rows only if those rows have been updated since their last query. No sense returning data they'd already have. So I created a column called 'lastupdated', a timestamp type which autoupdates every time any content in the row is updated. This works fine. Now, I want to form the query correctly. The user will have their previous query's timestamp saved, and via php will use it to compare their previous query's time with the time each row has been updated. If the row was updated after their last query, the row should be returned.
I made something like this,
SELECT * FROM users WHERE '2011-02-26 01:50:30' <= lastupdated
but its obviously much too simple. I checked the MySQL manual and found this page MySQL Time/Date Page. I'm sure the answer is here, but I've read through it any nothing really makes sense. I have a timestamp in the same format used by the MySQL timestamp type, but I don't know how I will compare them. Thank you very much for your help.
That query is exactly how you'd do it. As long as a stringified date-time is in MySQL's preferred format (yyyy-mm-dd hh:mm:ss), then it will be internally converted into a datetime value, and the comparisons will go ahead.
You'd only need the date/time functions you found if you want to do something more complicated than simple "greater/less than/equal" type comparison, e.g. "any records that have a December timestamp".
As Marc said, your code should work. But you probably want to do this programmatically with a variable for the time instead of the literal.
If you don't have the date-time specified as a string, but rather as a timestamp (e.g. from using the php time() function), then you can use the following query:
$query = "SELECT * FROM users WHERE FROM_UNIXTIME(" . $timestamp . ") <= lastupdated";
The key is the FROM_UNIXTIME() MySQL function.