MySQL在Codeigniter中按DESC限制排序

时间:2019-07-18 11:01:45

标签: php mysql codeigniter

我有一个类似下面的表格目标

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

我想显示的是在

之类的使用SQL查询的codeigniter中
SELECT * FROM `target` WHERE `staff_id`='$id' ORDER BY 'id' DESC LIMIT 3,1

我已经在Codeigniter中尝试使用get where,order by和limit查询,但是屏幕变黑了

这是型号代码

    $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;

这是控制器代码

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

这是查看代码

 <?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;
 ?>

我的代码中的错误在哪里?

谢谢

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

在模型中:

  

删除多余的逗号

int i = 0;
while(i < s.Length) {
    // get the current character
    char c = s[i];
    if(c == ',') {
        // current character is a comma
        // check if the previous character was also a comma OR if the current position is at the start/end of the string
        if(i == 0 || s[i - 1] == ',' || i == s.Length - 1) {
            MessageBox.Show("Substring empty");
        } else {
            MessageBox.Show("Substring not empty");
        }
    }
    // advance by one position
    ++i;
}

在控制器中:

  

将目标更改为与foreach中的目标相同的目标;

    $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;