简体   繁体   English

在PHP的HTML表中显示来自SQL查询的数据

[英]Display data from SQL query in an HTML table in PHP

I retrieved a list of data from an SQL database and now I would like to display it in a neat table rather than in a list. 我从SQL数据库检索了一个数据列表,现在我希望将其显示在一个整洁的表中而不是一个列表中。 I managed to find a way to do this (probably not very elegant, though), but the column headers seem to be offset and I have not idea how to fix this. 我设法找到了一种方法来执行此操作(虽然可能不是很优雅),但是列标题似乎已偏移并且我不知道如何解决此问题。

在此处输入图片说明

I'm completely new to PHP, so any hints on how to solve this will be much appreciated! 我是PHP的新手,因此非常感谢有关如何解决此问题的任何提示!

    echo '<table>';
    echo '<tr>';
    echo '<th>';
    echo '<td>Word</td>';
    echo '<td>Frequency</td>';
    echo '</th>';
    echo '</tr>';
    $response = $db->query("SELECT * FROM frequencies WHERE freq BETWEEN 900 AND 910 ORDER BY freq");

    while ($row = $response->fetch())
    {
        echo '<tr>';
        echo '<td>'.$row['word'].'</td>';
        echo '<td>'.$row['freq'].'</td>';
        echo '</tr>';
    }
    echo '</table>';
    $response->closeCursor();   

A <th> element is a table header element and should be used instead of <td> ( table data ) element in your header row - it should never be a wrapper around <td> elements. <th>元素是表头元素,应使用它代替标题行中的<td>表数据 )元素-永远不要将其作为<td>元素的包装。

echo '<table>';
echo '<tr>';
echo '<th>Word</th>';
echo '<th>Frequency</th>';
echo '</tr>';

I prefer combining php and html 我更喜欢结合php和html

<table >
    <thead>
        <tr>
            <th >Word</th>
            <th >Frequency</th>   
        </tr>
    </thead>
        <?php
        $response = $db->query("SELECT * FROM frequencies WHERE freq 
        BETWEEN 900 AND 910 ORDER BY freq");

        ?>
    <tbody>
        <?php  
 while ( $row = $response->fetch()) { 
         ?>
           <tr>

            <td><?php echo $row['word']; ?></td>
            <td><?php echo $row['freq']; ?></td>

         </tr>
          <?php } 

            $response->closeCursor();

           ?>
    </tbody>
</table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM