如何修复PHP日期区间搜索后刷新页面出现的foreach无效参数错误
问题根因
Invalid argument supplied for foreach() in C:\xampp\htdocs\parking reservation\admin\reports-details.php on line 52
该报错触发的核心逻辑:
- 从reports.php提交表单时是POST请求,携带
search、start_date、end_date参数,managereport()方法能正常返回查询结果数组,foreach可以正常遍历 - 直接刷新reports-details.php时,请求为GET类型,没有任何POST参数,
managereport()方法没有命中isset($_POST['search'])的判断逻辑,没有指定返回值,默认返回null,foreach无法遍历null类型变量,触发警告。
修复步骤
1. 给查询方法加默认返回值
修改back-end-reports.php的managereport()方法,没有查询条件时默认返回空数组,避免返回null:
<?php include 'config.php'; class report extends Connection{ public function managereport(){ // 没有查询参数时直接返回空数组 if (!isset($_POST['search'])) { return []; } $start_date = $_POST['start_date']; $end_date = $_POST['end_date']; // 提示:此处直接拼接SQL参数存在注入风险,后续建议改为预处理查询 $sqlselect = "SELECT * FROM tbl_customers WHERE test_date BETWEEN '$start_date' AND '$end_date' ORDER BY test_date"; $result = $this->conn()->query($sqlselect); $result->execute(); return $result->fetchAll(); } } $new_vehicle = new report(); $new_vehicle->managereport(); ?>
2. 遍历前增加合法性判断
修改reports-details.php的foreach逻辑,先判断查询结果是否为非空数组,为空时展示提示文案:
<?php include '../back-end/back-end-reports.php'; $result = new report(); $query = $result->managereport(); ?> <?php if (!empty($query) && is_array($query)): ?> <?php $id = 1; foreach($query as $row) { ?> <tbody> <tr> <td><?php echo $id; ?></td> <td><?php echo $row['serial']; ?></td> <td><?php echo $row['fullname']; ?></td> <td><?php echo $row['num_plate']; ?></td> <td><a href="view-ingoing.php?id=<?php echo $row['customers_id']; ?>" class="text-dark">View</a> | <a class="text-dark" href="print.php">Print</a></td> </tr> </tbody> <?php $id++; } ?> <?php else: ?> <tr><td colspan="5" style="text-align:center;">暂无匹配的查询结果,请先在报表页选择日期查询</td></tr> <?php endif; ?>
可选优化(解决刷新重复提交问题)
当前用POST方式提交查询,刷新页面时会弹出“是否重新提交表单”的提示,可以根据需求优化:
- 表单提交方式改为GET,参数会拼接在URL上,刷新也不会丢失参数
- 或者提交后将查询条件存入SESSION,跳转到reports-details.php后从SESSION取参数查询,完全避免重复提交问题
内容的提问来源于stack exchange,提问作者KA trending
相关产品推荐
相关产品推荐

