PDO PHP - 查找2个日期之间的所有行 - 显示为空白

时间:2013-02-26 21:02:04

标签: php mysql pdo between

使用PDO php我试图获取数据库表中当前周内具有start_date的所有行。要计算本周的第一个和最后一个日期,我使用以下内容:

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

问题是我没有在输出中显示任何行,尽管有多个预订在本周内有开始日期

1 个答案:

答案 0 :(得分:2)

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