使用mPDF打印表格时如何在while循环外获取数据库的月份数据
实现方案
最简单的实现方式不需要二次查询数据库,只需要先把查询结果提前全部加载到数组中,就能在拼接PDF头部之前拿到月份数据,步骤如下:
- 执行SQL查询拿到结果集后,先将所有数据转为数组存储,避免直接遍历后结果集被清空
- 从数组第一条数据中取出月份值赋值给
$MONTH变量(请将代码中的planningMonth替换为你实际表中存储月份的字段名) - 后续拼表格时直接遍历提前存储的数组即可
- 注意:你原代码中HTML部分是用单引号包裹的,单引号字符串内的PHP变量不会自动解析,需要改成双引号包裹或者用字符串拼接的方式插入
$MONTH
修改后的核心代码示例:
$stmt->execute(); $result = $stmt->get_result(); // 新增:提前把所有结果存到数组 $rows = $result->fetch_all(MYSQLI_ASSOC); // 新增:获取月份,没有数据时的默认值可以自行调整 $MONTH = !empty($rows) ? $rows[0]['planningMonth'] : '未设置'; $mpdf = new \Mpdf\Mpdf(['tempDir' => '/tmp']); // 注意这里把单引号改成双引号,$MONTH才能被正常解析 $html = " <img src=\"../img/ue-logo.jpg\" height=\"60\" width=\"auto\" /> <img style=\"padding-left: 32%;\" src=\"../img/gr-logo.jpg\" height=\"60\" width=\"auto\" /> <img style=\"padding-left: 32%;\" src=\"../img/is-logo.jpg\" height=\"60\" width=\"auto\" /> <br /><br /> <p style=\"text-align: right; padding-right: 5%;\"><strong>ANEXA 4</strong></p> <br /> <p style=\"text-align: left;\"><strong> id 130788<br /> \"Proiect “Stagii de practică pentru elevii din învățământul tehnic – calificări în servicii”, cod SMIS 130788\"<br /> Centralizator activitati stagii de practica luna $MONTH </strong></p> <h3 style=\"text-align: center;\">PLANIFICAREA TEMATICA LUNA $MONTH </h3> <br/> <table style=\"border:1px solid black; width:100%; border-collapse: collapse; text-align: center;\"> <tr style=\"border:1px solid black;\"> <th style=\"border:1px solid black;\">Clasa</th> <th style=\"border:1px solid black;\">Domeniu/Sc Profesioanala/Liceu</th> <th style=\"border:1px solid black;\">Saptamana</th> <th style=\"border:1px solid black;\">Ora start - Ora terminare</th> <th style=\"border:1px solid black;\">Angajator</th> </tr> "; // 原来的while循环改为遍历提前存储的数组即可 foreach ($rows as $row) { $html .= ' <tr> <td style="border:1px solid black;">' . $row['planningClass'] . '</td> <td style="border:1px solid black;">' . $row['classesQualification'] . '</td> <td style="border:1px solid black;">' . $row['planningWeek'] .'</td> <td style="border:1px solid black;">' . $row['planningHourStart'] . ' - ' . $row['planningHourEnd'] . '</td> <td style="border:1px solid black;">' . $row['planningCompany'] .'</td> </tr>'; } $html .= '</table>';
如果你的查询结果中包含多个不同月份的记录,可以先按月份对$rows数组分组,每个分组单独生成头部+表格即可。
内容的提问来源于stack exchange,提问作者Andrei Valentin Niculae
相关产品推荐
相关产品推荐

