M.BABER Zaman
M.BABER Zaman

Reputation: 107

How to get data from Mysql between two specific dates

I want to get data from Mysql With Php between 2 dates. I am unable to get this.. Here are my Codes. These Lines are for Date Interval...

date_default_timezone_set("EST");
$today = date('d-m-Y');
$date_to = $today;
$date_to = strtotime("-7 days", strtotime($date_to)); //-7 days for last week. -30 for last week
$date_to = date("d-m-Y", $date_to);

Now Here are the Queries Which i am running.. I have two conditions. 1 The Data should be between $today and $date_to dates. And assigned should be equal to 1. Assigned is a column in Database table 'requests'.

$get_req = "SELECT * FROM `requests` WHERE `req_date` between '$today' AND '$date_to' AND `assigned`='1'";
$result = mysqli_query($dbc, $get_req);
while ($res = mysqli_fetch_assoc($result)){
    $driver_id = $res['assigned_driver_id'];
    $req_id = $res['req_id'];
    $req_title = $res['request_title'];
    $req_price = $res['price'];
    $req_time = $res['request_time'];
    $req_date = $res['req_date'];
    $driver = $res['driver_name'];
}

Here i am unable to get my required result. Problem is Only in Date query. I mean in Between Date A to Date B. req_date` between '$today' AND '$date_to' It works Perfect.

Please advise me what i should do to fix it. I want to get the Records of Past 7 Days only.

Upvotes: 0

Views: 651

Answers (2)

Pratik Soni
Pratik Soni

Reputation: 2588

Here is your solution. You need to change the query like this.

STR_TO_DATE(yourdatefield, '%d-%m-%Y') > CURDATE() - INTERVAL 7 DAYS

Upvotes: 0

Mindastic
Mindastic

Reputation: 4141

I don't know what's your DB structure, but you could change your code and do something like:

Your PHP Code

date_default_timezone_set("EST");
$today = time();
$date_to = strtotime("-7 days"); //-7 days for last week. -30 for last week

And your query:

$get_req = "SELECT * FROM `requests` WHERE UNIX_TIMESTAMP(`req_date`) between '$today' AND '$date_to' AND `assigned`='1'";

Upvotes: 2

Related Questions