2015-11-07 49 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;