CRUD CodeIgniter 4 Tutorial with Bootstrap Modal (Complete Guide)

CRUD CodeIgniter 4 Tutorial with Bootstrap Modal (Complete Guide)

In this tutorial you will learn about:

How to create a CRUD application using CodeIgniter 4 with Bootstrap modal.

If you are beginner in CodeIgniter 4, I suggest you first to learn "Complete tutorial CodeIgniter 4 for beginners".

If you feel familiar with Codeigniter 4, then you are in the right place.

In this tutorial, you will also learn how to use a join query from 2 tables using the CodeIgniter 4 query builder.

Step-by-Step

Let get started.

 

Step #1. Preparation

To create a CRUD with CodeIgniter and Bootstrap Modal, this is what you need to prepare:

1. CodeIgniter 4

2. JQuery

3. Bootstrap

In this tutorial I use CodeIgniter v4.x, JQuery v3.4.x, Bootstrap v4.4.x.

 

Step #2. Creating a Database and Tables

Create a new database named "pos_db".

If you create a database with the same name that's even better.

To create a "pos_db" database in MySQL, it can be done by executing the following query:

CREATE DATABASE pos_db;

The SQL command above, will create a database with the name "pos_db" in MySQL.

Next, create a new table in the "pos_db" database.

In this tutorial, 2 tables are needed, namely: "category" and "product".

To create a "category" table you can do this by executing the following query:

CREATE TABLE category(
category_id INT PRIMARY KEY AUTO_INCREMENT,
category_name VARCHAR(50)
)ENGINE=INNODB; 

The SQL command above, will create a table called "category" with fields: category_id and category_name.

Furthermore, to create a "product" table it can be done by executing the following query:

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

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

 

Step #3. Insert data ke table Category dan Product

This is important!

Insert some data into the "category" table and the "product" table as sample data.

Insert some data into the "category" table by executing the following query:

INSERT INTO category(category_name) 
VALUES ('Books'),('Electronics'),('Fashions');

The query above will insert 3 records of data into the "category" table.

Next, insert some data into the "product" table by executing the following query:

INSERT INTO product(product_name,product_price,product_category_id) 
VALUES ('The 4 Hour Workweek','76000','1'),('CodeIgniter Cheat Sheet','50000','1');

The above query will insert 2 records of data into the "product" table.

 

Step #4. Installing CodeIgniter 4

To install Codeigniter 4, you can do it in 2 ways, namely: manual installation and installation via composer.

In this tutorial, I will use manual installation.

Manual installation, exactly the same as installing CodeIgniter 3.

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

https://codeigniter.com

If you are using WAMPSERVER, extract it in the folder:

C:/wamp64/www

If you are using XAMPP, extract it in the folder:

C:/xampp/htdocs

In this tutorial, I am using XAMPP.

Then rename it to "pos" as shown below:

project name

Then, open the project "pos" folder using a code editor.                     

In this tutorial, I use "Visual Studio Code", you can use Sublime Text, PHP Storm, or any other code editor.

If you also use Visual Studio Code, you will love this tutorial.

To make sure the CodeIgniter 4 installation is successful, type the following command in the Terminal / Command Prompt:

php spark serve

Like the following picture:

php spark serve

If you are using Visual Studio Code, you can type the above commands directly in the terminal in Visual Studio Code.

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

Next, extract the “Bootstrap” file that has been prepared in advance into the "pos/public" folder as shown below:

After that, open the "public/js" folder, then create a file called "jquery.min.js", then open the file using a code editor.

Then visit the following URL:

https://code.jquery.com/jquery-3.4.1.min.js

Then, select all the codes (Ctrl + A) and copy (Ctrl + C) then paste (Ctrl + V) in the file "jquery.min.js" and save (Ctrl + S).

 

Step #5. Connect to Database

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 change it to be like the following:

    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,
    ];

Furthermore, this is important!

So that you have a good interface for handling errors, find the env file in the root of the project, then rename it to .env and open it.

Then find the following code:

# CI_ENVIRONMENT = production

Then change it to be like the following:

CI_ENVIRONMENT = development

That means you are in development mode, this mode will help you to easily track errors as you build your project.

After your project is finished, do not forget to put it back into production mode!

 

Step #6. Creating a Model file

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
{
    
    public function getCategory()
    {
        $builder = $this->db->table('category');
        return $builder->get();
    }

    public function getProduct()
    {
        $builder = $this->db->table('product');
        $builder->select('*');
        $builder->join('category', 'category_id = product_category_id','left');
        return $builder->get();
    }

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

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

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

  
}

 

Step #7. Creating a Controller file

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()->getResult();
        $data['category'] = $model->getCategory()->getResult();
        echo view('product_view', $data);
    }

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

    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'),
            'product_category_id' => $this->request->getPost('product_category'),
        );
        $model->updateProduct($data, $id);
        return redirect()->to('/product');
    }

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

}

 

Step #8. Creating a View file

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 Lists</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
    <h3>Product Lists</h3>
    <button type="button" class="btn btn-success mb-2" data-toggle="modal" data-target="#addModal">Add New</button>

        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Product Name</th>
                    <th>Price</th>
                    <th>Category</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($product as $row):?>
                <tr>
                    <td><?= $row->product_name;?></td>
                    <td><?= $row->product_price;?></td>
                    <td><?= $row->category_name;?></td>
                    <td>
                        <a href="#" class="btn btn-info btn-sm btn-edit" data-id="<?= $row->product_id;?>" data-name="<?= $row->product_name;?>" data-price="<?= $row->product_price;?>" data-category_id="<?= $row->product_category_id;?>">Edit</a>
                        <a href="#" class="btn btn-danger btn-sm btn-delete" data-id="<?= $row->product_id;?>">Delete</a>
                    </td>
                </tr>
            <?php endforeach;?>
            </tbody>
        </table>

    </div>
    
    <!-- Modal Add Product-->
    <form action="/product/save" method="post">
        <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Add New Product</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
            
                <div class="form-group">
                    <label>Product Name</label>
                    <input type="text" class="form-control" name="product_name" placeholder="Product Name">
                </div>
                
                <div class="form-group">
                    <label>Price</label>
                    <input type="text" class="form-control" name="product_price" placeholder="Product Price">
                </div>

                <div class="form-group">
                    <label>Category</label>
                    <select name="product_category" class="form-control">
                        <option value="">-Select-</option>
                        <?php foreach($category as $row):?>
                        <option value="<?= $row->category_id;?>"><?= $row->category_name;?></option>
                        <?php endforeach;?>
                    </select>
                </div>
            
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save</button>
            </div>
            </div>
        </div>
        </div>
    </form>
    <!-- End Modal Add Product-->

    <!-- Modal Edit Product-->
    <form action="/product/update" method="post">
        <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Edit Product</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
            
                <div class="form-group">
                    <label>Product Name</label>
                    <input type="text" class="form-control product_name" name="product_name" placeholder="Product Name">
                </div>
                
                <div class="form-group">
                    <label>Price</label>
                    <input type="text" class="form-control product_price" name="product_price" placeholder="Product Price">
                </div>

                <div class="form-group">
                    <label>Category</label>
                    <select name="product_category" class="form-control product_category">
                        <option value="">-Select-</option>
                        <?php foreach($category as $row):?>
                        <option value="<?= $row->category_id;?>"><?= $row->category_name;?></option>
                        <?php endforeach;?>
                    </select>
                </div>
            
            </div>
            <div class="modal-footer">
                <input type="hidden" name="product_id" class="product_id">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Update</button>
            </div>
            </div>
        </div>
        </div>
    </form>
    <!-- End Modal Edit Product-->

    <!-- Modal Delete Product-->
    <form action="/product/delete" method="post">
        <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Delete Product</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
            
               <h4>Are you sure want to delete this product?</h4>
            
            </div>
            <div class="modal-footer">
                <input type="hidden" name="product_id" class="productID">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>
                <button type="submit" class="btn btn-primary">Yes</button>
            </div>
            </div>
        </div>
        </div>
    </form>
    <!-- End Modal Delete Product-->

<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function(){

        // get Edit Product
        $('.btn-edit').on('click',function(){
            // get data from button edit
            const id = $(this).data('id');
            const name = $(this).data('name');
            const price = $(this).data('price');
            const category = $(this).data('category_id');
            // Set data to Form Edit
            $('.product_id').val(id);
            $('.product_name').val(name);
            $('.product_price').val(price);
            $('.product_category').val(category).trigger('change');
            // Call Modal Edit
            $('#editModal').modal('show');
        });

        // get Delete Product
        $('.btn-delete').on('click',function(){
            // get data from button edit
            const id = $(this).data('id');
            // Set data to Form Edit
            $('.productID').val(id);
            // Call Modal Edit
            $('#deleteModal').modal('show');
        });
        
    });
</script>
</body>
</html>

 

Step #9. Testing

To ensure that the CRUD application that is built runs well, test it by visiting the following URL:

http://localhost:8080/product

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

product list

1. Add New Product

Click the "Add New" button to add a new product, then a form will appear as follows:

add new from

Enter the product name, price, and select category, then click the "Save" button.

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

product list

2. Update Product

Click the "Edit" button to update the product, then a form will appear as follows:

edit form

Edit the data according to what you want, then click the "Update" button to update the data.

3. Delete Product

Click the "Delete" button on the product list to delete the product, then a confirmation will appear as follows:

delete confirm

Then click the "Yes" button to delete the data.

 

Conclusion

The discussion this time is how to create a simple Create-Read-Update-Delete (CRUD) application using CodeIgniter 4 and Bootstrap Modal.

Not only that, you have also learned to use a join query using the query builder in CodeIgniter 4.

This is a great foundation for you to build more complex applications with CodeIgniter 4 and Bootstrap.

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

Download Source Code

Share:



Sponsorship:


Recommended for you


Comments (0)

Leave a Comment