PDO PHP - Find all rows between 2 dates - shows blank

会有一股神秘感。 提交于 2019-12-11 06:33:35

问题


Using PDO php i am trying to get all the rows in my database tables that have a start_date within the current week. To calculate the first and last date of this week i use the following:

$week_start = date('d-m-Y',time()+( 1 - date('w'))*24*3600);  
$week_end =  date('d-m-Y',time()+( 7 - date('w'))*24*3600); 

Then within my pdo query i have:

$query = " 
    SELECT 
        *
    FROM 
        bookings as bb 
    INNER JOIN 
        reservation as br ON bb.booking_id=br.bookings_id
    INNER JOIN 
        cars as bc ON br.car_id=bc.car_id 
    WHERE 
        payment_success=1 AND 
        is_block=false AND 
        is_deleted=0 AND
        DATE_FORMAT(start_date, '%d-%m-%Y') 
        BETWEEN '".$week_start."' AND '".$week_end."'
"; 

try { 
    $stmt = DB::get()->prepare($query); 
    $stmt->execute(); 

    $rows = $stmt->fetchAll();
}  
catch(PDOException $ex) { 
    die("Failed to run query: " . $ex->getMessage()); 
} 

foreach($rows as $row):
    $row['booking_id'] etc...
endforeach;

The problem is i am not getting any rows to show up in the output despite having multiple bookings which have a start date within this week


回答1:


DATE_FORMAT() returns a string, not a date. Passing 3 string arguments to BETWEEN... who knows what that is going to return.

To un-ass-backwards your code, use:

$week_start = date('Y-m-d',time()+( 1 - date('w'))*24*3600);  
$week_end =  date('Y-m-d',time()+( 7 - date('w'))*24*3600); 

to format your dates in the way mySQL expects, and:

WHERE 
  start_date BETWEEN '".$week_start."' AND '".$week_end."'

in the query.

Or if you would prefer an object-oriented approach, do something like this:

$week_start = new DateTime; 
$week_end = new DateTime;
$week_start->setTimestamp(time()+( 1 - date('w'))*24*3600)); 
$week_end->setTimestamp(time()+( 7 - date('w'))*24*3600);

Then in your query do:

WHERE 
  start_date 
      BETWEEN '".$week_start->format('Y-m-d')."'
      AND '".$week_end->format('Y-m-d')."'

Then for everything else, you can echo the format how you wish:

echo $date->format('d-m-Y'); // etc


来源:https://stackoverflow.com/questions/15099187/pdo-php-find-all-rows-between-2-dates-shows-blank

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!