PHP表格无法渲染仅显示空白页面,求排查解决方案
问题排查与修复方案
嘿,我帮你找出了代码里几个会导致页面空白或渲染异常的关键问题,一个个来梳理:
1. Foreach循环的致命语法错误
你写的循环是:
<?php foreach ($animal as $a); ?>
这里的分号是大问题——PHP看到这个分号会直接认为循环体结束了,后面的表格行代码根本不会被循环执行,自然没有内容输出。因为你后面用了endforeach,所以正确的写法应该是把分号改成冒号:
<?php foreach ($animal as $a): ?>
如果你习惯用大括号风格,也可以写成:
<?php foreach ($animal as $a) { ?>
记得把后面的<?php endforeach; ?>改成<?php } ?>就行。
2. 变量名混乱错误
好几处变量用错了,这会导致PHP输出空值或者报错:
- 第二列的
$p['dogs_count']应该是$a['dogs_count'](循环变量是$a,不是$p) - 编辑按钮里的
$p[animal]同样要改成$a['animal'],而且数组键必须加引号,不然PHP会把animal当成未定义的常量,直接报错 - 最后多出来的
<td><?php echo $p['edit'] ?></td>完全没必要,不仅变量名错了,你的表头里也没有对应的列,会破坏表格的结构匹配
3. HTML标签的无效闭合
- 开头的
<i class="fa fa-chevron-down toggle" aria-hidden="true"></i></span>多了一个</span>,前面根本没打开对应的<span>标签,这会让浏览器的HTML解析器混乱,可能直接跳过整个表格的渲染 - 第二列的
<td>里多了一个</a>,前面没有打开的<a>标签,也是无效的HTML,同样会影响渲染
4. 额外需要确认的点
如果上面的错误都修复了还是空白,再检查这几个地方:
- 先确认
$animal变量有没有数据:在循环前加一行<?php var_dump($animal); ?>,看看输出的是不是非空的数组 - 如果你用了DataTables插件,要确保已经正确引入它的CSS和JS文件,并且在页面加载完成后初始化表格:
$(document).ready(function() { $('.datatable').DataTable(); });
- 数据库连接是否正常,有没有正确把查询结果赋值给
$animal变量
修复后的核心代码示例
<section class="cc-margin-top-50"> <div class="container-fluid"> <div class="page-header"> <h4><i class="fa fa-chevron-down toggle" aria-hidden="true"></i> Animals in shop </h4> </div> <div class="table-responsive well"> <table class="datatable display responsive"> <thead> <?php addcolumnfilters('7','animals_table'); ?> <tr> <th>cats</th> <th>dogs</th> <th>mice</th> <th>rabbits</th> <th>birds </th> <th>snakes</th> <th>edit</th> </tr> </thead> <tbody> <?php foreach ($animal as $a): ?> <tr> <td><?php echo $a['cats_count'] ?></td> <td><?php echo $a['dogs_count'] ?></td> <td><?php echo $a['mice_count'] ?></td> <td><?php echo $a['rabbits_count'] ?></td> <td><?php echo $a['birds_count'] ?></td> <td><?php echo $a['snakes_count'] ?></td> <td> <a class="cc-pointer" ng-click="edit_animal_count('<?php echo($a['animal']) ?>')" data-toggle="modal" data-target="#modalAnimalEdit"> <span class="glyphicon glyphicon-edit cc-pointer cc-color-blue" title="Edit/View Notes"></span> </a> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </section>
内容的提问来源于stack exchange,提问作者Celestialchippy
相关产品推荐
相关产品推荐

