Codeigniter 4 – Creating Database, Model then setting up the configuration

Creating a Database

- Create a new database using your preferred method (e.g. phpMyAdmin, MySQL Workbench).
- Note the database name, username, and password.

Setting up Database Configuration

- Open the app/Config/Database.php file.
- Update the default group with your database settings.

Example:

public $default = [
    'DSN' => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'my_database',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug' => (ENVIRONMENT !== 'production'),
    'cacheOn' => false,
    'cacheDir' => '',
    'charSet' => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre' => '',
    'encrypt' => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port' => 3306,
];

Creating a Model

- Create a new file in the app/Models directory.
- Extend the CodeIgniter\Model class.

Example:

namespace App\Models;

use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
}

Setting up Model Configuration

- Update the app/Config/Model.php file.
- Set the model setting to the namespace of your Model.

Example:

public $model = 'App\Models';

Using the Model

- Use the model() method to load the Model.
- Call methods on the Model to interact with the database.

Example:

$userModel = model('User');
$data = $userModel->find(1);

I hope this helps! Let me know if you have any further questions or need more information.

Note: Setting up a database and Model in CodeIgniter 4 provides a simple and intuitive way to interact with your database. It helps to keep your code organized and maintainable.

Leave a Reply

Shopping cart0
There are no products in the cart!
Continue shopping
0