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 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件