CodeIgniter Forums

Full Version: why is the $this->db not available in a certain module?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In my controller I am using $this->load->database(); which gives me access to $this->db in that controller. I have a php file at /app/assets/MyExport6765.php. But I have no access to $this->db in it. I can see $this in my debugger, but the db is not in there. Is there someway that I can share the same dbase handle from my controller with MyExport6765.php? I need to do some dbase manipulations of a table in that module. 
Within Controllers/Models you can use either $db = $this->db; like $db = db_connect(); The ideal is $db = $this->db;
In other types of files $db = $this->db; is not supported, only $db = db_connect(); I'm talking about CI4, obviously.
(04-23-2021, 02:23 PM)wdeda Wrote: [ -> ]Within Controllers/Models you can use either $db = $this->db; like $db = db_connect(); The ideal is $db = $this->db;
In other types of files $db = $this->db; is not supported, only $db = db_connect(); I'm talking about CI4, obviously.
Thanks, I am still on CI3
I recommend you learn about PHP and OOP.

$this->load->database() creates a database object of CI3 and set it to the property $db ($this->db)
in the controller. Within CodeIgniter's Models, you can also use $this->db.
It is the functionality of CodeIgniter.

If you want to use a database object of CI3 in your MyExport6765.php,
you need to create a database object in it or inject the db object into it.
PHP Code:
$ci =& get_instance();

$db $ci->db_connect(); 
(04-23-2021, 08:43 PM)InsiteFX Wrote: [ -> ]
PHP Code:
$ci =& get_instance();

$db $ci->db_connect(); 
Thanks Insite. I am getting this error:

Type: Error
Message: Call to undefined method Configure::db_connect()
Filename: /app/assets/MyExport6765.php
I believe there is a function deviation. The code is self-explanatory: it must be used to connect to a database. Unlike $db = $this->db; which can only be used in Controllers/Models, since "$this->" cannot be used in a non-object context.
Although not recommended if you want to make a query outside the Model/Controller you can use it:
PHP Code:
$db db_connect();
$query $db->table('mytable')
// and so on ... 


https://codeigniter.com/user_guide/datab...cting.html

I insist: I'm talking about CodeIgniter 4!
This option, db_connect();, is exclusive to CI4.

https://codeigniter.com/userguide3/datab...cting.html
The problem is that db_connect() is not found. I am on CI3, btw.
I then tried using $db = \Config\Database::connect();
instead but I get Class 'Config\Database' not found
CodeIgniter 3 uses load database here the code for that one.

PHP Code:
$ci =& get_instance();

$ci->load->database(); 

Not tested but sould be something around that.