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

jQuery - How come my string values are getting cut off?

It's been a while since I last worked with jQuery, and I seem to be missing something obvious that's affecting my calculations. I have various text boxes for Weight, Moisture %, and Number of Filled Squares, as well as a multi-select option for ...

Fetching JSON data from an external URL using AngularJS

Check out this URL that shows JSON data in the browser: I attempted to store the data in a variable with the following code: $http.get('http://api.geosvc.com/rest/US/84606/nearby?apikey=4ff687893a7b468cb520b3c4e967c4da&d=20&pt=PostalCode& ...

Securing the connection between clients and servers through encryption

For my mobile client, I am using Xamarin, with node.js as my backend and MongoDB as the database. The main issue I am facing is how to securely store user data in the database. If I only do server-side encryption, there is a risk of hackers intercepting th ...

Comparison of loading time between loader gif and browser's loading image

Recently, I've come across a code snippet where I implemented a 'loader' gif to show while PHP retrieves data from an SQL database. Everything seemed to be working fine when testing on my localhost. However, upon closer observation, I notice ...

Do not open iframe links in a new window

Is it possible to manipulate the iframe so that links open inside the iframe window? I want the links clicked within the iframe to stay within the same window instead of opening in a new one. However, I have too many links to individually edit their code ...

Spotfire: Changing a URL in an input field after it has been entered by the user

Currently, I am faced with a challenge related to importing a file in spotfire based on the path provided by the user. To accomplish this, I am utilizing a data function written in R script. In R, it is essential to note that all "\" characters are n ...

How can I replay an HTML audio element?

I created an HTML5 page with an audio element for playing music in mp3 format. However, when the music plays to the end, it stops and I'm using JavaScript to control the audio element. Even so, I can't seem to replay it, only stop it. Is there a ...

Navigating in a Curved Path using Webkit Transition

Currently, I am working on a simple project to learn and then incorporate it into a larger project. I have a basic box that I want to move from one position to another using CSS webkit animations and the translate function for iOS hardware acceleration. I ...

Having trouble retrieving data from MongoDB and rendering it on an HTML page

Creating a Model Named Field.js in Mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/SuperchainV1', { useNewUrlParser: true }); mongoose.set('useNewUrlParser', true); ...

Retrieve solely the text content from a JavaScript object

Is there a way to extract only the values associated with each key in the following object? const params = [{"title":"How to code","author":"samuel","category":"categoery","body":"this is the body"}] I'm struggling to figure out how to achieve this. ...

Implementing dynamic class bindings with Vue.js using v-for

I am currently using a v-for loop in Vue.js to create a list of items populated with data from an API. Here is an example of the items array: items: [ { foo: 'something', number: 60 }, { foo: 'anything', ...

What could be the reason for the history.length being 2 on the initial page?

Why is it that when I open a new browser window and load a page in it, the history.length property is always 2 in both Chrome and Firefox? You can test this phenomenon yourself by visiting the following link: http://jsbin.com/amiyaw ...

Having trouble with Vue.js not returning HTML elements from methods properly?

I have been attempting to retrieve html elements from a method, and I thought of using v-html for this purpose (not sure if there is a better approach). However, I seem to have encountered an issue with backtick templates and string interpolation. An error ...

What could be causing the Gruntfile to throw an error?

Getting an unexpected error while trying to run grunt $ grunt Loading "Gruntfile.js" tasks...ERROR >> SyntaxError: Unexpected token : Warning: Task "default" not found. Use --force to continue. Execution terminated due to warnings. Here is my ...

Tips for obtaining accurate response from axios

When utilizing axios, I receive my query response in the format of response.data.response.object. Is there a way to access the answer directly without going through response.data first? ...

Utilizing PHP and Ajax for paginating JSON responses

I have successfully parsed some JSON data from the YouTube API, but I am running into a limitation where only 50 results can be shown per request. I am looking for help on how to implement pagination using either JavaScript or Ajax in my PHP script. The go ...

The absence of "_ssgManifest.js" and "_buildManifest.js" files in a Next.js application deployed on Google Cloud Platform was discovered

Upon opening the website, there are instances where the console displays the following errors: GET https://example.com/subpath/_next/static/9ufj5kFJf/_buildManifest.js [HTTP/3 404 Not Found 311ms] GET https://example.com/subpath/_next/static/9ufj5kFJf/_ss ...

Error message: The Node.js filtered LS command is missing a ")" after the argument list

I've been working on the learnyounode workshop and I'm stuck on a code issue. After running it through jslint, I received this feedback: Expected ')' to match '(' from line 6 but instead saw '{'. Oddly enough, line ...

Node development does not operate continuously

I'm facing a minor issue with node-dev. I followed the instructions in the readme file and successfully installed it. However, when I run the command like so: node-dev somescript.js, it only runs once as if I used regular node without -dev. It doesn&a ...

Using jQuery to dynamically include option groups and options in a select box

Generate option groups and options dynamically using data retrieved via AJAX. <select name="catsndogs"> <optgroup label="Cats"> <option>Tiger</option> <option>Leopard</option> <option>Ly ...