The Complete CodeIgniter 4 Tutorial For Beginners

The Complete CodeIgniter 4 Tutorial For Beginners

In this tutorial you will learn about:

1. Introduction to CodeIgniter 4

2. CodeIgniter 4 Installation (Manual and Composer)

3. Creating simple applications using CodeIgniter 4

4. Connecting CodeIgniter 4 to database

5. Fetch data from database (READ)

6. Insert data to database (CREATE)

7. Update data to database (UPDATE)

8. Delete data to database (DELETE)

(Step-by-Step)

Let's get started.

 

#1. Introduction to CodeIgniter 4

Codeigniter is a PHP framework for building web-based applications.

Codeigniter itself provides 3 options: CodeIgniter 2, CodeIgniter 3, and CodeIgniter 4.

Codeigniter 2 is the legacy version of CodeIgniter, CodeIgniter 3 is the latest version of CodeIgniter, while CodeIgniter 4 is the future version of CodeIgniter.

CodeIgniter 2 and CodeIgniter 3 do not have a significant difference, it's just that there are some features added in version 3 and support for PHP version 5.6+.

While CodeIgniter 4, is very different from CodeIgniter 2 and CodeIgniter 3.

Due to the rapid development of technology, CodeIgniter was forced to make major changes.

CodeIgniter 4 supports PHP version 7.2+, if your web server doesn't support PHP 7.2+, I recommend upgrading your PHP version.

In addition, CodeIgniter 4 also cannot run if your web server does not have intl extensionphp-jsonphp-mbstringphp-mysqlnd, and php-xml enabled.

You can check it on phpinfo, if one of the extensions is not active (disabled), please activate it in the php.ini file.

If you are using XAMPP, the php.ini file is in the:

C:/xampp/php

Meanwhile, if you use WampServer, the php.ini file is located in the folder:

C:/wamp64/bin/php/php7.4.3

In this tutorial I use XAMPP.

In addition, CodeIgniter 4 does not have an "index.php" file in the project root, and the "index.php" file is moved to the "public" folder for security reasons.

CodeIgniter 4 makes it easy for web developers to write shorter program code and makes it easy to track errors through the "development" mode.

Not only that, CodeIgniter 4 also makes it easier for web developers to create RESTful API, which are required for additional libraries to create RESTful API in Codeigniter 3.

That's what makes CodeIgniter 4 very interesting.

 

#2. CodeIgniter 4 Installation

To install CodeIgniter 4 can be done in 2 ways, namely: manual installation and installation via composer.

In this tutorial I will show you both way.

 

2.1. Manual Installation

Manual CodeIgniter 4 installation, exactly the same as installing CodeIgniter 3.

Download the CodeIgniter 4 file at the following link, then extract it on your web server.

http://codeigniter.com

If using WAMPSERVER, extract it in the folder:

C:/wamp64/www

If using XAMPP, extract it in the folder:

C:/xampp/htdocs

 

2.2. Installation via Composer

CodeIgniter 4 allows you to install via composer.

Composer is a Dependency Manager for PHP, as well as NPM in node.js.

To be able to install CodeIgniter 4 using Composer, you must first install Composer on your computer.

If you are using windows, you can download Composer-Setup.exe at the following link:

https://getcomposer.org/download/

If you are using Linux / Unix / mac OS, check the following link for more info:

https://getcomposer.org/doc/00-intro.md

To make sure that Composer is installed properly on your computer, please open Terminal / Command Prompt and type the following command:

composer –v

If Composer is installed properly, it will look like the following image:

composer

After that, check your PHP version by using the command:

php –v

This is important, if your php version is below PHP 7.2+ then you can't install CodeIgniter 4 via composer.

php version

I am using PHP 7.3.7, so I can install CodeIgniter 4 via composer.

To install CodeIgniter 4 via composer, you can do it by typing the following command in Terminal / Command Prompt:

composer create-project codeigniter4/appstarter ci-project --no-dev

You have to install CodeIgniter 4 in the root of your web server.

Here I am using XAMPP, so the root of my web server is:

C:/xampp/htdocs

You can use the change directory (cd) command at the following terminal / command prompt to switch to the “xampp/htdocs” folder:

cd ../../xampp/htdocs

Like the following picture:

change directory

After you are in the "xampp/htdocs" folder then you can install CodeIgniter 4 through composer.

Like the following picture:

installation

The above command will create a "ci-project" folder in "xampp/htdocs".

Then go to the "ci-project" folder with the following command:

change directory project

After that, type the following command:

composer update --no-dev

Like the following picture:

update composer

Done.

Installing CodeIgniter 4 via composer, might seem complicated if you are not used to it.

However, by making use of composer, you can easily install the dependency packages you need and you can also update all the dependencies easily.

To ensure a successful installation, type the following command at the Terminal/Command Prompt:

php spark serve

Like the following picture:

php spark serve

Then open your browser and visit the following url:

http://localhost:8080

If the installation is successful, it will look like the following image:

welcome codeigniter

 

#3. Creating the first application using CodeIgniter 4

Similar to the CodeIgniter 3 concept, CodeIgniter 4 also adopts the MVC (Model-View-Controller) pattern design.

In this step, you will learn how to display views with CodeIgniter 4 and you can see how it is different from CodeIgniter 3.

3.1. Create a controller named “Hello.php” in the “app/Controllers” folder as shown below:

hello controller

Then type the following code:

<?php namespace App\Controllers;
use CodeIgniter\Controller;

class Hello extends Controller
{
    public function index()
    {
        $data['title'] = "Hello World from Codeigniter 4";
        echo view('hello_view', $data);
    }

}

3.2. After that, create a view "hello_view.php" in the "app/Views" folder as shown below:

hello view

Then type the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><?= $title; ?></title>
</head>
<body>
    <h2><?= $title; ?></h2>
</body>
</html>

Then run your project using the following command at the terminal / command prompt:

php spark serve

Then open a browser and visit the following URL:

http://localhost:8080/hello

If it goes well, it will look like the following image:

hello codeigniter

 

#4. Create a connection to the database

To make a connection to the database, of course you must have a database in advance.

Here I use MySQL as a DBMS (Database Management System).

If you are using MySQL, you will love this tutorial.

Create a database on MySQL by executing the following query:

CREATE DATABASE pos_db;

The above query will create a database called “pos_db”.

Next, create a table in the “pos_db” database by executing the following query:

CREATE TABLE product(
product_id INT PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(100),
product_price INT
);

The query above will create a table called "product" with fields: product_id, product_name, and product_price.

To make a connection to the database on CodeIgniter 4, there are two ways: using the Database.php file in the “app/Config” folder or using an env file located at the project root.

You may choose one of the two methods.

Method 1: Using the “Database.php” file contained in the "app/Config" folder.

Open the “Database.php” file located in the “app/Config” folder, then find the following code:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => '',
        'password' => '',
        '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,
];

Then set to be like this:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'pos_db',
        '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,
];

This method is similar to making a connection to a database in Codeigniter 3.

Method 2: Using the “env” file contained in the project root.

In addition to the method above, there are other ways provided by CodeIgniter 4 to make connections to the database, namely with the “env” file contained in the project root.

Find the “env” file in the project root, then rename it to “.env” and then open the file.

Then find the following code:

# database.default.hostname = localhost
# database.default.database = ci4
# database.default.username = root
# database.default.password = root
# database.default.DBDriver = MySQLi

Change it to be like the following:

database.default.hostname = localhost
database.default.database = pos_db
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi

Done.

In this tutorial, I use this method to make a connection to the database.

 

#5. Fetch data from database (READ)

Before displaying data from the database to view using CodeIgniter 4, you must first have the data in the "product" table found in the "pos_db" database.

You can execute the following query to insert data into the "product" table:

INSERT INTO product(product_name, product_price) 
VALUES ('Product 1', 20000),('Product 2', 30000);

The query above will insert two data records in the "product" table contained in the database.

5.1. Create a model file named “Product_model.php” in the “app/Models” folder, then type the following code:

<?php namespace App\Models;
use CodeIgniter\Model;

class Product_model extends Model
{
    protected $table = 'product';
    
    public function getProduct($id = false)
    {
        if($id === false){
            return $this->findAll();
        }else{
            return $this->getWhere(['product_id' => $id]);
        }   
    }

}

In the model "Product_model.php" above, there is one function, namely:

function getProduct($id = false)

Where the function carries the $id parameter which is set to false by default.

In the getProduct function there are two conditions:

If $id equals false, then return the value of all data contained in the "product" table with code:

return $this->findAll();

In the code above, codeigniter immediately knows the table used, namely the "product" table which has been set through the following code:

protected $table = 'product';

In addition, if $id has a value, then restore the data based on the value $id with the following code:

return $this->getWhere(['product_id' => $id]);

This is a great idea if you need product data based on a certain id, you don't need to create another function anymore.

Cool right?

5.2. Create a controller file named "Product.php" in the "app/Controllers" folder, then type the following code:

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\Product_model;

class Product extends Controller
{
    public function index()
    {
        $model = new Product_model();
        $data['product'] = $model->getProduct();
        echo view('product_view',$data);
    }
}

On the "Product.php" Controller, we call the "Product_model.php" model using the following code:

use App\Models\Product_model;

And in the "Product.php" controller there is one function, namely the index() function.

In the function index, we create an instance of the “Product_model.php” model with the following code:

$model = new Product_model();

So that, you can call all the functions contained in the model "Product_model.php" from the index function of the Controller.

Furthermore, there is the following code:

$data['product'] = $model->getProduct();

The code is used to call the getProduct() function contained in the model "Product_model.php" and store it in the variable $data['product'].

Next, the data is sent to the view "product_view" using the following code:

echo view('product_view',$data);

This code functions to call a view "product_view" which we will create, as well as carry the data contained in the $data variable.

5.3. Create a view file named "product_view.php" in the "app/Views" folder, then type the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Product List</title>
</head>
<body> 
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($product as $row):?>
            <tr>
                <td><?= $row['product_name'];?></td>
                <td><?= $row['product_price'];?></td>
            </tr>
        <?php endforeach;?>
        </tbody>
    </table>
</body>
</html>

Then run your project with the following command in Terminal/Command Prompt:

php spark serve

Like the following picture:

php spark serve

Then open your browser and visit the following URL:

http://localhost:8080/product

If it goes well, it will look like the following image:

product list

 

#6. Insert data to database (CREATE)

6.1. Create one more view file named "add_product_view.php" in the "app/Views" folder, then type the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Add New Product</title>
</head>
<body>
    <form action="/product/save" method="post">
        <input type="text" name="product_name">
        <input type="text" name="product_price">
        <button type="submit">Save</button>
    </form>
</body>
</html>

The code above functions to create a form with the “post” method which consists of two text inputs, namely: product_name, and product_price.

6.2. Open the controller file "Product.php" in the "app/Controllers" folder then change it to be like this:

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\Product_model;

class Product extends Controller
{
    public function index()
    {
        $model = new Product_model();
        $data['product'] = $model->getProduct();
        echo view('product_view',$data);
    }

    public function add_new()
    {
        echo view('add_product_view');
    }

    public function save()
    {
        $model = new Product_model();
        $data = array(
            'product_name'  => $this->request->getPost('product_name'),
            'product_price' => $this->request->getPost('product_price'),
        );
        $model->saveProduct($data);
        return redirect()->to('/product');
    }
}

In the Controller "Product.php" there are two additional functions, namely: function add_new() and function save().

The function add_new() to display the product input form, while the function save() to save data to the database that is sent to the model.

6.3. Open the model file “Product_model.php” in the “app/Models” folder then change it to the following:

<?php namespace App\Models;
use CodeIgniter\Model;

class Product_model extends Model
{
    protected $table = 'product';
    
    public function getProduct($id = false)
    {
        if($id === false){
            return $this->findAll();
        }else{
            return $this->getWhere(['product_id' => $id]);
        }   
    }

    public function saveProduct($data)
    {
        $query = $this->db->table($this->table)->insert($data);
        return $query;
    }
}

In the "Product_model.php" model there is one additional function, namely: the function  saveProduct() which functions to save data to the database.

Then go back to the browser, and visit the following URL:

http://localhost:8080/product/add_new

If it goes well, it will look like the following form:

form add new

Then enter the product name and price, then click the save button.

Here I enter the product name = "Product 3" and price = "4000".

If it goes well, it will look like the following image:

 

#7. Update data to database (UDPATE)

7.1. Open the view file "product_view.php" in the "app/Views" folder then change it to be like the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Product List</title>
</head>
<body>
    <a href="/product/add_new">Add New</a>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($product as $row):?>
            <tr>
                <td><?= $row['product_name'];?></td>
                <td><?= $row['product_price'];?></td>
                <td><a href="/product/edit/<?= $row['product_id'];?>">Edit</a></td>
            </tr>
        <?php endforeach;?>
        </tbody>
    </table>
</body>
</html>

7.2. Open the Controller file "Product.php" in the "app/Controllers" folder then change it to be like this:

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\Product_model;

class Product extends Controller
{
    public function index()
    {
        $model = new Product_model();
        $data['product'] = $model->getProduct();
        echo view('product_view',$data);
    }

    public function add_new()
    {
        echo view('add_product_view');
    }

    public function save()
    {
        $model = new Product_model();
        $data = array(
            'product_name'  => $this->request->getPost('product_name'),
            'product_price' => $this->request->getPost('product_price'),
        );
        $model->saveProduct($data);
        return redirect()->to('/product');
    }

    public function edit($id)
    {
        $model = new Product_model();
        $data['product'] = $model->getProduct($id)->getRow();
        echo view('edit_product_view', $data);
    }

    public function update()
    {
        $model = new Product_model();
        $id = $this->request->getPost('product_id');
        $data = array(
            'product_name'  => $this->request->getPost('product_name'),
            'product_price' => $this->request->getPost('product_price'),
        );
        $model->updateProduct($data, $id);
        return redirect()->to('/product');
    }
}

In the Controller "Product.php" there are 2 additional functions, namely: function edit() and function update().

The function edit() to displays data on the form, while the function update() to updates the data to the database through the model.

7.3. Create one more view file named "edit_product_view.php" in the "app/Views" folder then type the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Edit Product</title>
</head>
<body>
    <form action="/product/update" method="post">
        <input type="text" name="product_name" value="<?= $product->product_name;?>">
        <input type="text" name="product_price" value="<?= $product->product_price;?>">
        <input type="hidden" name="product_id" value="<?= $product->product_id;?>">
        <button type="submit">Update</button>
    </form>
</body>
</html>

7.4. Open the Model file "Product_model.php" in the "app/Models" folder then change it to be like the following:

<?php namespace App\Models;
use CodeIgniter\Model;

class Product_model extends Model
{
    protected $table = 'product';
    
    public function getProduct($id = false)
    {
        if($id === false){
            return $this->findAll();
        }else{
            return $this->getWhere(['product_id' => $id]);
        }   
    }

    public function saveProduct($data)
    {
        $query = $this->db->table($this->table)->insert($data);
        return $query;
    }

    public function updateProduct($data, $id)
    {
        $query = $this->db->table($this->table)->update($data, array('product_id' => $id));
        return $query;
    }
}

In the "Product_model.php" model there is one additional function, namely: the function  updateProduct() which functions to update data to the database..

Then go back to the browser, and visit the following URL:

http://localhost:8080/product

If it goes well, it will look like the following form:

Click on one of the “Edit” links, then the edit form will appear as follows:

Change the data you want to edit, then click the "Update" button.

If it goes well, it will look like the following image:

 

#8. Delete data to database (DELETE)

8.1. Open the view file "product_view.php" in the "app/Views" folder then change it to be like the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Product List</title>
</head>
<body>
    <a href="/product/add_new">Add New</a>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Price</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach($product as $row):?>
            <tr>
                <td><?= $row['product_name'];?></td>
                <td><?= $row['product_price'];?></td>
                <td>
                    <a href="/product/edit/<?= $row['product_id'];?>">Edit</a>
                    <a href="/product/delete/<?= $row['product_id'];?>">Delete</a>
                </td>
            </tr>
        <?php endforeach;?>
        </tbody>
    </table>
</body>
</html>

8.2. Open the Controller file "Product.php" in the "app/Controllers" folder then change it to be like this:

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\Product_model;

class Product extends Controller
{
    public function index()
    {
        $model = new Product_model();
        $data['product'] = $model->getProduct();
        echo view('product_view',$data);
    }

    public function add_new()
    {
        echo view('add_product_view');
    }

    public function save()
    {
        $model = new Product_model();
        $data = array(
            'product_name'  => $this->request->getPost('product_name'),
            'product_price' => $this->request->getPost('product_price'),
        );
        $model->saveProduct($data);
        return redirect()->to('/product');
    }

    public function edit($id)
    {
        $model = new Product_model();
        $data['product'] = $model->getProduct($id)->getRow();
        echo view('edit_product_view', $data);
    }

    public function update()
    {
        $model = new Product_model();
        $id = $this->request->getPost('product_id');
        $data = array(
            'product_name'  => $this->request->getPost('product_name'),
            'product_price' => $this->request->getPost('product_price'),
        );
        $model->updateProduct($data, $id);
        return redirect()->to('/product');
    }

    public function delete($id)
    {
        $model = new Product_model();
        $model->deleteProduct($id);
        return redirect()->to('/product');
    }
}

In the Controller "Product.php" there is an additional function, namely: function delete() which functions to delete data to the database through the model.

8.3. Open the Model file "Product_model.php" in the "app/Models" folder then change it to be like the following:

<?php namespace App\Models;
use CodeIgniter\Model;

class Product_model extends Model
{
    protected $table = 'product';
    
    public function getProduct($id = false)
    {
        if($id === false){
            return $this->findAll();
        }else{
            return $this->getWhere(['product_id' => $id]);
        }   
    }

    public function saveProduct($data)
    {
        $query = $this->db->table($this->table)->insert($data);
        return $query;
    }

    public function updateProduct($data, $id)
    {
        $query = $this->db->table($this->table)->update($data, array('product_id' => $id));
        return $query;
    }

    public function deleteProduct($id)
    {
        $query = $this->db->table($this->table)->delete(array('product_id' => $id));
        return $query;
    } 
}

In the "Product_model.php" model there is one additional function, namely: the function deleteProduct() which functions to delete data to the database.

Then go back to the browser, and visit the following URL:

http://localhost:8080/product

If it goes well, it will look like the following form:

Then click one of the “Delete” links to delete the data to the database.

 

Conclusion:

The discussion this time is about the complete CodeIgniter 4 tutorial for beginners.

Starting from the introduction of CodeIgniter 4, installing CodeIgniter 4, creating simple applications using CodeIgniter 4, connecting CodeIgniter 4 with the database.

Not only that, you have also learned how to make a simple CRUD (Create-Read-Update-Delete) application using CodeIgniter 4.

So what are you waiting for. Let's Coding!

Download Source Code

Share:



Sponsorship:


Recommended for you


Comments (3)

Tricia, 24 February 2021 00:28 -

What's up friends, nice article and pleasant arguments commented here, I am truly enjoying by these.

Uldis, 21 May 2021 01:45 -

Excellent tutorial for beginners. Thank You !

HamidReza, 11 June 2021 15:19 -

thank you very very very much!

Leave a Comment