Datatables joining tables search and order stuck with codeigniter

好久不见. 提交于 2020-01-02 05:04:28

问题


I was follow this step to learn datatables with codeigniter. But I'm getting some error with joining two tables to use search at datatables. This is my error,

And then as I see at the documentation AJAX error, the resolution is search finding error server at network request browser. And I'm getting 500 Internal Server Error. This is I copied the response body for the fault.

Error Number: 42000/1064

You have an error in your SQL syntax; check the manual that corresponds to >your MySQL server version for the right syntax to use near 'as >nm_propinsi LIKE '%c%' ESCAPE '!' ) ORDER BY id_kota DESC LIMIT 10' at line 7

SELECT * FROM `kota` as `k` LEFT JOIN `propinsi` as `p` ON `p`.`id_propinsi` = `k`.`id_propinsi` WHERE ( `k`.`id_kota` LIKE '%c%' ESCAPE '!' OR `k`.`nm_kota` LIKE '%c%' ESCAPE '!' OR `p`.`nm_propinsi` as `nm_propinsi` LIKE '%c%' ESCAPE '!' ) ORDER BY `id_kota` DESC LIMIT 10

The fault is on my query to get list data by LIKE for datatables.

This is my model to create query search for datatables,

var $column = array('k.id_kota','k.nm_kota', 'p.nm_propinsi as nm_propinsi'); //set column field database for order and search
var $order = array('id_kota' => 'desc'); // default order 
function get_datatables(){
  $this->_get_datatables_query();
  if($_POST['length'] != -1)
  $this->db->limit($_POST['length'], $_POST['start']);
  $query = $this->db->get();
  return $query->result();
}
private function _get_datatables_query(){

  $this->db->from('kota as k');
  $this->db->join('propinsi as p', 'p.id_propinsi = k.id_propinsi');

  $i = 0;

  foreach ($this->column as $item) // loop column 
  {
     if($_POST['search']['value']) // if datatable send POST for search
     {

        if($i===0) // first loop
        {
           $this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND. 
           $this->db->like($item, $_POST['search']['value']);
        }
        else
        {
           $this->db->or_like($item, $_POST['search']['value']);
        }

        if(count($this->column) - 1 == $i) //last loop
           $this->db->group_end(); //close bracket
     }
     $column[$i] = $item; // set column array variable to order processing
     $i++;
  }

  if(isset($_POST['order'])) // here order processing
  {
     $this->db->order_by($column[$_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)]);
  }
}

My function controller to get AJAX JSON,

public function list_kota(){
    $this->load->model("kota_model");
    $list = $this->kota_model->get_datatables();
    $data = array();
    $no = $_POST['start'];
    foreach ($list as $ko) {
        $no++;
        $row = array();
        $row[] = $ko->id_kota;
        $row[] = $ko->nm_kota;
        $row[] = $ko->nm_propinsi;

        //add html for action
        $row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" title="Edit" onclick="edit_kota('."'".$ko->id_kota."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>
              <a class="btn btn-sm btn-danger" href="javascript:void()" title="Hapus" onclick="delete_kota('."'".$ko->id_kota."'".')"><i class="glyphicon glyphicon-trash"></i> Delete</a>';

        $data[] = $row;
    }

    $output = array(
        "draw" => $_POST['draw'],
        "recordsTotal" => $this->kota_model->count_all(),
        "recordsFiltered" => $this->kota_model->count_filtered(),
        "data" => $data,
        );
    //output to json format
    echo json_encode($output);
}

What should I do now? Any suggestion?


回答1:


based on your models, you can modify it just like below

private function _get_datatables_query($term=''){ //term is value of $_REQUEST['search']['value']
    $column = array('k.id_kota','k.nm_kota', 'p.nm_propinsi');
    $this->db->select('k.id_kota, k.nm_kota, p.nm_propinsi');
    $this->db->from('kota as k');
    $this->db->join('propinsi as p', 'p.id_propinsi = k.id_propinsi','left');
    $this->db->like('k.id_kota', $term);
    $this->db->or_like('k.nm_kota', $term);
    $this->db->or_like('p.nm_propinsi', $term);
    if(isset($_REQUEST['order'])) // here order processing
    {
       $this->db->order_by($column[$_REQUEST['order']['0']['column']], $_REQUEST['order']['0']['dir']);
    } 
    else if(isset($this->order))
    {
       $order = $this->order;
       $this->db->order_by(key($order), $order[key($order)]);
    }
}

function get_datatables(){
  $term = $_REQUEST['search']['value'];   
  $this->_get_datatables_query($term);
  if($_REQUEST['length'] != -1)
  $this->db->limit($_REQUEST['length'], $_REQUEST['start']);
  $query = $this->db->get();
  return $query->result(); 
}

function count_filtered(){
  $term = $_REQUEST['search']['value']; 
  $this->_get_datatables_query($term);
  $query = $this->db->get();
  return $query->num_rows();  
}

public function count_all(){
  $this->db->from($this->table);
  return $this->db->count_all_results();  
}



回答2:


why not library ignited-datatables ? and combine with jquery.dataTables.columnFilter.js ..

Example View diplay view

Controller :

    function fnDataJson()
{
    $this->load->library('datatables');
    $this->datatables->select('id,first_name,last_name,position,email,office,salary');
    $this->datatables->from('datatables_demo');

    echo $this->datatables->generate();
}

View

// HTML
<table id="tableEmployee" class="table datares">
    <thead>
        <tr>
            <th>id</th>
            <th>first_name</th>
            <th>last_name</th>
            <th>position</th>
            <th>email</th>
            <th>office</th>
            <th>salary</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
    <tfoot>
        <tr>
            <th>id</th>
            <th>first_name</th>
            <th>last_name</th>
            <th>position</th>
            <th>email</th>
            <th>office</th>
            <th>salary</th>
        </tr>
    </tfoot>
</table>


// Javascript
    oTable = $('#tableEmployee').dataTable({
        "processing": true,
        "serverSide": true,
        "sAjaxSource": "<?php echo site_url();?>/md_employee/fnDataJson",
        "aoColumns": [ 
            {'sName' : 'id'},{'sName' : 'first_name'},{'sName' : 'last_name'},{'sName' : 'position'},{'sName' : 'email'},{'sName' : 'office'},{'sName' : 'salary'} 
        ],
        "fnServerData": function( sSource, aoData, fnCallback ) {
            $.ajax( {
                'dataType': 'json',
                'type'    : 'POST',
                'url'     : sSource,
                'data'    : aoData,
                'success' : fnCallback
            } );
        },      
        "fnRowCallback": function (nRow, aData, iDisplayIndex, DisplayIndexFull) {
          var page      = this.fnPagingInfo().iPage;
          var lengt     = this.fnPagingInfo().iLength;
          var index     = (page * lengt + (iDisplayIndex +1));
          //alert( 'Now on page '+index );
          $('td:eq(0)', nRow).html(index+'<input type="hidden" id="idEmployee'+iDisplayIndex+'" value="'+aData[0]+'" >');
        }
    }).columnFilter({ aoColumns: [
            null,
            { type: "text", bRegex:true },
            { type: "text", bRegex:true },
            { type: "text", bRegex:true },
            { type: "text", bRegex:true },
            { type: "text", bRegex:true },
            { type: "text", bRegex:true }
        ]});


来源:https://stackoverflow.com/questions/34385680/datatables-joining-tables-search-and-order-stuck-with-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!