php - 用php的mysql记录动态生成html表

标签 php mysql html

(对我来说)这很复杂的原因是表的每一列都是从单独的 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>";

这是错误的,不仅因为它生成了格式错误的表格,还因为它将列转换为行...

如有任何帮助,我们将不胜感激

最佳答案

我最讨厌的问题的解决方案:

$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>";

关于php - 用php的mysql记录动态生成html表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18196374/

相关文章:

javascript - 使用当前日期生成随机 ID

mysql - Ruby on Rails : Best way to save search queries in a database

php - 使用 PHP 和 MYSQL 进行过滤

javascript - 如何使用 jsp 和 javascript 从完整路径(系统位置)播放视频?

javascript - 使用 js 的高级表格过滤器

php - javascript 函数调用不起作用

php - Mysql查询变量语法

php - MySQL PHP - 正斜杠后缺少字符

php - Laravel Dompdf 如何一起下载两个pdf文件

php - 如何在没有重定向的情况下使用 Paypal 进行 future 付款?