Making $db available globally |
Taken from https://codeigniter.com/user_guide/datab...cting.html
Quote:You can connect to your database by adding this line of code in any function where it is needed, or in your class constructor to make the database available globally in that class. When i do exactly that: Code: <?php ErrorException Undefined variable $db I also tried adding it into the BaseController which im trying to use as Ci3's version of an autoloader but i get the same error Code: public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) Kindly point me in the right direction.
You are missing some OOP notions. In your example, $db is a local variable, not a class property. You need to assign it to $this->db.
But, I wouldn't advise you to do that. Database queries should be done in models, not in controllers. CI is very flexible and won't prevent you from doing database requests everywhere, but your application will be hard to maintain and debug if you have SQL all over the place instead of following the MVC pattern.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
You should simply use ,
db_connect()->table('table_name')->...->...; This one is already enough global.
(10-16-2021, 09:11 PM)iRedds Wrote: The controller is not the place for database queries You can still create a database object in a controller and invoke a method that queries or updates the database. You don't need to use the CI model class. He/she could do this in the BaseController and then it would be sort of "global".
Simpler is always better
(10-17-2021, 12:55 AM)donpwinston Wrote:(10-16-2021, 09:11 PM)iRedds Wrote: The controller is not the place for database queries It is technically possible but not a best practice. If it's not in a model class it should at least be in a library.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/ |
Welcome Guest, Not a member yet? Register Sign In |