从SQL数据库将标头和数据导入HTML表

时间:2017-12-10 22:08:33

标签: php html sql

简而言之,我在过去一周左右尝试实现的是从SQL表中检索数据并将其插入HTML表的特定列。已经完成了,我知道,我浏览过一堆论坛,手册和视频,但没有找到任何可以解决我问题的内容。

我想要做的是创建一个如下表所示的表:

html table

简要说明是:用户在预约时输入日期。除了选择日期之前3天和之后3天(在本例中用户选择星期三,12月6日至17日),SQL表还检索用户选择的日期。标题表示日期,下面的时间段表示当天可预订的可用时间段(此时间长达17:00)。如果时隙不可用,则不应在此处显示,而应将其替换为下一个可用时隙。

这是(无效的)php代码:



<?php
require 'connection.php';
$conn = Connect();

$sql1 = 'SELECT DATE_b FROM daysofweek';
$query1 = mysqli_query($conn,$sql1);

$sql2 = 'SELECT TIME FROM daysofweek';
$query2 = mysqli_query($conn, $sql2);
?>

<table class="bookAppointment">
  <thead>
      <?php
      while ($row = mysqli_fetch_array($query1)) {
        echo '<tr>
                <th>'.date('D, M d-y',strtotime($row['DATE_b']) ).'</th>
              </tr>';
        }
      ?>
  </thead>
      <?php
      while ($row = mysqli_fetch_array($query2)){
        echo '<tr>
                <td>'.$row['TIME'].'</td>
              </tr>';
        }
      ?>
    </table>
&#13;
&#13;
&#13;

结果是每个标题垂直打印(一个在另一个下面),我希望标题水平打印。

其他资源主要涵盖的是表标题必须修复 - 而不是从SQL数据库中修复。但是,在这种情况下,除了属于每个日期的时隙之外,我还需要从数据库中提取这些标头。

非常感谢这方面的任何帮助。即使它只是指向我的方向,我可以阅读更多关于如何使PHP代码执行此操作或如果这是数据库设计的问题。

提前致谢!

2 个答案:

答案 0 :(得分:0)

问题很简单,就是在$_POST循环中,除了列之外,您还要循环遍历行;每次运行循环时,都会创建一个新行。

您目前有:

while

哪个输出:

while ($row = mysqli_fetch_array($query1)) {
    echo '<tr>
            <th>'.date('D, M d-y',strtotime($row['DATE_b']) ).'</th>
          </tr>';
}

为了让您的标题单元格全部在同一行,您只需将<tr> <th>One</th> </tr> <tr> <th>Two</th> </tr> echo <tr>置于while循环之外:

echo '<tr>';
while ($row = mysqli_fetch_array($query1)) {
    echo '<th>'.date('D, M d-y',strtotime($row['DATE_b']) ).'</th>';
}
echo '</tr>';

这将导致:

<tr>
  <th>One</th>
  <th>Two</th>
</tr>

希望这有帮助! :)

答案 1 :(得分:0)

虽然不是您原始代码的直接答案,但以下内容应该让您清楚了解如何实现既定目标。

在此代码中,数组$rsdates$rstimes将通过查询数据库并迭代各自的记录集来获取 - 事实上,根本不需要从数据库中抽取时间 - 您可以使用range,如图所示。

$html=array();
$rsdates=array('Mon','Tues','Wed','Thurs','Fri');
$rstimes=range( 09.00, 17.00, 0.5 );


$html[]="<table border=1 width='100%' cellpadding='1rem' cellspacing='1rem'>";
$html[]="<tr>";
foreach( $rsdates as $date ){
    $html[]="<th>$date</th>";
}
$html[]="</tr>";

foreach( $rstimes as $i => $time ){
    $html[]="<tr>";
    foreach( $rsdates as $index => $header ){
        if( is_float( $time ) ){
            list( $hour, $min )=explode( '.', strval( $time ) );
            if( $min==5 ) $min=30;
        }
        $html[]="<td id='day_{$index}_time_{$i}'>".date('H.i',mktime( $hour, $min, 0, 1, 1, date('Y') ) )."</td>";
    }
    $html[]="</tr>";
}

$html[]="</table>";


echo implode( PHP_EOL, $html );

通过为表格单元格分配ID,您还应该能够识别单击的日期/时间(假设有一些javascript交互)

这将生成以下HTML表 enter image description here

相关问题