0

I am trying to port an application's few functions from a CodeIgniter application to another existing CodeIgniter application. Both applications on themselves are working very well but when I added this thing it gives the following error:

Fatal error: Call to a member function order_by() on null in …\application\core\MY_Model.php on line 7

In this question I have removed parts unrelated to the error to simplify code.

//MY_Model.php model file

<?php
class MY_Model extends CI_Model {
    protected $_order_by = '';

    public function get(){
        $this->db->order_by($this->_order_by);
    }
}

//article_m.php model file

<?php
class Article_m extends MY_Model
{
    protected $_order_by = 'pubdate desc, id desc';
}

//frontend.php controller file

<?php
class Frontend extends MY_Controller
{
    function __construct()
    {
    $this->load->model('article_m');  
    }
    function index()
    {
    $this->article_m->get();
    }
}

Please help. Thank you!

0

1 Answer 1

2

whenever calling any $this->db ... you have to make sure to load your database library. Check in application\config\autoload.php for the following:

$autoload['libraries'] = array('database');
Sign up to request clarification or add additional context in comments.

3 Comments

that worked thanks! is there anyway to load database from controller itself?
you should not load any database information in the controller as this is not good MVC practice. All database interaction should be done in your Model. If you do not want to autoload the the database library, you can run $this->load->library('database') in your model method prior creating your queries.
Sorry to be not clear what I meant, I actually wanted to ask this:- Is there anyway to load the database library from a controller? I did not mean database info from controller but load/activate database library. I seem to have got the answer by the way. I got this line from an app using this to load database lib from controller :- $this->load->database();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.