PostgreSQL循环批量生成客户采购报表PDF的实现方案咨询
批量生成客户采购明细PDF方案(PHP+PostgreSQL 9.3)
核心思路
用PHP连接PostgreSQL,先拉取所有需要生成报表的客户ID,循环遍历每个ID执行采购明细查询,最后将查询结果导出为单独的PDF文件。
准备工作
- 确保PHP已启用
pgsql扩展(在php.ini中检查extension=pgsql是否开启) - 引入轻量PDF生成库
FPDF(直接下载源码放到项目目录即可)
完整代码实现
<?php require('fpdf.php'); // 数据库配置 $dbHost = 'localhost'; $dbName = '你的数据库名'; $dbUser = '数据库用户名'; $dbPass = '数据库密码'; $reportMonth = '2024-02'; // 每月修改这个参数 $startDate = $reportMonth . '-01'; $endDate = date('Y-m-t', strtotime($reportMonth)); // 自动获取当月最后一天 // 连接PostgreSQL $conn = pg_connect("host=$dbHost dbname=$dbName user=$dbUser password=$dbPass"); if (!$conn) { die('数据库连接失败: ' . pg_last_error()); } // 获取所有需要生成报表的客户ID(可根据需求加过滤条件,比如只取活跃客户) $clientQuery = "SELECT DISTINCT client_id FROM purchase_orders WHERE fec_rec BETWEEN '$startDate' AND '$endDate'"; $clientResult = pg_query($conn, $clientQuery); if (!$clientResult) { die('查询客户ID失败: ' . pg_last_error()); } // 循环处理每个客户 while ($clientRow = pg_fetch_assoc($clientResult)) { $clientId = $clientRow['client_id']; // 查询该客户的采购明细 $orderQuery = "SELECT order_no, date, item, total FROM purchase_orders WHERE client_id='$clientId' AND fec_rec BETWEEN '$startDate' AND '$endDate'"; $orderResult = pg_query($conn, $orderQuery); if (!$orderResult) { echo "客户ID $clientId 查询失败,跳过\n"; continue; } // 检查是否有数据 if (pg_num_rows($orderResult) === 0) { echo "客户ID $clientId 本月无采购数据,跳过\n"; continue; } // 生成PDF $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial', 'B', 16); $pdf->Cell(0, 10, "客户ID $clientId 采购明细报表 ($reportMonth)", 0, 1, 'C'); $pdf->Ln(10); // 表格表头 $pdf->SetFont('Arial', 'B', 12); $pdf->Cell(40, 10, '订单号', 1); $pdf->Cell(30, 10, '日期', 1); $pdf->Cell(80, 10, '商品', 1); $pdf->Cell(40, 10, '总价', 1); $pdf->Ln(); // 填充表格数据 $pdf->SetFont('Arial', '', 10); while ($orderRow = pg_fetch_assoc($orderResult)) { $pdf->Cell(40, 10, $orderRow['order_no'], 1); $pdf->Cell(30, 10, $orderRow['date'], 1); $pdf->Cell(80, 10, $orderRow['item'], 1); $pdf->Cell(40, 10, number_format($orderRow['total'], 2), 1); $pdf->Ln(); } // 保存PDF文件 $pdfPath = "./reports/client_{$clientId}_{$reportMonth}.pdf"; $pdf->Output('F', $pdfPath); echo "已生成报表: $pdfPath\n"; // 释放结果集 pg_free_result($orderResult); } // 清理资源 pg_free_result($clientResult); pg_close($conn); ?>
注意事项
- 替换代码中的数据库配置、报表保存路径为实际值
reportMonth变量每月修改一次即可,代码会自动计算当月起止日期- 如果客户ID是数字类型,去掉SQL里的单引号
- 若需要更美观的PDF样式,可调整FPDF的字体、单元格大小、颜色等参数
- 针对PostgreSQL 9.3,以上SQL语法完全兼容,无需修改
内容的提问来源于stack exchange,提问作者Pablo Mazzara
相关产品推荐
相关产品推荐

