pdo查询2个日期之间的选择记录

时间:2012-04-29 08:50:53

标签: php mysql pdo

此查询:payment_date BETWEEN "old date" AND "new date"只有在新日期之前写旧日期才会成功运行。如果查询payment_date BETWEEN "new date" AND "old date",如何使其工作?因为有时用户首先输入新日期,所以只输入旧日期。示例代码:

$sql = "SELECT customer_name, phone_number, address FROM sale 
        WHERE seller_id=? && $search_by  LIKE ? && payment_date BETWEEN ? AND ?";
$q = $conn->prepare($sql);
$result = $q->execute(array($userid, "%".$search_value."%", $oldPaymentDate, $newPaymentDate));

1 个答案:

答案 0 :(得分:2)

始终验证用户输入,同时只是比较日期,然后进行交换,它们的顺序不正确,如下所示:

$date1 = new DateTime($newPaymentDate);
$date2 = new DateTime($oldPaymentDate);

if($date1 < $date2) list($newPaymentDate,$oldPaymentDate)=array($oldPaymentDate,$newPaymentDate);