Page 3: Model & Database Integration

3. Model and Database Integration

The Model is responsible for interacting with the database. This separates data processing logic from the Controller and View.

3.1. Database Configuration (app/Config/Database.php)

Configure the database connection information (MySQL, PostgreSQL, etc.) in the app/Config/Database.php or .env file.

// .env file Example
database.default.hostname = localhost
database.default.database = my_database
database.default.username = root
database.default.password = 

3.2. Creating a Model and Retrieving Data

Create app/Models/ProductModel.php and inherit CodeIgniter's base Model functionality. Setting the $table property automatically connects to the corresponding table.

// app/Models/ProductModel.php
namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
    protected $table = 'products';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'price', 'description'];

    // Method to fetch all product listings
    public function getAllProducts()
    {
        return $this->findAll();
    }
}

You can now call this Model from the Controller to use the data.