2015-11-07 50 views
0

按特定列在笨排序行我使用笨和我的数据库这样有一些数据:获得使用MySQL的

id name priority 

1 Amit  3 
2 Pankaj 2 
3 Ashish 5 

现在我想找回这种格式的数据,按优先级排序:

id name priority 

1 Pankaj 2 
2 Amit  3 
3 Ashish 5 

我尝试这个代码,但没有奏效:

$this->db->select('*')->from('class')->order_by('priority', 'desc'); 
+0

如果顺序,然后'Ashish'应该是第一位的。说啥? –

+0

我想你想按优先顺序排列“ASC”,不是吗? –

+0

但阿米特的位置是一样的。 – user3653474

回答

0

为了能够让你像第二个数据,你需要给我们ASC和返回result_array()

http://www.codeigniter.com/user_guide/database/query_builder.html

的工作形象

enter image description here

如下面的模型图所示:

文件名: Model_sample.php

<?php 

class Model_sample extends CI_Model { 

    public function get_data() { 
     $this->db->select('*'); 
     $this->db->from($this->db->dbprefix . 'class'); 
     $this->db->order_by('priority', 'ASC'); 
     $query = $this->db->get(); 

     if ($query->num_rows() > 0) { 
      return $query->result_array(); 
     } else { 
      return false; 
     } 
    } 
} 

控制器

文件名:的welcome.php

<?php 

class Welcome extends CI_Controller { 

    public function __construct() { 
     parent::__construct(); 

     $this->load->model('model_sample'); 
    } 

    public function index() { 
     $data['results'] = array(); 

     $data['results'] = $this->model_sample->get_data(); 

     $this->load->view('welcome_message', $data); 
    } 
} 

查看

文件名: welcome_message.php

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>Welcome to CodeIgniter</title> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous"> 
</head> 
<body> 

<div class="container"> 
<table class="table"> 
    <thead> 
     <tr> 
      <td>Class ID</td> 
      <td>Name</td> 
      <td>Priority</td> 
     </tr> 
    </thead> 
    <tbody> 
     <?php if ($results) {?> 
     <?php foreach ($results as $result) {?> 
      <tr> 
       <td><?php echo $result['id'];?></td> 
       <td><?php echo $result['name'];?></td> 
       <td><?php echo $result['priority'];?></td> 
      </tr> 
     <?php }?> 
     <?php } else {?> 
      <tr> 
       <td>No Results</td> 
      </tr> 
     <?php }?> 
    </tbody> 
</table> 
</div> 

</body> 
</html> 
0

在模型的优先级从高到低添加此

$query = $this->db->query->("SELECT * FROM class ORDER BY priority DESC") 
$result = $query->result_array(); 
return $result;