我正在制作一个预订系统,因此我需要能够在让用户预订之前检查时隙是否可用(我的功能还会在检查前后添加1个时间段来覆盖旅行时间等)。 / p>
function timeSlotAvailable($date, $time){
$timeslots = array($time - 1, $time, $time + 1);
$slots = join(',',$timeslots);
$STH = $this->database->prepare("SELECT COUNT(*) FROM bookings WHERE bookings.date = :bdate AND bookings.slot IN (:ids)");
$STH->execute(array(":bdate"=>$date, ":ids"=>$slots));
$data = $STH->fetchColumn();
return "checking date:".$date." for slots ".$slots." the count is ".$data;
}
输出
checking date:02/15/2014 for slots 3,4,5 the count is 0
现在在bookings
时间槽4上有一个用于该日期的插槽。然后我在phpmyadmin中尝试此查询
SELECT COUNT(*) FROM bookings WHERE bookings.date = "02/15/2014" AND bookings.slot IN (3,4,5)
本质上是相同的查询(提交相同的变量),但返回的1
响应正确。这让我觉得我的代码有些问题是我看不到的。
答案 0 :(得分:0)
问题在于:
function timeSlotAvailable($date, $time){
$timeslots = array($time - 1, $time, $time + 1);
$slots = join(',',$timeslots); //bad
$STH = $this->database->prepare("SELECT COUNT(*) FROM bookings WHERE bookings.date = :bdate AND bookings.slot IN (:ids)");
$STH->execute(array(":bdate"=>$date, ":ids"=>$slots)); //here is the problem
$data = $STH->fetchColumn();
return "checking date:".$date." for slots ".$slots." the count is ".$data;
}
这样您的查询就像:
SELECT COUNT(*)
FROM bookings WHERE bookings.date ='02/15/2014'
AND bookings.slot IN (3) //Just took one, oops
当然答案是零。
以这种方式更改您的代码:
function timeSlotAvailable($date, $time){
$timeslots = array($time - 1, $time, $time + 1);
$STH = $this->database->prepare("SELECT COUNT(*) FROM bookings WHERE bookings.date = :bdate AND bookings.slot IN (:ids)");
$STH->execute(array(":bdate"=>$date, ":ids"=>$timeslots));
$data = $STH->fetchColumn();
return "checking date:".$date." for slots ".$slots." the count is ".$data;
}
或者这样:
function timeSlotAvailable($date, $time){
$timeslots = array($time - 1, $time, $time + 1);
$slots = join(',',$timeslots);
$STH = $this->database->prepare("SELECT COUNT(*) FROM bookings WHERE bookings.date = :bdate AND bookings.slot IN (".$slots.")");
$STH->execute(array(":bdate"=>$date));
$data = $STH->fetchColumn();
return "checking date:".$date." for slots ".$slots." the count is ".$data;
}