【问题标题】:Dynamically generate html table with php of mysql records用mysql记录的php动态生成html表
【发布时间】:2013-08-12 20:44:23
【问题描述】:

这很复杂的原因(对我来说)是表的每一列都是从一个单独的 MySQL 表加载的,每个 MySQL 表都有不同数量的记录。最初我以为我可以开始从左上角到右下角逐列、逐个单元格地生成 html 表,但这不起作用,因为每个 MySQL 表都有不同长度的记录,这会生成格式错误的 html 表。你有什么建议吗?

到目前为止我的想法:

  • 获取MySQL中所有表的列表,这些表决定了表的个数 列
  • 从记录最多的表中获取计数
  • 使用参数创建表(表的数量为列,最大的行数为
  • 用相应的记录更新每个单元格,但不太确定如何

根据要求,一些代码:

$tables = mysql_query("show tables");

$output = "<table border=1><thead><tr>";

while($table = mysql_fetch_array($tables)) {

$output .= "<td>";
$output .= $table[0];
$output .= "</td>";
$tableNames[] = $table[0];

}

$output .= "</tr></thead>";
$output .= "<tbody>";

//Get a count of the table with the most records
for($i=0; $i<count($tableNames); $i++ ){

    $currentTable = $tableNames[$i];

    $tableContent = mysql_query("select * from $currentTable") or die("Error: ".mysql_error());

    //Generating all content for a column
    $output .= "<tr>";

    while($content = mysql_fetch_array($tableContent)){

        //generating a cell in the column
        $output .= "<td>";
        $output .= "<strong>".$content['subtheme'].": </strong>";
        $output .= $content['content'];
        $output .= "</td>";

    }

    $output .= "</tr>";

}

$output .= "</tbody>";
$output .= "</table>";

这是错误的,不仅因为它生成了一个格式错误的表,还因为它把列转置为行......

任何帮助将不胜感激

【问题讨论】:

  • 我们需要代码来帮助您
  • 结果不能加入 MySQL 查询吗?
  • 你在完成第三个要点之前有点落后
  • 请更清楚您到底想做什么。您如何知道一个表中的哪一行与其他表中的哪一行相匹配?
  • 听起来您需要决定如何组织表格中的数据 - 然后您就可以着手实施了。

标签: php mysql html


【解决方案1】:

我非常讨厌的问题的解决方案:

$mymax = 0;
for($i=0; $i<count($tableNames); $i++){
    $currentTable = $tableNames[$i];
    $tableCounts = "select * from $currentTable";

    if($stmt = $mysqli->prepare($tableCounts)){

        mysqli_stmt_execute($stmt);
        mysqli_stmt_store_result($stmt);
        $count = mysqli_stmt_num_rows($stmt);
        mysqli_stmt_close($stmt);

    }   
    ($mymax >= $count ? "" : $mymax = $count);

    $colWidth = 100 / count($tableNames);   
}

// DIV GRID
// via DIV GENERATION
$output .= "<div class='grid'>";
for ($i=0; $i<count($tableNames); $i++){
    $output .= "<div id='col$i' class='col' style=\"width:$colWidth%\">";
    $output .= "<h3>".$tableNames[$i]."</h3>";

    $tableqry = "select * from $tableNames[$i]";

    if ($result = mysqli_query($mysqli, $tableqry)) {

        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

            $output .= "<div class='item'>".$row["content"]."</div>";

        }

        mysqli_free_result($result);

    }

    $output .= "</div>";

}

$output .="</div>";

$output .="<div class='clear'></div>";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2015-02-20
    • 2010-10-11
    相关资源
    最近更新 更多