循环访问数据库并将其显示在新文件中

时间:2016-02-05 16:45:23

标签: 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"];
}

我的问题是,我可以创建一个包含循环内容的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);
}

IMAGE:

generated html table

2 个答案:

答案 0 :(得分:1)

只需循环需要循环的项目(在本例中为表格行):

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

答案 1 :(得分:0)

看起来你正在为每一行重新创建表格。只需要操纵体内的TR部分。