php - 查询在 phpmyadmin 中工作但不在脚本中

标签 php mysql

我正在制作一个预订系统,因此我需要能够在让用户预订之前检查是否有可用的时间段(我的功能还在前后添加了 1 个时间段以检查是否包含旅行时间等)

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。这让我觉得我的代码有一些我看不到的错误。

最佳答案

问题是:

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;

}

关于php - 查询在 phpmyadmin 中工作但不在脚本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22096802/

相关文章:

php - 当数据库出现故障或我想永久断开数据库连接时,如何将用户重定向到 404 页面?

php - php 的 file_get_contents 是否忽略文件锁定?

php - 想要根据使用 CjuiDatePicker 给出的开始日期计算结束日期

MySQL选择一栏

php - Codeigniter 分页和搜索问题

java - Hibernate:Hibernate 为 Fetch 模式 Eager 进行的多个选择查询

c# - 如何比较 DateTime.Now 与 MySQL DATETIME 格式?

php - Unicode/UTF Seo Friendly Url (slug) 使用 Php Mysql

php - EventSource 的响应具有 MIME 类型 ("application/x-httpd-php") 而不是 "text/event-stream"。中止连接

php - 如何解决 €25.99 vs 25.99€ preg_match 问题?