【问题标题】:CodeIgniter table class loops through db records 3 times - why?CodeIgniter 表类循环通过 db 记录 3 次 - 为什么?
【发布时间】:2025-12-07 12:50:02
【问题描述】:

这是我的控制器代码(使用 Colin Williams 的模板类):

$this->load->library('table');
$table['records'] = $this->db->get_where('data', array('category_1' => 'weight'));
$this->template->write_view('content', 'vw/weight_vw', $table, TRUE);

还有我的查看代码:

<div class="grid_16">
    <?php echo $this->table->generate($records); ?>
</div>

看看我得到了什么

2   1   29  2011-01-01      10  weight      
4   1   29  2010-11-03      11  weight      
5   1   29  2011-05-02      10  weight      
6   1   42  2011-07-11      23  weight // the database only has records up to here      
2   1   29  2011-01-01      10  weight  // from here on it's repeated twice 
4   1   29  2010-11-03      11  weight      
5   1   29  2011-05-02      10  weight      
6   1   42  2011-07-11      23  weight      
2   1   29  2011-01-01      10  weight      
4   1   29  2010-11-03      11  weight      
5   1   29  2011-05-02      10  weight      
6   1   42  2011-07-11      23  weight

任何想法为什么会发生这种情况?我的代码都没有在循环或类似的东西中。

【问题讨论】:

  • 表数组中还有什么?我问是因为当您将 $table['records'] 声明为查询结果时,我看到您将 $table 传递给 write_view 方法作为 $table。
  • @peter,$table 数组中没有其他内容 - 我应该以不同的方式传递数据吗?我现在将查询移至模型,将 $table 返回到控制器并得到相同的结果。
  • 如何将结果从模型返回到控制器?
  • \\ the model $table['records'] = $this-&gt;db-&gt;get_where('data', array('category_1' =&gt; 'weight')); return $table; \\ the controller $this-&gt;load-&gt;library('table'); $table = $this-&gt;weight_model-&gt;weight_get_data(); $this-&gt;template-&gt;write_view('content', 'vw/weight_vw', $table, TRUE); BTW,当我在全新的控制器和视图上执行此操作时,没有其他代码并且不使用模板,它工作正常 - 当我通过模板运行它时,它会创建这个循环数据
  • 做一些调试看看是否a.如果数据库返回重复的行,b。如果表库以某种方式重复行。执行var_dump() 在每一步后检查变量。

标签: php codeigniter class


【解决方案1】:

使用

 $this->output->enable_profiler()

查看数据库查询。

获取查询并直接针对您的数据库运行它。

很可能您的数据库模型中有一个错误的联接。

【讨论】: