Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this:

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

Now, I want to use these variables 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);
}

Next, I call that private function within my public functions to retrieve data from 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,
      }, ],
    });  
   }
});

If you are encountering errors with the select_sum() function in your model, you may need to check the syntax and ensure that the database query is constructed correctly. Additionally, debugging tools or error logs can help identify any specific issues.

Answer №1

It appears that you may have overlooked adding a $this variable in the function get_data_query. The function body does not contain a $battery_consumption array, and there is also missing a function keyword. This could result in errors being flagged by my PHP IDE even before running the code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The window:beforeunload event in IE 11 always triggers the unsaved changes dialogue box

When it comes to adding a listener for the beforeunload event on the global window object, IE 11 behaves differently compared to Chrome and Firefox. This is particularly noticeable when using Angular's "ngForm" module. If a form is dirty and has not ...

How should v-select, item-text, and item-value be correctly utilized?

When I make an API call, the response is returned. from another perspective. I store the result of the API call in a variable called result = [];. To create a dropdown list, I use v-select with :items="result". If I want the services.name to ...

The process of prioritizing specific elements at the top of an array when ordering

In my array, I want to prioritize specific items to always appear at the top. The API response looks like this: const itemInventorylocationTypes = [ { itemInventorylocationId: '00d3898b-c6f8-43eb-9470-70a11cecbbd7', itemInvent ...

Revolving mechanism within React.js

I am currently developing a lottery application using React.js that features a spinning wheel in SVG format. Users can spin the wheel and it smoothly stops at a random position generated by my application. https://i.stack.imgur.com/I7oFb.png To use the w ...

retrieving the result from an asynchronous function in Node.js

Currently, I am using Node.js to query data from Mongodb via Mongoose. Once the data is retrieved, I need to perform some operations on it before sending it back to the client. However, I am facing an issue where I cannot access the return value of the d ...

Comparing obj.hasOwnProperty(key) with directly accessing obj[key]

Consider the scenario where I need to determine if a property exists within an Object. A comparison between two methods caught my attention: if(object.hasOwnProperty(key)) { /* perform this action */ } OR if(object[key]) { /* perform this action */ ...

AngularJS to validate image dimensions (width and height) on upload

Hello, I am new to working with Angular JS. I have been experimenting with a login form that includes a file upload field for the user picture. The input field code looks like this: <input type="file" file-model="userPic"/> When I submit the form i ...

Having trouble setting up Strongloop for Loopback v.3 on macOS Catalina?

I'm currently in the process of understanding Loopback v3 (which is being utilized on a project site where I'm actively involved), and I'm attempting to follow the tutorials provided. One of the crucial steps involves installing Strongloop ...

Passing variable values from .post response to PHP: A guide

I'm currently working on integrating Geocode from the Google Maps API into my WordPress plugin within the wp-admin. I have created a custom post type that includes an input field for the address of a place, and I also have jQuery code set up to watch ...

What are the steps to make React JSX direct to "/profile" and display the profile page?

Throughout my application, I have integrated reach router to facilitate navigation between the different pages. However, I came across a navbar component that I really like and decided to add it to my app. Strangely, clicking on the "to: "/profi ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

Protractor's Get Attribute Value function may return null after updating the Chrome version

Having trouble with Get Attribute Value returning null after updating to the latest Chrome version 91.0.4472.77. It was working perfectly before the update. selector.getAttribute('value') => now returns null Does anyone have an alternativ ...

Trouble with image display in a next.js project hosted on Firebase

Exploring Next.js for the first time, I recently created a website and attempted to host it on Firebase hosting. Everything seems to be working well except for one issue - the images are not rendering on the hosted site. In my project structure, there are ...

What is the best way to initiate the handling of newly inserted values in a Vuex store?

I am working with a Vuex store that stores entries: const store = createStore({ state() { return { entries: [ { id: 1, date-of-birth: "2020-10-15T14:48:00.000Z", name: "Tom", }, ...

After creating a new Packery using AngularJS, the getElementById function may return null

Alright, so I've got this HTML markup: <button ng-click="create()">create list</button> Every time I click it, I create a new list using the Packery jQuery plugin. app.directive('packery', ['$compile', function($com ...

Unexpected outcomes in linq.js

Hey there, I have a JSON object named "Faults" that looks like this: "Faults":[{"RoomId":1,"ElementId":173,"FaultTypeId":1,"Count":1,"Remark":""},{"RoomId":3,"ElementId":211,"FaultTypeId":7,"Count":1,"Remark":""},{"RoomId":4,"ElementId":173,"FaultTypeId": ...

Replacing data in a Node server

I am currently working on a server that temporarily stores files in its memory before uploading them to the database. Below is the code snippet I'm using: uploadImage(file, uid, res) { var fs = require('fs'); mongoose.connect(config ...

Unable to access the attributes of the mongoose model

I'm experiencing an issue with my mongoose model.find code below Displayed here is my node.js code that utilizes mongoose to interact with MongoDB. However, upon running it, I encounter the following error message: Starting... (node:7863) Unhandl ...

Update the div content to completely replace it with fresh data using Ajax

I'm currently working on implementing a currency switcher feature for my website, allowing users to toggle between two different currencies. The site is a reservation platform with a booking form displayed on the left side and the booking details occu ...

"Utilize jQuery's append method to dynamically add elements to the DOM and ensure

I am currently facing an issue with my AJAX function that appends HTML to a page using the jQuery append method. The HTML being appended is quite large and contains cells with colors set by CSS within the same document. The problem I'm encountering i ...