从mysql以表格格式显示

时间:2012-04-16 13:57:09

标签: php mysql html-table automation

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

enter image description here

我喜欢在5 td中放置类别,然后如何在[{1}}

中将tr修改为table

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

以下是我需要解决方案的图像

enter image description here

代码

<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

回答的结果输出图像

enter image description here

1 个答案:

答案 0 :(得分:3)

试试这个( 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>\n<tr>\n";

  // 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>\n";
    // 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>\n<tr>\n";
    }
  }

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

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

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