从mysql以表格格式显示

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从mysql以表格格式显示相关的知识,希望对你有一定的参考价值。

我有product_category的表,它有超过20个类别,我想以表格格式显示它们,如下图

我喜欢在5个td中放置类别然后如何在tr中将其固定到table

下面是我尝试过的代码,但它没有提供所需的输出

下面是我需要的可能解决方案的图像

下面的代码

<table>
<?php

$fquery5 = mysql_query("select Cat_ID, Cat_Name from product_category where Active_Flag=1");    

    $count1 = mysql_num_rows($fquery5);

    $hor_length = 5;
    $ver_length = $count1 / $hor_length;

    $data1 = mysql_fetch_row($fquery5);

    for ($i = 0; $i <= $ver_length; $i++) {
        echo "<tr>";
            for ($j = $i + $hor_length; $j <= $count1; $j++) {
                    echo "<td>";
                        echo "Id : " . $data1[0] . " = " . $data1[1];
                    echo "</td>";
            }
        echo "</tr>";
    } 

?>
</table>

添加了由@DaveRandom回答的结果输出图像

答案

试试这个(FIXED):

<?php

  // Number of columns
  $hor_length = 5;

  // Do the query, get the number of rows in the result
  $fquery5 = mysql_query("
    SELECT Cat_ID, Cat_Name
    FROM product_category
    WHERE Active_Flag = 1
  ");    
  $numrows = mysql_num_rows($fquery5);

  // Start of table
  echo "<table>
<tr>
";

  // Loop the results with a counter
  for ($i = 1; $row = mysql_fetch_row($fquery5); $i++) {
    // Every iteration echos a cell
    echo "<td>Id : " . $row[0] . " = " . $row[1] . "</td>
";
    // If we're at the end of a row, echo a row break, unless it is the last result
    if (!($i % $hor_length) && $i < $numrows) {
      echo "</tr>
<tr>
";
    }
  }

  // Right-pad the end row with empty cells
  for ($i--; $i % $hor_length; $i++) {
    echo "<td></td>
";
  }

  // Echo the end of the table
  echo "</tr>
</table>";

查看working example(手动创建数据数组,因为我无法从键盘查询数据库)

以上是关于从mysql以表格格式显示的主要内容,如果未能解决你的问题,请参考以下文章

使用字符串(不是HTML)以表格格式显示对象数组。

使用 PHP 从 MySQL 数据库中获取数据,以表格形式显示以进行编辑

如何在android中以表格格式显示数据?

如何在 React js 中以表格格式显示 API 响应?

从mysql的片段中加载ListView

安卓开发前后台通信,从数据库中取数据并在前台以表格形式显示,以json格式传输