1

使用 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;

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

4

1 回答 1

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
于 2013-02-26T21:09:50.880 回答