Welcome Guest, Not a member yet? Register   Sign In
CodeIgniter 4 - How to autoload Database library?
#1

Hello,
Please help me what should I write (and in which file) to automatically load the database library. Now I try to do it like this and it works:
Thank you!

Controllers/Test.php

PHP Code:
<?php

namespace App\Controllers;

class 
Test extends BaseController
{
    public function index(): string
    
{
        $db = \Config\Database::connect();

        $query $db->query('SELECT name FROM users');
        $data['results'] = $query->getResult();

        $data['title'] = 'Title';
        $data['description'] = 'Description';
        
        
return view('test'$data);
    }

Reply
#2

You can also do this.

A convenience method exists that is purely a wrapper around the above line and is provided for your convenience:

PHP Code:
$db db_connect(); 
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

I'm answering myself, maybe this will be useful to someone.

Initiate the Database globally on the BaseController in the "initController" function:

PHP Code:
$this->db = \Config\Database::connect();

// And use it anywhere:

$query $this->db->query('SELECT name FROM users');
$data['results'] = $query->getResult(); 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB