首页 > 解决方案 > Mysql query order by desc limit in codeigniter

问题描述

I have a table target like below

id |    subject        |      achievement                |     staff_id
1     Target January          1150000                            1
2     Target January          1350000                            2
3     Target February         20000000                           1
4     Target February         23500000                           2
5     Target January          1500000                            3

What I want to show is in codeigniter using sql query like

SELECT * FROM `target` WHERE `staff_id`='$id' ORDER BY 'id' DESC LIMIT 3,1

I have tried in codeigniter using get where,order by and limit query however the screen is going blank

Here's the model code

    $id=get_staff_user_id();
    $this->db->get_where('target', array('staff_id'=>$id,));
    $this->db->order_by('id','desc');
    $this->db->limit(3, 1);  
    $query=$this->db->get();
    return $query;

Here's the controller code

 $data['target'] = $this->target_model->getAllTarget()->result();

Here's the view code

 <?php foreach($targets as $target){ 
  if($total >= floatval($target->achievement)) {
                $percent = 100;
            } else {
                if ($total !== 0) {
                    $percent = number_format(($total * 100) / $target->achievement, 2);
                }
            }
  echo $percent;
 ?>

Where's the error in my code ?

Thank you

标签: phpmysqlcodeigniter

解决方案


问题是 -get_where()已经返回一个数据库结果实例 - 为了解决您的问题,您必须执行类似的操作

return $this->db
    ->select('*')
    ->from('target')
    ->where('staff_id', get_staff_user_id())
    ->order_by('id', 'desc')
    ->limit(3,1)
    ->get();

推荐阅读