【问题标题】:Create HTML table from sql table从 sql 表创建 HTML 表
【发布时间】:2012-08-10 05:22:31
【问题描述】:

我在 SQL 数据库中有一个表,其中包含以下字段:ID、姓名、电子邮件、大学、语言和经验。我想创建一个从 SQL 中获取数据并输出最后 10 个结果的 html 表?我该怎么做?

如果这是一个非常简单的问题,我很抱歉,我对 PHP 和 SQL 知之甚少。

这是我现在的代码,它只显示名称而不是在表格中:

    <html>
    <head>
        <title>Last 5 Results</title>
    </head>
    <body>
        <?php
            $connect = mysql_connect("localhost","root", "root");
            if (!$connect) {
                die(mysql_error());
            }
            mysql_select_db("apploymentdevs");
            $results = mysql_query("SELECT * FROM demo");
            while($row = mysql_fetch_array($results)) {

                echo $row['Name'] . "</br>";


            ?>
    </body>
</html>

【问题讨论】:

标签: php html sql html-table


【解决方案1】:

要求您将数据库中的数据编码为 JSON 的选项:http://www.jeasyui.com/documentation/datagrid.php

但这看起来更有希望:http://phpgrid.com/

【讨论】:

    【解决方案2】:

    我希望你知道如何用 HTML 制作表格,&lt;table&gt;, &lt;tr&gt; and &lt;td&gt;.

    在您的 while 循环中使用该表修复一个表,并使用 "SELECT * FROM demo LIMIT 10" 作为 SQL 查询。

    【讨论】:

      【解决方案3】:

      这里有一些内容可以帮助您创建表格并获得更多关于phpmysql 的知识。

      此外,您应该将连接逻辑和查询移到进程的开头,从而避免在加载页面时出现错误并显示比 mysql_error 更准确的错误。

      编辑:如果你的 ids 是递增的,那么你可以添加 ORDER BY 子句,
      更改:SELECT * FROM demo LIMIT 10 至:SELECT * FROM demo LIMIT 10 ORDER BY id

      <html>
          <head>
              <title>Last 10 Results</title>
          </head>
          <body>
              <table>
              <thead>
                  <tr>
                      <td>Id</td>
                      <td>Name</td>
                  </tr>
              </thead>
              <tbody>
              <?php
                  $connect = mysql_connect("localhost","root", "root");
                  if (!$connect) {
                      die(mysql_error());
                  }
                  mysql_select_db("apploymentdevs");
                  $results = mysql_query("SELECT * FROM demo LIMIT 10");
                  while($row = mysql_fetch_array($results)) {
                  ?>
                      <tr>
                          <td><?php echo $row['Id']?></td>
                          <td><?php echo $row['Name']?></td>
                      </tr>
      
                  <?php
                  }
                  ?>
                  </tbody>
                  </table>
          </body>
      </html>
      

      【讨论】:

      • 您还需要ORDER BY id DESC 才能获得最新结果
      • 假设他的 ID 在 AUTO_INCREMENT 中,那么是的,将编辑帖子,谢谢。
      • 我不是一个经常提出为什么你应该避免使用mysql_* 命令的人,但是当你使用它们来回答那些刚刚学习语言的人时,它可能会适得其反.
      • 代替 您可以使用 = ... ?>
      • 另外,您不应该简单地回显数据库中的数据,因为它可能(意外甚至恶意)包含与生成的 html 文档混淆的内容它可能包含一个 & 或一个会破坏的
      【解决方案4】:

      您可能有兴趣使用mysql_fetch_assoc() 获取数据(这样您就可以在关联数组中获取数据:keys=>value)。键中是您的列名;因此,对于每一行,您可以遍历每一列(使用array_keys())并打印其值。

      $results = mysql_query("SELECT * FROM demo");
      while($row = mysql_fetch_assoc($results)) {
          foreach (array_keys($row) as $column) {
              echo $row[$key] . "</br>";
          }
      }
      

      (之后,您可以将 array_keys($row) 缓存在一个只设置一次的变量中,因为它的值在您运行结果时不会改变。)

      【讨论】:

        【解决方案5】:

        即使已经有一段时间了,我还是要把我的 2 美分投入:使用函数(甚至更好 - 类)。从 mysql 结果创建表是一项非常常见的任务。

        <!DOCTYPE html>
        <html>
            <head><title>Create Tables from MySQL using functions</title></head>
        <body>
        <?php
        db_connect();
        // assuming you have an auto increment id as the first column
        $result = mysql_query("SELECT * FROM demo ORDER BY 1 DESC LIMIT 10");
        print createTable(array_result($result));
        ?>
        </body>
        </html>
        
        <?php 
        /**
         * Quick mysql result function
         *
         * @param $result
         * @return array
         */
        function array_result($result)
        {
            $args = array();
            while ($row = mysql_fetch_assoc($result)) {
                $args[] = $row;
            }
            return $args;
        }
        
        
        
        /**
         * Connect to db
         * 
         * @param string $db_host
         * @param string $db
         */
        function db_connect($db_host = "localhost", $db = "apploymentdevs")
        {
            $connect = mysql_connect($db_host,"root", "root");
            if (!$connect) {
                die(mysql_error());
            }
            mysql_select_db($db);
        }
        
        /**
         * Create a table from a result set
         *
         * @param array $results
         * @return string
         */
        function createTable(array $results = array())
        {
            if (empty($results)) {
                return '<table><tr><td>Empty Result Set</td></tr></table>';
            }
        
            // dynamically create the header information from the keys
            // of the result array from mysql
            $table = '<table>';
            $keys = array_keys(reset($results));
            $table.='<thead><tr>';
            foreach ($keys as $key) {
                $table.='<th>'.$key.'</th>';
            }
            $table.='</tr></thead>';
        
            // populate the main table body
            $table.='<tbody>';
            foreach ($results as $result) {
                $table.='<tr>';
                foreach ($result as $val) {
                    $table.='<td>'.$val.'</td>';
                }
                $table.='</tr>';
            }
            $table.='</tbody></table>';
            return $table;
        }
        

        【讨论】:

          【解决方案6】:

          我非常恼火地一遍又一遍地将相同的代码粘贴在一起以从 SQL 查询构建 HTML 表。

          所以,我们在这里使用一个函数,该函数接收mysqli 结果并将它们一起粘贴到一个简单的 HTML 表中,该表具有根据数据库中的列名:

          function sql_to_html_table($sqlresult, $delim="\n") {
            // starting table
            $htmltable =  "<table>" . $delim ;   
            $counter   = 0 ;
            // putting in lines
            while( $row = $sqlresult->fetch_assoc()  ){
              if ( $counter===0 ) {
                // table header
                $htmltable .=   "<tr>"  . $delim;
                foreach ($row as $key => $value ) {
                    $htmltable .=   "<th>" . $key . "</th>"  . $delim ;
                }
                $htmltable .=   "</tr>"  . $delim ; 
                $counter = 22;
              } 
                // table body
                $htmltable .=   "<tr>"  . $delim ;
                foreach ($row as $key => $value ) {
                    $htmltable .=   "<td>" . $value . "</td>"  . $delim ;
                }
                $htmltable .=   "</tr>"   . $delim ;
            }
            // closing table
            $htmltable .=   "</table>"   . $delim ; 
            // return
            return( $htmltable ) ; 
          }
          

          示例用法:

          $DB = new mysqli("host", "username", "password", "database");
          $sqlresult = $DB->query( "SELECT * FROM testtable LIMIT 1 ;" ) ; 
          
          echo sql_to_html_table( $sqlresult, $delim="\n" ) ; 
          

          【讨论】:

          • 我很困惑你把它放在你的 html 文件中的什么地方。顶部在 php 部分,底部也在 php 中吗?
          • 是的,当然,正如您所说。这只是您仍然必须放在&lt;?php ... ?&gt; 之间的 php 代码。为了获得最佳实践,第一个代码块将进入一个单独的文件并通过include 'file/path/my_fiel.php' 提供。
          • 看起来棒极了! +1。但我不明白$counter = 22;
          • 嗯,阅读 6 年的代码......不过,这是个好问题,我认为这是可以改进的部分:$counter 使第一行结果的代码表现不同($counter===0 ) 与所有其他行相比,使用 &lt;th&gt; 而不是 &lt;td&gt; 元素。可以将此变量命名为 $is_first_line 并将其设为布尔值以使其更具可读性。
          【解决方案7】:

          在查询结果上调用 table( $result ); 将生成一个基于 html 的表,而不管您提供给它的 sql 数组的大小。我希望这会有所帮助:)

          <?php
          
          function table( $result ) {
              $result->fetch_array( MYSQLI_ASSOC );
              echo '<table>';
              tableHead( $result );
              tableBody( $result );
              echo '</table>';
          }
          
          function tableHead( $result ) {
              echo '<thead>';
              foreach ( $result as $x ) {
              echo '<tr>';
              foreach ( $x as $k => $y ) {
                  echo '<th>' . ucfirst( $k ) . '</th>';
              }
              echo '</tr>';
              break;
              }
              echo '</thead>';
          }
          
          function tableBody( $result ) {
              echo '<tbody>';
              foreach ( $result as $x ) {
              echo '<tr>';
              foreach ( $x as $y ) {
                  echo '<td>' . $y . '</td>';
              }
              echo '</tr>';
              }
              echo '</tbody>';
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-06-15
            • 2023-03-23
            • 2018-08-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多