CodeIgniter Forums
Call $this->db from initController in __construct? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Call $this->db from initController in __construct? (/showthread.php?tid=73866)



Call $this->db from initController in __construct? - Smil3y - 06-14-2019

Hi,

is it possible to use $this->db in controller in __construct function from BaseController?
This is my code:

PHP Code:
    public function __construct()
    {

        
$data = [];

        
$dbData $this->db->query("SELECT * FROM myTable");
        
$resultBots $dbData->getResultArray();



    } 

However, I get a "We hit a snag" error.


RE: Call $this->db from initController in __construct? - donpwinston - 06-14-2019

rename the env file to .env. Edit the file and set CI_ENVIRONMENT to development.

Then you'll get an error message describing what went wrong that will answer your question.


RE: Call $this->db from initController in __construct? - kilishan - 06-14-2019

donpwinston is right. That way you'll be able to see the errors. However I can tell you one right off the bat.

The $this->db doesn't work like you're used to in previous versions of CI. There is no more CI "superobject". You need to instantiate the things you need by calling new ClassName() and the like. For databases, there's the quick connection method of:

Code:
$db = db_connect();
$dbData = $db->query("SELECT * FROM myTable");