We will cover 2 topics given below:
- – Database connection in CodeIgniter 4.
- – Database Access in controller or View.
Database connection in CodeIgniter 4
Open app/Config/Database.php and set your database connection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public array $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'username of your DB', 'password' => 'password of your DB', 'database' => 'Databse name goes here', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => true, 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ]; |
Database Access in controller and View
Controller:
1 2 3 4 | public function __construct() { $db = db_connect(); // DB Connection $this->YourModel = new YourModel($db); // DB Connection for model } |
View:
1 2 3 4 5 6 | <?php $db = db_connect(); $query = $db->query('YOUR QUERY'); //you get result as an array in here but fetch your result however you feel to $result = $query->getResultArray(); ?> |
Complete code of controller with DB Connection and connection to model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php namespace App\Controllers; use App\Controllers\BaseController; use App\Models\HomeModel; // Model Load class Home extends BaseController { public function __construct() { $db = db_connect(); $this->HomeModel = new HomeModel($db); } public function index() { //return view('welcome_message'); echo view('includes/header'); echo view('homepage'); echo view('includes/footer'); } } |