CodeIgniter 3数据少于5条时隐藏分页失效问题求助
CodeIgniter3 数据少于5条时禁用分页的问题修复
问题根源
- 统计数据错误:模型
jumlah_data方法里,count_all($this->table)会直接返回整张表的总记录数,完全忽略了之前设置的where('status', 'K')和关联查询条件,导致获取的总数据量和实际符合业务要求的记录数不符。 - 分页链接无条件输出:视图中不管是否初始化过分页组件,都会调用
$this->pagination->create_links(),哪怕数据量不足5条也会显示空的分页结构。 - 控制器判断逻辑不规范:
if(($config['total_rows'] = $jumlah_data) >5)是赋值操作而非单纯比较,虽然语法能运行,但写法容易混淆,不利于维护。
修复步骤
1. 修正模型的统计方法
修改MTransaksi模型中的jumlah_data方法,正确统计符合条件的记录数:
public function jumlah_data(){ $status = 'K'; $this->db->where('status', $status); $this->db->join('pelanggan', 'transaksi.id_pelanggan = pelanggan.id_pelanggan'); // 使用count_all_results统计符合条件的记录数 return $this->db->count_all_results($this->table); }
或者用查询后统计行数的写法:
public function jumlah_data(){ $status = 'K'; $this->db->select('*'); $this->db->where('status', $status); $this->db->join('pelanggan', 'transaksi.id_pelanggan = pelanggan.id_pelanggan'); $query = $this->db->get($this->table); return $query->num_rows(); }
2. 调整控制器逻辑,传递分页显示标记
修改Kembali控制器的index方法,规范判断逻辑,并给视图传递控制分页显示的变量:
public function index(){ $data['kembali'] = true; $jumlah_data = $this->MTransaksi->jumlah_data(); $config['base_url'] = base_url().'index.php/Kembali/index/'; $config['total_rows'] = $jumlah_data; $data['show_pagination'] = false; // 默认不显示分页 if($config['total_rows'] > 5){ $config['per_page'] = 5; // 处理URI分段为空的情况,避免报错 $from = $this->uri->segment(3) ?: 0; $this->pagination->initialize($config); $data['result'] = $this->MTransaksi->data($config['per_page'], $from); $data['show_pagination'] = true; // 数据量足够时开启分页显示 }else{ $data['result'] = $this->MTransaksi->getlist("B"); } $this->load->view('kembali', $data); }
3. 修改视图,根据标记控制分页显示
修改视图文件,只有当$show_pagination为true时才输出分页链接:
<?php if($result) : ?> <table class="table table-bordered"> <!-- 表格表头、内容保持原有代码不变 --> <thead> <tr> <th>No</th> <th>No. Kendaraan</th> <th>Nama Peminjam</th> <th>Tanggal Pinjam</th> <th>Tanggal Kembali</th> <th>Aksi</th> </tr> </thead> <tbody> <?php $i = ($this->uri->segment('3') ?: 0) + 1; ?> <?php foreach ($result as $row) : ?> <tr> <td><?php echo $i ?>.</td> <td><?php echo $row->nomor_kendaraan?></td> <td><?php echo $row->nama_pelanggan ?></td> <td><?php echo $row->tanggal_pinjam ?></td> <td><?php echo $row->tanggal_kembali ?></td> <td> <a href="<?php echo site_url()?>/Kembali/kembalikan/<?php echo $row->id_transaksi ?>">Kembalikan</a> </td> </tr> <?php $i++; ?> <?php endforeach ?> </tbody> </table> <!-- 仅当需要显示分页时输出链接 --> <?php if($show_pagination) : ?> <p><?php echo $this->pagination->create_links(); ?></p> <?php endif; ?> <?php else :?> Tidak ada data <?php endif ?>
额外注意:控制器中调用的getlist("B")和模型data方法中的status='B'是一致的,但jumlah_data中统计的是status='K'的数据,若业务上需要统计和展示的是同一批数据,需统一状态值,避免逻辑矛盾。
内容的提问来源于stack exchange,提问作者Sirious
相关产品推荐
相关产品推荐

