Codeigniter 4 – Setting Database with Example

Configuring the Database

- Open the app/Config/Database.php file and add 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,
];

Loading the Database

- Use the db_connect() function to load the database.

Example:

$db = db_connect();

Creating a Query

- Use the query() function to create a query.

Example:

$query = $db->query('SELECT * FROM my_table');

Executing a Query

- Use the execute() function to execute a query.

Example:

$db->query('INSERT INTO my_table (name, email) VALUES (?, ?)', ['John Doe', 'john@example.com']);

Retrieving Data

- Use the result() function to retrieve data from a query.

Example:

$result = $db->query('SELECT * FROM my_table')->result();

Retrieving a Single Row

- Use the row() function to retrieve a single row from a query.

Example:

$row = $db->query('SELECT * FROM my_table WHERE id = 1')->row();

Retrieving a Single Value

- Use the get() function to retrieve a single value from a query.

Example:

$value = $db->query('SELECT name FROM my_table WHERE id = 1')->get()->name;

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

Note: The Database class in CodeIgniter 4 provides a powerful and flexible way to interact with your database. It supports multiple database drivers, including MySQL, PostgreSQL, and SQLite.

One comment on “Codeigniter 4 – Setting Database with Example

  • Author's gravatar
    Felix Meyer 25th August 2024 , 9:29 pm

    Superb and well-thought-out content!

    Reply

Leave a Reply to Felix Meyer Cancel reply

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