Mysql Get table result between two dates - php

I know my question is similar to other question already answered but my issue is different because I need some alternative or advice no how to go the other way around.
My issue is: I want to get values between either two dates or one according to what user wants..
When User request data of one day.. php query data successful.. but problem is when data requested is between two dates..
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '$first_date' AND
`meta_transaction_date` <= '$second_date' ");
return $query->result();
I get an empty set...
So I thought may be the values are not submitted correct.. so I echoed the values to see if they are correct or not. I find they are correct...
$first_date = 09/13/2014;
$second_date = 09/19/2014;
But if I try to put the value like
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014' AND
`meta_transaction_date` <= '09/19/2014' ");
return $query->result();
I get my result back correct.. so is there anything am doing it wrong??

Change the type of meta_transaction_date to DATE as that is what it is! Also use the standard 'yyyy-mm-dd' when passing in DATEs.
Your problem probably stems from string ordering of the 'mm/dd/yyyy' US date format which is horrible for coding. If you wish to display the DATE in this format, convert it when SELECTing the final output.

MySQL has a built in function called Between that you can use like this:
SELECT * FROM table_name WHERE date_column BETWEEN 'start_date_parameter' AND 'end_time_parameter'

Try to cast the date first , and then with between statement:
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` BETWEEN
date_format(str_to_date('$first_date', '%d/%m/%Y'), '%Y-%m-%d') AND
date_format(str_to_date('$second_date', '%d/%m/%Y'), '%Y-%m-%d')");

$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014'
AND `meta_transaction_date` <= '09/19/2014' ");
Since the above seems to be working fine, the problem is in your code.
$query = $this->db->query("SELECT `meta_transaction_date` FROM meta_receipt_data WHERE
meta_transaction_date BETWEEN "
.date( "Y-M-d", ( strtotime($first_date) ) )." AND "
.date( "Y-M-d", ( strtotime($second_date) ) ) );
A word of advice, do not use queries like SELECT * as they will degrade performance of your application. And I just read in your comment to your own question:
I have set the type as Varchar
Do not do that. It is best to use the DATE type to store dates. You can use the query:
ALTER TABLE `meta_receipt_data`
MODIFY `meta_transaction_date` DATE NOT NULL;`
Well, that is assuming you wish to keep the column to not accept null values.

I found that the value had space before and after so I use $first = trim($first_date); and problem solved...

Related

Codeginiter JOIN query with DATE between and LIMIT not working

I am trying to get the details of a persons based on the user input age (Integer). Now my query always returns null Array() whenever I execute the below code. I haven't specified the $postdata array. You can see I have used $postdata['ageto'] and $postdata['agefrom'] are used in calculating $agefrom and $ageto
$now = new DateTime();
//Converting _POST age to Date
$agefrom = date("Y-m-d",strtotime($now->format("Y")-$postdata['ageto'].'-'.$now->format("m").'-'.$now->format("d")));
$ageto = date("Y-m-d",strtotime($now->format("Y")-$postdata['agefrom'].'-'.$now->format("m").'-'.$now->format("d")));
$this->db->select('uacc_id, uacc_username, name, dob, city, education');
$this->db->from('user_accounts as a');
$this->db->join('personal as b','a.uacc_id = b.pruserid','INNER');
$this->db->join('profession as c','a.uacc_id = c.puserid','INNER');
$this->db->join('location as d','a.uacc_id = d.luserid','INNER');
$this->db->where('dob >= ',$agefrom);
$this->db->where('dob <= ',$ageto);
$this->db->limit(10, $offset);
$query = $this->db->get();
return $query->result();
I have suspected that my input post is not fetching the data properly. So I have replaced it with my simple query select * from... where dob >.... and it worked well. So there is no problem with _POST variables. I am not sure what I am doing wrong. Can some one help me.
I think you have to specify to which table DOB belongs like a.dob. Sorry for the post but I could not comment. Hope this helps.
The select field should add the table name
$this->db->select('a.uacc_id, a.uacc_username, a.name....); // example
and your where add table name too.
$this->db->where('b.dod >= ', $agefrom); // example
or you can output the sql command.
You can look here

use the like command in MySQLi and php for a datetime field

I am attempting to run a query based on a date to get everything changed today, however the field that has the date is a datetime field, which I can't change. The value in my date_modified field looks like 2013-10-25 07:05:43. I know the query works without the date. If I just use Navicat and run the query's where clause as:
WHERE inventory.date_modified like '2013-10-25%'
It runs fine. I found a few ideas in other SO posts and when I try to put it into my php code as:
$today = date("Y-m-d"); $today = '%' . $today . '%';
and then my where clause is:
WHERE inventory.date_modified like $today
I get the fatal error of trying to parse a non object. I know there is a value in $today, but I am unclear how to do this with my php code?
Best solution was the N.B.'s in the question comment. Because, if you have index on field date_modified, it will be used.
So, if you have date formated as Y-m-d, like you have in $today, you can do:
$sql = "
...
WHERE inventory.date_modified BETWEEN '$today 00:00:00' AND '$today 23:59:59'
...
";
Another example would be, to use DATE() function, to get date part from datetime:
$sql = "
...
WHERE DATE(inventory.date_modified) = '$today'
...
";
but, this example is not good if you have index on field date_modified, because it will be ignored, and whole table will be scanned.
You Forget to set the quotes on database value:
WHERE inventory.date_modified like '$today'
Try this code:-
$today = '2013-10-25';
SELECT * FROM inventory WHERE DATE_FORMAT(inventory.date_modified, "%Y-%m-%d") = $today;

ORDER BY two dates mysql query

I am going to give order in query like:
SELECT * FROM `sales_report` ORDER BY `cancel_date`, `pur_date`
But its not working could you please check what is wrong in this query because its not ordering dates?
pur_date type is date and cancel_date type is text so is it issue ? I can't change its type.
I echo a different think like:
if(cancel_date != ''){
$transection_date = cancel_date;
}
else {
$transection_date = pur_date;
}
Try to use STR_TO_DATE() function:
SELECT
*
FROM
`sales_report`
ORDER BY
STR_TO_DATE(`cancel_date`, '%Y-%m-%d'), `pur_date`;
As zerkms mentioned in comments: You should use format specifiers, dependent of your text values in cancel_date column.
SELECT *, CAST(`cancel_date` as DateTime) cancelDate
FROM `sales_report`
ORDER BY `cancelDate`, `purDate`
This should work

MySQL 'Between' dates not selecting the correct results using PHP (and Codeigniter)

Here is my code (using CodeIgniter):
$now = date('Y-m-d');
$then = strtotime($now . '-1 week');
$then = date('Y-m-d', $then);
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
$data['posts_today'] = $q3->num_rows();
I clearly have posted at least twenty posts this week, but it only displays '1'. Any ideas why?
Thanks!
Does this work for you:
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN DATE_SUB(NOW(), INTERVAL 1 WEEK)
AND NOW()");
Potential issues I see:
is POSTS.publish_date a DATETIME data type?
if PHP and MySQL are on different hosts, NOW from codeigniter/PHP could be a different time than what's being stored/used in MySQL.
Verify that MySQL expects dates in that format. You might be better off using MySQL's date functions to compose them.
First, offload everything you can to MySQL. The less date math you have to do the better.
Second, Look at what your actual created code looks like. Change this
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
to this
$sql = "SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
print "EXECUTING: $sql\n";
$q3 = $this->db->query( $sql );
You're assuming that the SQL you are generating is valid, and it might not be. This is very common when you're using one language to generate code in another. Always print to verify your assumptions.

Selecting from a MySQL DB based on parts of a timestamp

Is there a way to select rows from a DB where the timestamp is in a certain year? I don't have a specific timestamp, just a range (ex. all timestamps within the year 2009). Is there a way to do this? How else might I go about doing something like this? Thanks for your help!
-iMaster
Use:
WHERE timestamp_col BETWEEN STR_TO_DATE('2009-01-01', '%Y-%m-%d')
AND STR_TO_DATE('2009-12-31', '%Y-%m-%d')
Any functions performed on a column mean that an index, if one exists for that column, can not be used.
I used the STR_TO_DATE function to ensure that whatever date provided as a string could be interpreted by MySQL as a TIMESTAMP.
Reference:
STR_TO_DATE
As simple as:
SELECT * FROM table WHERE YEAR(timestamp) = '1999'
Use FROM_UNIXTIME similar to this:
SELECT
FROM_UNIXTIME(my_timestamp, '%Y') AS year
FROM
table_name
WHERE
FROM_UNIXTIME(my_timestamp, '%Y') = 2009;
Where 'my_timestamp' is the name of your timestamp column.
Alternatively you can also convert it to a DATETIME
If you convert it to datetime you can do it by using the mysql DATE_FORMAT function which allows you to take a DATETIME and format it as a date. Then group by that column.
private function _formatDate() {
if ($this->_granularity == 'month') {
return '%y/%M';
}elseif($this->_granularity == 'day') {
return '%y/%M/%d';
}
}
public function getmyquery() {
$query = "
SELECT count( * ) as visits, DATE_FORMAT( `myOriginalDateField` , '".$this->_formatDate()."' ) AS mydate
FROM `mys`
WHERE id = ".$this->_Id."
GROUP BY mydate
ORDER BY mydate ASC
";
return $query
}
An important addition to the excellent suggestions already given here: if you plan on executing this query as a part of rendering your pages (as opposed to running this as a one-off report), you should really consider performance. Indexes won't help you much if you're post-processing the column value with a function before comparing it to something.
In that case, I would consider creating a separate database column that contains JUST the year, or just the month, etc.

Categories