Codeigniter 4 CRUD Operation with Mysql and Bootstrap Example

If you are searching how to create CRUD operations in Codeigniter 4 so you are in perfect place. Here we are going to share best example of Codeigniter 4 CRUD Operation with Mysql and Bootstrap step by step Example. We are going to use datatables for paginationa and search filter as well.

CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are basic data manipulation for database. Creating, editing, updating and deleting content on a website is what makes the site dynamic, That’s what we are going to be doing in this post.

Bootstrap: We’ve used the Bootstrap framework to make this CRUD application layout quickly and beautifully. Bootstrap is the most popular and powerful front-end framework for faster and easier responsive web development. Please, checkout the Bootstrap tutorial section to learn more about this framework.

Datatables: DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

Topics for Codeigniter 4 CRUD Steps

Follow the following steps to create a basic Codeigniter 4 CRUD Operation with Mysql and bootstrap;

  • Download Codeigniter 4 App
  • Enable Codeigniter Errors
  • Set Up Database
  • Create Product Model
  • Create Product Controller
  • Add Routes
  • Creating views to handle CRUD operations
  • Implementing Bootstrap 4 in Codeigniter
  • Implementing DataTables in Codeigniter
  • Adding data to MySQL
  • Retrieving data from MySQL
  • Update data from MySQL
  • Delete product from the database
  • Enable Codeigniter Errors.

Step 1: Download Codeigniter 4

First you need to manually download the Codeigniter 4 application to impetus the CRUD operations development process. Extract the zip file in your root where you want to add the project, If you are using xample let’s add in xamp\htdocs. If you are using ubuntu you can add this in /var/www or /var/www/html direcotry.

Download Here: download codeignier

Step 2: Enable Codeigniter Errors

Enable errors we need to set the display_errors to 1 instead of 0 in app/Config/Boot/development.php and app/Config/Boot/production.php file.

ini_set('display_errors', '1');

Make empty to index page “index.php” from Config\App.php file, just like below. Open the app\Confib\App.php file and update the public $indexPage = ‘ ‘, same as below.

app\Config\App.php

/**
 * --------------------------------------------------------------------------
 * Index File
 * --------------------------------------------------------------------------
 *
 * Typically this will be your index.php file, unless you've renamed it to
 * something else. If you are using mod_rewrite to remove the page set this
 * variable so that it is blank.
 *
 * @var string
 */
public $indexPage = ''; // make empty this

Step 3: Set Up Database

Open the database.php file and setup your database credentials like username, password, database_name etc.

app\Config\Database.php

/**
 * The default database connection.
 *
 * @var array
 */
public $default = [
	'DSN'      => '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'codeigniter_crud',
	'DBDriver' => 'MySQLi',
	'DBPrefix' => '',
	'pConnect' => false,
	'DBDebug'  => (ENVIRONMENT !== 'production'),
	'charset'  => 'utf8',
	'DBCollat' => 'utf8_general_ci',
	'swapPre'  => '',
	'encrypt'  => false,
	'compress' => false,
	'strictOn' => false,
	'failover' => [],
	'port'     => 3306,
];

Execute the following SQL query to create a table named products inside your MySQL database. We will use this table for all of our future operations.

CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255),
 `price` double(16, 2),
 `description` text,
 PRIMARY KEY (`id`)
)

Step 4: Create Product Model

Create new UserModel.php model file in the app/Models/ folder and update the below code on it. The model is used for defining the schema that is an archetype of table values.

app\Models\Product.php

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

class Product extends Model
{
    protected $table = 'products';
    protected $primaryKey = 'id';
    protected $useAutoIncreament = true;

    protected $allowedFields = ['name', 'price', 'description'];
}

Step 5: Create Product Controller

Here in this step we create a new controller named as ProductController.php. This controller handle all CRUD operations such as Create, Read, Update, Delete.

Now open the controller file and update the below code on it.

app\Controllers\ProductController.php

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

class ProductController extends Controller
{
    // show products list
    public function index() {
        $product = new Product();
        $data['products'] = $product->orderBy('id', 'DESC')->findAll();
        return view('products/index', $data);
    }

    // show create product form
    public function create() {
        return view('products/create');
    }

    // save product data
    public function store() {
        $product = new Product();

        $data = [
            'name' => $this->request->getVar('name'),
            'price'  => $this->request->getVar('price'),
            'description'  => $this->request->getVar('description'),
        ];

        $product->insert($data);

        return $this->response->redirect(site_url('/products'));
    }

    // show product
    public function edit($id) {
        $product = new Product();
        $data['product'] = $product->where('id', $id)->first();
        return view('products/edit', $data);
    }

    // update product data
    public function update() {
        $product = new Product();
        $id = $this->request->getVar('id');

        $data = [
            'name' => $this->request->getVar('name'),
            'price'  => $this->request->getVar('price'),
            'description'  => $this->request->getVar('description'),
        ];

        $product->update($id, $data);
        return $this->response->redirect(site_url('/products'));
    }

    // delete product
    public function delete($id) {
        $product = new Product();
        $data['product'] = $product->where('id', $id)->delete($id);
        return $this->response->redirect(site_url('/products'));
    }
}

Step 6: Add Routes

In this step we add routes to handle codeigniter CRUD operations. Open the Routes.php file and update the following routes.

app\Config\Routes.php

$routes->get('products', 'ProductController::index');
$routes->get('products/create', 'ProductController::create');
$routes->post('products/store', 'ProductController::store');
$routes->get('products/edit/(:num)', 'ProductController::edit/$1');
$routes->post('products/update', 'ProductController::update');
$routes->get('products/delete/(:num)', 'ProductController::delete/$1');

Step 7: Create Views Files

Now we need to create the view files for products listing, form create, edit for generating crud operation.

First we create a products folder which is add our product crud seprately, For showing data listing we create “index.php” file in our products folder just like below.

We will create a button on the top of the products list that can be used for creating new records in the products table.

Now open the recentaly created products\index.php file and update the follow code on it.

app\Views\products\index.php

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 CRUD App Example Tutorial - codingdriver.com</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>

<div class="container mt-4">
    <div class="d-flex justify-content-end">
        <a href="<?php echo site_url('/products/create') ?>" class="btn btn-success mb-2">Add Product</a>
	</div>
    <?php
     if (isset($_SESSION['msg'])) {
        echo $_SESSION['msg'];
      }
     ?>
  <div class="mt-3">
     <table class="table table-bordered" id="products-list">
       <thead>
          <tr>
             <th></th>
             <th>Name</th>
             <th>Price</th>
             <th>Description</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <?php if($products): ?>
          <?php foreach($products as $key => $product): ?>
          <tr>
             <td><?php echo $key+1; ?></td>
             <td><?php echo $product['name']; ?></td>
             <td><?php echo $product['price']; ?></td>
             <td><?php echo $product['description']; ?></td>
             <td>
              <a href="<?php echo base_url('products/edit/'.$product['id']);?>" class="btn btn-primary btn-sm">Edit</a>
              <a href="<?php echo base_url('products/delete/'.$product['id']);?>" class="btn btn-danger btn-sm">Delete</a>
              </td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
     </table>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script>
    $(document).ready( function () {
      $('#products-list').DataTable();
    });
</script>
</body>
</html>

Once products table is populated with some records the landing page i.e. the CRUD data grid may look something like the picture shown below:

Let’s create a file named “create.php” inside “procuts” folder and put the following code inside it. It will generate a web form that can be used to insert records in the products table.

app\Views\products\create.php

<!DOCTYPE html>
<html>

<head>
  <title>Codeigniter 4 Crud with Validation Demo</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <style>
    .container {
      max-width: 500px;
    }

    .error {
      display: block;
      padding-top: 5px;
      font-size: 14px;
      color: red;
    }
  </style>
</head>

<body>
  <div class="container mt-5">
    <form method="post" id="createProduct" action="<?= site_url('/products/store') ?>">
      <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" class="form-control">
      </div>

      <div class="form-group">
        <label>Price</label>
        <input type="number" name="price" class="form-control">
      </div>

      <div class="form-group">
        <label>Description</label>
        <textarea type="text" name="description" class="form-control"></textarea>
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Save</button>
      </div>
    </form>
  </div>

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
  <script>
    if ($("#createProduct").length > 0) {
      $("#createProduct").validate({
        rules: {
          name: {
            required: true,
          },
          price: {
            required: true,
          },
          description: {
            required: true,
          },
        },
        messages: {
          name: {
            required: "Name is required.",
          },
          price: {
            required: "Price is required.",
          },
          description: {
            required: "Description is required.",
          },
        },
      })
    }
  </script>
</body>

</html>

Let’s create a file named “products\update.php” and put the following code inside it. It will update the existing records in the products table based the id attribute of the product.

app\Views\products\edit.php

<!DOCTYPE html>
<html>

<head>
  <title>Codeigniter 4 Crud with Validation Demo</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <style>
    .container {
      max-width: 500px;
    }

    .error {
      display: block;
      padding-top: 5px;
      font-size: 14px;
      color: red;
    }
  </style>
</head>

<body>
  <div class="container mt-5">
    <form method="post" id="createProduct" action="<?= site_url('/products/update') ?>">
    <input type="hidden" name="id" value="<?php echo $product['id']; ?>">
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" class="form-control" value="<?php echo $product['name']; ?>">
        </div>
        <div class="form-group">
            <label>Price</label>
            <input type="number" name="price" class="form-control" value="<?php echo $product['price']; ?>">
        </div>
        <div class="form-group">
            <label>Description</label>
            <textarea type="text" name="description" class="form-control"><?php echo $product['description']; ?></textarea>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-primary btn-block">Save</button>
        </div>
    </form>
  </div>

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
  <script>
    if ($("#createProduct").length > 0) {
      $("#createProduct").validate({
        rules: {
          name: {
            required: true,
          },
          price: {
            required: true,
          },
          description: {
            required: true,
          },
        },
        messages: {
          name: {
            required: "Name is required.",
          },
          price: {
            required: "Price is required.",
          },
          description: {
            required: "Description is required.",
          },
        },
      })
    }
  </script>
</body>

</html>

Step 8: Start the Application

Now running the codeigniter crud operation we run the following command.

php spark serve

After running the application just paste the below code on your browser for testing the crud example.

http://localhost:8080/products

Conclusion: After a long journey finally we’ve finished our Codeigniter 4 CRUD operation with MySQL and Bootstrap. We recommend you to check out PHP Crud with MySQL example tutorial section from the beginning, if you haven’t already covered, for a better understanding of each and every part of this tutorial. Hope you enjoy with this crud operation with codeigniter 4, please share your friends in social networks …

1 thought on “Codeigniter 4 CRUD Operation with Mysql and Bootstrap Example”

Leave a Comment