Can't run Select WPDB to get values between 2 date ranges - php

I am trying to get rows from a custom table I had created in my wp database.
I am trying to get all records that their date_created time value is in a date range.
This is part of the function I am building
global $wpdb;
$start_date = '2021-07-04';
$end_date = '2021-10-04';
$table_name = 'statistics_revenues';
$query = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}$table_name WHERE DATE(date_created) BETWEEN ($start_date AND $end_date)", ARRAY_A);
$query_results = $wpdb->get_results($query, ARRAY_A);
when I just run a select query with no conditions, everything works, but
as soon as I add the part from "WHERE DATE(date_created)...." the query does not get the needed results.
Where did I get it wrong?

Remove parenthesis from between just write BETWEEN $start_date AND $end_date

The main reason for the bug actually was that I didn't understand the wpdb->prepare method.
It basically works as sprintf and I used it in another manner.
in any case, Thank you everybody :)

Related

how to select data from table according to date interval?

how to retrieve all data from table using date interval?
this is my code
<?php
include '../php_action/db_connect.php';
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
echo 'ORDERS BETWEEN '.$startdate.' and '.$enddate;
$sql = "SELECT * from orders WHERE order_date BETWEEN '$startdate' AND '$enddate'" ;
$result=$connect->query($sql);
while($row=$result->fetch_array())
{
echo '<br>'. $row['order_id'] ;
}
?>
it isn't working, but when i change it to where order_id = 1; (for example) it works.
i even tried where order_date = 2020/03/02; still not working.
how should i work this out?
Put a semicolon after the sql statement inside the quotes.
$sql = "SELECT * from orders WHERE order_date BETWEEN '$startdate' AND '$enddate';" ;
^^
If that doesn't solve it the problem could be a number of things. You may have your MySql set to StrictDates. Depending on your setup you may have strict dates requiring additional zeros. See the following:
https://dev.mysql.com/doc/refman/8.0/en/datetime.html
When troubleshooting these I try to insert known good data and then work on identifying on how to get that data to pass through.
Try #1 - attempt this: change to specific dates and add a semi-colon to the end inside the quote:
$sql = "SELECT * from orders WHERE order_date BETWEEN '2020-01-01 10:10:10' AND '2020-03-01 10:10:10';" ;
If that works you can delete the times to identify if MySQL is in strict mode. This should help you identify where your issues are.

I cant query a column that is Datetime using the year, month and seconds

My site was built with WordPress and I have the following case:
The table I want to query is the wp_posts and the column to be targeted is the post_date which is of the time Datetime (not Date and I cant change it because of WordPress's convenience).
How want to fire a sql query that will give me all the details about an event posted on a specific date that will come from a calendar.
I tried this:
$date = new DateTime(2019-07-03);
$date_format = $date->format("Y-m-d");
$request = $pdo->query("SELECT * FROM posts WHERE post_date = ".$date_format);
$result = $request->fetch()
If I var_dump() the $dateformat I can see the data, however, my $result shows nothing.
I then concluded that it will never show anything because in table, the dates also have times.
So, how can I get those details if I only have year, month, day, and not the hours?
Dates are considerated as string in SQL. You must use quotes :
$request = $pdo->query('SELECT * FROM posts WHERE post_date = "'.$date_format .'"');
By the way, yes if you have datetime columns, you need to query in other way, using BETWEEN or simply :
$date_format_next = $date->add(1, 'day')->format('Y-m-d');
$request = $pdo->query('SELECT * FROM posts
WHERE post_date >= "'.$date_format .'"'
AND post_date < "'.$date_format_next .'"');
After browsing through w3schools I ended up concluding that I can use the sql search.
SELECT * FROM `wp_posts` WHERE `post_date` LIKE "%2019-07-03%"
My query works now
Your column post_date is a datetime field and I found the requested query has only the date value so you can use this query as:
$request =$pdo->query("SELECT * FROM posts WHERE DATE(post_date) = '$date_format'");

Mysql Get table result between two dates

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...

SELECT * BETWEEN AND

I'm trying to select a list of events from a database with MySQL. I'm fairly new to php but usually I can figure stuff out. cant seam to get this to work though..
function get_events_within_dates($da,$dd) {
global $connection;
$query = "SELECT *
FROM events
WHERE date
BETWEEN STR_TO_DATE('$da','Y-m-d') AND STR_TO_DATE('$dd','Y-m-d')
ORDER BY date ASC";
I've used $da and $dd as date of arrival and date of departure..
I can get it to work fine when I replace the variables with exact dates, tried messing around with STR_TO_DATE() and that didn't help either. Any help appreciated.
You are missing % in the format string. Use STR_TO_DATE() as:
STR_TO_DATE('$da','%Y-%m-%d')
Full query as below:
$query = "SELECT *
FROM events
WHERE date BETWEEN STR_TO_DATE('$da','%Y-%m-%d')
AND STR_TO_DATE('$dd','%Y-%m-%d')
ORDER BY date ASC";

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.

Categories