PDO PHP - 查找两个日期之间的所有行 - 显示空白(PDO PHP - Find all

2019-09-29 12:20发布

使用PHP的PDO我想获得在具有当前一周内的起始日期我的数据库表中的所有行。 为了计算这个星期我用下面的第一个和最后一个日期:

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

然后我的PDO查询中我有:

$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;

问题是我没有得到任何行输出显示出来,尽管具有这周之内的开始日期的多个预订

Answer 1:

DATE_FORMAT()返回一个字符串,而不是一个日期。 3个传递字符串参数来BETWEEN ...谁知道什么会回来。

要取消屁股向后你的代码,使用方法:

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

格式化你的日期在MySQL中期望的方式,并:

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

在查询中。

或者,如果你希望一个面向对象的方法,这样做:

$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);

然后在您的查询做:

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

那么对于一切,你可以重复你怎么想的格式:

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


文章来源: PDO PHP - Find all rows between 2 dates - shows blank