我正在使用CodeIgniter并在我的数据库中包含一些数据:
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 :(得分:0)
为了能够为您提供ASC所需的第二个数据并返回result_array()
http://www.codeigniter.com/user_guide/database/query_builder.html
工作图像
如下面的模型所示:
文件名: 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>
答案 1 :(得分:0)
在模型中添加此
$query = $this->db->query->("SELECT * FROM class ORDER BY priority DESC")
$result = $query->result_array();
return $result;