首页 > 解决方案 > 使用数据库中的值突出显示 HTML 表格单元格

问题描述

我想通过将它与给定日期的数据库表进行比较来突出显示 HTML 表中的时间值。

我正在尝试这段代码

<?php

     function getdata($start_date, $timevalue)
     {
        $host = "localhost";
        $user = "root";
        $password = "";
        $database = "test";

        $con = mysqli_connect($host,$user,$password,$database);
        $result = $con->query( "SELECT * FROM booking" );
        while($row = $result->fetch_assoc()) {
                if(($row['datefrom']==$start_date) && ($row['timefrom']<=$timevalue && $row['timeto']>=$timevalue)){
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
     }

    $start_date = "2019-07-11";
    $end_date = "2019-07-15";
    $tmfrm = strtotime("07:00:00");
    $tmto = strtotime("15:00:00");

    echo "<table border='1'>";
     while (strtotime($start_date) <= strtotime($end_date))
     {
        echo "<tr><td>".$start_date."</td>";
        for($t=$tmfrm; $t<=$tmto; $t+=1800)
        {
            $timevalue=date("H:i:s", $t);
            if (getdata($start_date, $timevalue)==1){
            echo "<td bgcolor='red'>". $timevalue  . "<br></td>";
            }else
            {
                echo "<td bgcolor='green'>".  $timevalue  . "<br></td>";
            }
        }
        echo "</tr>";
        $start_date = date ("Y-m-d", strtotime("+1 days", strtotime($start_date)));
      }
      echo "</table>"; 
?>

下面是带有样本数据的表格

预订
------------------------------------------
房间号 | 日期从 | 时间从| 时间到 |
------------------------------------------
房间1 | 2019-07-11 | 07:00:00 | 10:00:00 |
------------------------------------------
房间1 | 2019-07-11 | 11:00:00 | 12:00:00 |
------------------------------------------
房间1 | 2019-07-12 | 11:00:00 | 12:00:00 |
------------------------------------------
房间1 | 2019-07-13 | 11:00:00 | 12:00:00 |
------------------------------------------
房间1 | 2019-07-14 | 07:00:00 | 10:00:00 |
------------------------------------------
房间1 | 2019-07-15 | 10:30:00 | 13:30:00 |
------------------------------------------
房间1 | 2019-07-11 | 13:30:00 | 14:00:00 |
------------------------------------------

在我得到的输出中,它只突出显示 2019 年 7 月 11 日从 07:00 到 10:00 的时间,而它应该突出显示其他日期的时间,包括其他时间(14:00 到 15:00) 2019-07-11。(见图)。逻辑有什么问题?

在此处查看输出

标签: php

解决方案


我已经想出了解决方案。我所要做的就是修改 getdata() 函数以在没有循环的情况下工作。我用 select 语句指定了条件,而不是用 if 语句在循环中检查它。以下是修改后的代码:

function getdata($start_date, $timevalue)
     {
        $host = "localhost";
        $user = "root";
        $password = "";
        $database = "test";

        $con = mysqli_connect($host,$user,$password,$database);
        $result = mysqli_query($con, "SELECT * FROM booking WHERE datefrom='$start_date' AND (timefrom<='$timevalue' AND timeto>='$timevalue')" );

         if(mysqli_num_rows( $result)>0){
                    return 1;
        }
         else{
             return 0;
         }
     }

现在它工作正常。以下是我得到的输出。这是我需要的。 输出


推荐阅读