Search code examples
javascriptphpajaxcodeigniterdatatable

How to make query select_sum in private variable


I have private variable in codeigniter like this :

private $table = 'phone';
private $column_order = array(null, 'name', 'price');
private $type = array('type');
private $battery_consumption = array('battery_consumption');

And I want using my variable in my private model :

private get_data_query(){
   $this->db->select($this->column_order);
   $this->db->select_sum($this->battery_consumption);
   $this->db->from($this->table);
   $this->db->group_by($this->type);
}

And Then I Call that private function into my public function to use fetch my data in the table :

function get_datatables(){
   $this->_get_data_query();
   if($_POST['length'] != -1)
   $this->db->limit($_POST['length'], $_POST['start']);
   $query = $this->db->get();
   return $query->result();
}

function count_filtered()
{
    $this->_get_data_query();
    $query = $this->db->get();
    return $query->num_rows();
}

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

In Controller:

public function get_data_phone()
{
    $list = $this->m_phone->get_datatables();
    $data = array();
    $no = $_POST['start'];

    foreach ($list as $field) {
        $row[] = $no;
        $row[] = $field->name;
        $row[] = $field->type;
        $row[] = $field->price;
        $row[] = $field->battery_consumption;
        $data[] = $row;
    }

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

In View:

<div class="card-block">
    <div class="dt-responsive table-responsive">
        <table id="phone" class="ui celled table" style="width:100%">
            <thead>
                <tr>
                    <th>No</th>
                    <th>Phone Name</th>
                    <th>Phone Type</th>
                    <th>Phone Price</th>
                    <th>Battery Health</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

Datatable query:

let table;

$(document).ready(function() {
   phone_data();

   function phone_data() {
      table = $('#phone').DataTable({
      "processing": true,
      "serverSide": true,
      "order": [],

      "ajax": {
         "url": "<?= site_url('phone/get_data_phone') ?>",
         "type": "POST",
      },

      "columnDefs": [{
         "targets": [0],
         "orderable": false,
      }, ],
    });  
   }
});

But My Query in model still error using select_sum(), what sould i do?


Solution

  • For me it seems you forgot a $this in function get_data_query. There's no $battery_consumption array in the function body. And you also didn't put a function keyword there, my PHP IDE marks errors on that even without running anything.