douzhi3776 2014-11-08 13:31
浏览 21
已采纳

我可以缩短这个PDO吗?

I am creating a place where people can reserve tables. This is a project for school.

But the point is that I want to check in my database if the table is already reserved for the chosen date & time and if true, add a class to it so it becomes red, or something like that.

I have this code now but i don't want to do the same thing for table 2 - 18 because of the gigantic code I'll get. There must be an easier way. Anybody any ideas?

<?
    $date = $_GET['date'];
    $time = $_GET['time'];
    ?>
    <button class="table 
    <?
    $table1 = $con->prepare( "SELECT * FROM `table` WHERE `table` = 1 AND `date` = ? AND `time` = ?" );
    $table1->bindValue( 1, $date );
    $table1->bindValue( 2, $time );
    $table1->execute();
    if( $tafel1->rowCount() > 0 ) { echo "active";}
    ?>"></button>
  • 写回答

1条回答 默认 最新

  • dragon88112 2014-11-08 13:42
    关注

    Something like this would work beautifully, taking full advantage of prepared statements:

    $date = $_GET['date'];
    $time = $_GET['time'];
    $query = $con->prepare("
        SELECT `id` -- if you don't have an ID column, replace with any column really
        FROM `table`
        WHERE `table` = ?
          AND `date` = ?
          AND `time` = ?
        LIMIT 1 -- you're only interested in existence, so limit 1 is more efficient
    ");
    foreach(range(1,18) as $table) {
        $query->execute(array($table, $date, $time));
        if( $query->rowCount() > 0) $class = "table active";
        else $class = "table";
    
        echo '<button class="'.$class.'"></button>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大