Php 循环浏览数据库并在新文件中显示它们

Php 循环浏览数据库并在新文件中显示它们,php,mysql,pdo,Php,Mysql,Pdo,我有一个脚本,它在数据库中循环并显示它的所有内容 $select_report = $conn->prepare("SELECT test_db FROM report"); $select_report->execute(); while ($result_report = $select_report->fetch(PDO::FETCH_ASSOC)){ echo $result_report["test_db"]; } 我的问题是,我可以创建一个包含循环内容的HT

我有一个脚本,它在数据库中循环并显示它的所有内容

$select_report = $conn->prepare("SELECT test_db FROM report");
$select_report->execute();
while ($result_report = $select_report->fetch(PDO::FETCH_ASSOC)){
   echo $result_report["test_db"];
}
我的问题是,我可以创建一个包含循环内容的HTML文件吗? 我尝试使用此脚本,但它只显示生成的HTML文件中的最后一行

$select_report = $conn->prepare("SELECT test_db FROM report");
$select_report->execute();
while ($result_report = $select_report->fetch(PDO::FETCH_ASSOC)){
   $html_report = "
                <!DOCTYPE html>
                <html>
                <head>
                <title>Sales report</head>
                </head>
                <body>
                  <div class='container'>
                    <table>
                        <thead>
                           <tr>
                             <th>test</th>
                           </tr>
                        </thead>
                        <tbody>
                           <tr>
                             <th>". $result_report["test_db"] ."</th>
                           </tr>
                        </tbody>
                    </table>
                  </div>
               </body>
               </html>
                  ";
$myfile = fopen("report - ".date("m, d, s").".html", "w") or die("Unable to open file!");
fwrite($myfile, $html_report);
fclose($myfile);
}
图片:


看起来您正在为每一行重新创建表。只需操纵身体中的TR部位

在这种情况下,只需循环需要循环的表行中的项即可:

$select_report = $conn->prepare("SELECT test_db FROM report");
$select_report->execute();
$html_report = "
                <!DOCTYPE html>
                <html>
                <head>
                <title>Sales report</head>
                </head>
                <body>
                  <div class='container'>
                    <table>
                        <thead>";

while ($result_report = $select_report->fetch(PDO::FETCH_ASSOC)){
   // concatenate rows
   $html_report .= "<tr>
                             <th>test</th>
                           </tr>
                        </thead>
                        <tbody>
                           <tr>
                             <th>". $result_report["test_db"] ."</th>
                           </tr>
                        </tbody>";
}
// outside of loop    
$html_report .= "</table>
                  </div>
               </body>
               </html>
                  ";

$myfile = fopen("report - ".date("m, d, s").".html", "w") or die("Unable to open file!");

fwrite($myfile, $html_report);
fclose($myfile);

我只是写了一个例子。它不是真正的HTML结构。即使我通过模仿剧本来尝试,它还是奏效了。所有内容都是循环显示的,但当我生成HTML文件时,它只显示最后一行