我写了一个代码来显示医生的可用性根据日期,但当mysql上的字段是空的,我有这个数组错误


I wrote a code to show the availability of doctors according to the date, but when the field on mysql is empty i have this array error

这就是我要讲的代码

session_start();
include ('configg.php');
$query = "SELECT Date, Time FROM gp_appointment WHERE Name = '$_POST[doctor]' AND Date = '$_POST[date]'";
$result = mysql_query($query);

  $data = array();
  while($row = mysql_fetch_assoc($result))
  {
     $data[] = $row;
  }
 $colNames = array_keys(reset($data))

 ?>
 <table border="1">
 <tr>
    <?php
       //print the header
       foreach((array)$colNames as $colName)
       {
          echo "<th>$colName</th>";
       }
    ?>
 </tr>
    <?php
       //print the rows
       foreach((array)$data as $row)
       {
          echo "<tr>";
          foreach($colNames as $colName)
          {
             echo "<td>".$row[$colName]."</td>";
          }
          echo "</tr>";
       }

    ?>
 </table>
 <a href="homepage.php">Go back to the homepage</a><br>
 <a href="docname.php">Check another doctor</a><br>

当我选择一个存在于数据库中的日期时,一切正常,但如果我选择一个不存在的日期,我收到这个错误:

警告:array_keys()期望参数1为array, boolean给定目录:H:'Project' examplite 'htdocs'example'phptutorial'doctorav.php第15行

有人知道该怎么做吗?

检查是否获得了数据,而不是只执行任何操作。或者直接打印消息No Records Found

if((!empty($data)){
     // Perform all operation
}
else{
   echo "No records Found";
}

注意:请不要在新代码中使用mysql_*函数。它们不再被维护,并被正式弃用。见红框?学习预处理语句,并使用PDO或MySQLi——本文将帮助您决定使用哪一种。如果你选择PDO,这里有一个很好的教程。

在处理结果之前,需要先检查结果是否为空。

if($data){
    $colNames = array_keys(reset($data));
}

您可能还需要在输出中检查这一点,否则for-each也会失败:)

相关文章: