如何使用PHP和MySQL实现HTML表格序列号垂直格式输出
实现垂直排序学生表格的解决方案
你原有代码的核心问题有两个:
- 变量命名冲突:预设的行数变量
$row和数据库查询结果接收变量重名,会导致预设配置被覆盖 - 逻辑顺序错误:需要先把所有符合条件的学生数据全部读取到数组中,再按垂直排列规则拼接表格,边查询边输出无法实现跨列的垂直排序逻辑
完整实现代码
<?php // 数据库查询 $query = mysqli_query($conn,"SELECT * FROM `students` WHERE student_status = 'active' "); // 配置项:修改变量名避免冲突 $per_col_rows = 5; // 每列显示的行数 $total_cols = 4; // 总列数 $students = []; // 存储所有学生数据 // 先把所有学生数据读取到数组中 while($student = mysqli_fetch_array($query)){ $students[] = $student; } $output = ''; $output .= '<table border="1">'; // 加border方便看效果,可自行删除 // 按行循环,每一行对应所有列的同一行位置 for($row_index = 0; $row_index < $per_col_rows; $row_index++){ $output .= '<tr>'; // 循环每一列 for($col_index = 0; $col_index < $total_cols; $col_index++){ // 计算当前位置对应的学生数组索引:列数*每列行数 + 当前行号,实现垂直排序 $stu_index = $col_index * $per_col_rows + $row_index; // 计算序列号 $serial_num = $stu_index + 1; $output .= '<td>'.$serial_num.'</td>'; // 判断索引是否存在,存在输出学生名,否则输出空 if(isset($students[$stu_index])){ $output .= '<td>'.htmlspecialchars($students[$stu_index]['student_name']).'</td>'; }else{ $output .= '<td></td>'; } } $output .= '</tr>'; } $output .= '</table>'; echo $output; ?>
实现逻辑说明
- 垂直排序的核心是索引计算规则:
当前学生索引 = 列索引 * 每列行数 + 行索引,该规则会先填充完第一列的所有行,再填充第二列,以此类推,符合你要的垂直排列效果 - 提前读取所有学生数据到数组,方便按索引取值,也能避免数据不足时出现报错
- 增加了
htmlspecialchars转义输出,避免XSS安全问题
内容的提问来源于stack exchange,提问作者DeezinerKKSoft
相关产品推荐
相关产品推荐

