使用 Codeigniter 进行数据表服务器端处理
Posted
技术标签:
【中文标题】使用 Codeigniter 进行数据表服务器端处理【英文标题】:Datatables server side processing with using Code Igniter 【发布时间】:2018-02-21 04:07:55 【问题描述】:我正在使用 Code Igniter 框架构建一个论坛。我正在尝试实现 Datatables 服务器端处理。我知道如何使用数据表和 JQuery 进行排序和搜索等操作,但是我的数据库表有可能增长到数千并且一次拉出所有行不会让用户很高兴,所以我试图结合这两个服务器端(Code Igniter)和客户端(AJAX)处理,以便使用限制和偏移量。所以我在网上挖掘并找到了一个很棒的教程。这就是我所拥有的:
模型:Posts_model.php
<?php
var $table = 'general_posts';
var $column_order = array(null, 'title','body','username','time','category'); //set column field database for datatable orderable
var $column_search = array('title','body','username','time','category'); //set column field database for datatable searchable
var $order = array('id' => 'desc'); // default descending order
private function get_posts_query()
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item)
if($_POST['search']['value'])
if($i===0) // first loop
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
else
$this->db->or_like($item, $_POST['search']['value']);
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end();
$i++;
if(isset($_POST['order']))
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
else if(isset($this->order))
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
function get_gen_posts($category)
$this->get_posts_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$this->db->where(array('category' => $category, 'display' => 'true'));
$query = $this->db->get();
return $query->result();
function count_filtered_gen_posts($category)
$this->get_posts_query();
$this->db->where(array('category' => $category, 'display' => 'true'));
$query = $this->db->get();
return $query->num_rows();
public function count_all($category)
$this->db->where(array('category' => $category, 'display' => 'true'));
$this->db->from($this->table);
return $this->db->count_all_results();
?>
控制器:Posts.php
<?php
public function __construct()
parent::__construct();
$this->load->model('posts_model','general_posts');
public function posts($category)
$data['category'] = $category;
$this->load->view('posts', $data);
public function posts_ajax($category)
$list = $this->general_posts->get_gen_posts($category);
$data = array();
foreach ($list as $post)
$row = array();
$row[] = $post->title;
$row[] = $post->body;
$row[] = $post->category;
$row[] = $post->poster;
$row[] = $post->time;
$data[] = $row;
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->general_posts->count_all($category),
"recordsFiltered" => $this->general_posts->count_filtered_gen_posts($category),
"data" => $data,
);
//output to json format
echo json_encode($output);
?>
查看:posts.php
<table id="table" class="table table-no-border" cellspacing="0" style="text-align: left">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
var table;
$(document).ready(function()
//datatables
table = $('#table').DataTable(
"paging": true,
"pageLength" : 10,
"lengthChange": true,
"searching": true,
"info": false,
"autoWidth": true,
"ordering": false,
"stateSave": true,
"processing": true,
"serverSide": true,
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax":
"url": "<?php echo base_url('posts/posts_ajax/'.$category)?>",
"dataType": "json",
"type": "POST",
"data": '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
,
//Set column definition initialisation properties.
"columnDefs": [
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
,
],
);
);
</script>
到目前为止,一切都按预期工作,但并不完全符合我的需要。看看这些行:
foreach ($list as $post)
$row = array();
$row[] = $post->title;
$row[] = $post->body;
$row[] = $post->category;
$row[] = $post->poster;
$row[] = $post->time;
$data[] = $row;
我希望每行的结果显示在 ONE COLUMN 中,而不是 5 列中。这是因为我打算使用 Bootstrap 面板来显示每一行的结果,并根据我的需要对其进行自定义。 我希望每个结果都像这样:
帖子标题:bla bla bla 身体在这里 发表于:类别名称 发布者:发帖人姓名 时间:2017年9月9日晚上10点30分
我想通过样式和格式来控制每个字段的显示方式,例如将时间字段转换为更易于阅读的内容(例如 2017 年 9 月 9 日晚上 10:30)。问题是,由于循环是在控制器内部创建的(而不是在视图中,我已经习惯了),我不知道该怎么做。我知道我是否可以在表格主体标签(此处)之间获得循环,我可以做我想做的事,但我认为如果我这样做了,AJAX 不会欣赏它(我试过了,'他'没有)。这是我第一次涉足 AJAX。
编辑:我想知道是否有办法在视图中使用 post_ajax 函数的内容,以便我可以将 foreach 循环放在 table 的 body 标记中。 所以我需要帮助。请帮忙!抱歉,拖了这么久……
【问题讨论】:
您需要使用render
。这是我找到的第一个链接:***.com/questions/40529987/jquery-datatable-how-to-use-render-function-get-data-from-another-column
好的,我会检查的。我想知道是否有办法在视图中使用 post_ajax 函数的内容,以便我可以将 foreach 循环放在 table 的 body 标记中
【参考方案1】:
跟踪镫骨并获得结果
第 1 步:- 在代码下方粘贴视图侧
<table id="table_lists" class="table table-bordered table-hover table-striped datatable ">
<thead>
<tr>
<th>No</th>
<th>Date</th>
<th>Day</th>
<th>Holiday</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="javascript">
var t = $('#table_lists').DataTable(
"processing": true,
"serverSide": true,
"ordering": false,
"ajax":
"url": "<?php echo admin_url('employee/lists'); ?>",
"type": "POST",
,
"columns": [
"data": "no" ,
"data": "date" ,
"data": "day" ,
"data": "holiday" ,
"data": "action",
],
);
</script>
第 2 步:- 在 Controller 中创建这样的函数
public function lists()
$json_data = $this->holiday->get_list_table();
echo json_encode($json_data);
第 3 步:- 在模型中粘贴以下代码 公共函数 get_list_table()
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
$start = $params['start'];
$where = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) )
$where .=" AND ";
$where .=" ( ";
$where .=" name LIKE '%".$params['search']['value']."%' ";
$where .=" OR DATE_FORMAT(date, \"%d-%m-%Y\") LIKE '%".$params['search']['value']."%' ";
$where .=" OR DAYNAME(date) LIKE '%".$params['search']['value']."%' ";
$where .=" )";
$sql = "SELECT *
FROM $this->tbl_holiday
WHERE 1 = 1 $where
ORDER BY date ASC";
$sqlTot .= $sql;
$sqlRec .= $sql;
$sqlRec .= " LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = $this->db->query($sqlTot);
$totalRecords = $queryTot->num_rows();
$queryRecords = $this->db->query($sqlRec);
$results = $queryRecords->result();
$i = ($start + 1);
if(!empty($results))
foreach ($results as $result)
$actions = '<a href="javascript:void(0);" onclick="javascript: editHoliday('.$result->id.');" class="btn btn-info btn-sm">
<i class="fa fa-edit"></i>
</a>
<a href="javascript:void(0);" title="Delete" data-toggle="modal" data-target="#confirm-delete" class="btn btn-danger btn-sm" data-href="'.admin_url('holiday/delete/'.$result->id).'">
<i class="fa fa-trash"></i>
</a>';
$data[] = array(
'no' => $i,
'date' => date('d-m-Y', strtotime($result->date)),
'day' => date('l', strtotime($result->date)),
'holiday' => $result->name,
'action' => $actions,
);
$i++;
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
return $json_data;
【讨论】:
以上是关于使用 Codeigniter 进行数据表服务器端处理的主要内容,如果未能解决你的问题,请参考以下文章
在codeigniter查询生成器中使用union,并在虚拟mysql列中进行过滤
如何使用 codeigniter 中的事务进行基于数据更改的提交和回滚?