PHP CodeIgniter 4 - Basic CRUD operation with MySQL Database with example

PHP CodeIgniter 4 - Basic CRUD operation with MySQL Database with example

PHP CodeIgniter 4 - Basic CRUD operation with MySQL Database with example

In this PHP CodeIgniter 4 tutorial, I will let you know the basic CRUD functionality with MySQL Database.

CRUD is an acronym for Create, Read, Update, and Delete database records.

This is one of the most common task in the development to create something in the table, update some information, read data from table and delete information.

In this example, I will use bootstrap library to list posts and render the forms for create and edit post.

Download & Configure Codeigniter 4 Application

In the first step, I will download fresh version of Codeigniter 4, Go to this link https://codeigniter.com/download and download Codeigniter 4 and unzip this application in your working directory and change the application name to crud.

Run the composer command to download the dependencies.

Now I will configure the base url in app/Config/App.php.

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/crud/public';
Configure Database and Create Table

In this step, I will create database first called crud and create a new table posts in this crud database.

You can run the below SQL query to create posts table in your database.

CREATE TABLE `posts` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) NOT NULL,
 `description` text NOT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` timestamp NULL DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Now I need to update the database credential in the database config file.

I need to go app/Config/Database.php and open the Database.php file in an editor.

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

In this step, I will create a model file PostModel.php to communicate with the posts table in the app/Models/ directory.

<?php 
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class PostModel extends Model
{
    protected $table = 'posts';
 
    protected $allowedFields = ['title', 'description'];
}
Create Controller

In this step, I will create a controller file Posts.php inside the app/Controllers directory.

In this controller file, I will create some method to perform crud operation.

  • index() - this method is used to list all the posts.
  • create() - this method is used to render the create form.
  • store() - this method is used to insert new post into the table.
  • edit() - this method is used to render the edit form.
  • update() - this method is used to update the post informaton.
  • delete() - this method is used to delete the post informaton from database table.
<?php namespace App\Controllers;
 
use CodeIgniter\Controller;
use App\Models\PostModel;
 
class Posts extends Controller
{
 
    public function index()
    {    
        
        $model = new PostModel();
 
        $data['posts'] = $model->orderBy('id', 'DESC')->findAll();
        
        return view('posts', $data);
    }    
 
    public function create()
    {    
        return view('create-post');
    }
 
    public function store()
    {  
 
        helper(['form', 'url']);
         
        $model = new PostModel();
 
        $data = [
 
            'title' => $this->request->getVar('title'),
            'description'  => $this->request->getVar('description'),
            ];
 
        $save = $model->insert($data);
 
        return redirect()->to( base_url('posts') );
    }
 
    public function edit($id = null)
    {
    
     $model = new PostModel();
     
     $data['post'] = $model->find($id);
      
     return view('edit-post', $data);
    }
 
    public function update()
    {  
 
        helper(['form', 'url']);
         
        $model = new PostModel();
 
        $id = $this->request->getVar('id');
        
        $data = [
 
            'title' => $this->request->getVar('title'),
            'description'  => $this->request->getVar('description'),
            ];
 
        $save = $model->update($id,$data);
 
        return redirect()->to( base_url('posts') );
    }
 
    public function delete($id = null)
    {
 
     $model = new PostModel();
 
     $data['post'] = $model->where('id', $id)->delete();
      
     return redirect()->to( base_url('posts') );
    }
}
Create Views

In this step, I will create respective html files.

  • posts.php
  • create-post.php
  • edit-post.php
posts.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 Tutorial -  posts List Example - Expertphp.in</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">

</head>
<body>
 
<div class="container mt-5">
    <a href="<?php echo base_url('posts/create') ?>" class="btn btn-sm btn-success">Create</a>
   
  <div class="row mt-3">
     <table class="table table-bordered" id="posts">
       <thead>
          <tr>
             <th>Id</th>
             <th>Title</th>
             <th>Description</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <?php if($posts): ?>
          <?php foreach($posts as $post): ?>
          <tr>
             <td><?php echo $post['id']; ?></td>
             <td><?php echo $post['title']; ?></td>
             <td><?php echo $post['description']; ?></td>
             <td>
              <a href="<?php echo base_url('posts/edit/'.$post['id']);?>" class="btn btn-sm btn-success">Edit</a>
              <a href="<?php echo base_url('posts/delete/'.$post['id']);?>" class="btn btn-sm btn-danger">Delete</a>
              </td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
     </table>
  </div>
</div>
 
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
 
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js" type="text/javascript"></script>
 
<script>
    $(document).ready( function () {
      $('#posts').DataTable();
  } );
</script>
</body>
</html>
create-post.php
<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 CRUD Tutorial - Post Form With Validation Example</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
 
</head>
<body>
 <div class="container">
    <br>
    <?= \Config\Services::validation()->listErrors(); ?>
 
    <span class="d-none alert alert-success mb-3" id="res_message"></span>
 
    <div class="row">
      <div class="col-md-9">
        <form action="<?php echo base_url('posts/store');?>" name="post_form" id="post_form" method="post" accept-charset="utf-8">
 
          <div class="form-group">
            <label for="title">Title</label>
            <input type="text" name="title" class="form-control" id="title" placeholder="Please enter title">
             
          </div> 
 
          <div class="form-group">
            <label for="email">Description</label>
            <input type="text" name="description" class="form-control" id="email" placeholder="Please enter description">
             
          </div>   
 
          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
          
        </form>
      </div>
 
    </div>
  
</div>
 <script>
   if ($("#post_form").length > 0) {
      $("#post_form").validate({
      
    rules: {
      title: {
        required: true,
      },
  
      description: {
        required: true,       
      },   
    },
    messages: {
        
      title: {
        required: "Please enter title",
      },
      description: {
        required: "Please enter description",       
      }, 
    },
  })
}
</script>
</body>
</html>
edit-post.php
<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 CRUD Tutorial - Edit Post Form With Validation Example</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
 
</head>
<body>
 <div class="container">
    <br>
    <?= \Config\Services::validation()->listErrors(); ?>
 
    <span class="d-none alert alert-success mb-3" id="res_message"></span>
 
    <div class="row">
      <div class="col-md-9">
        <form action="<?php echo base_url('posts/update');?>" name="post_form" id="post_form" method="post" accept-charset="utf-8">
 
           <input type="hidden" name="id" class="form-control" id="id" value="<?php echo $post['id'] ?>">
 
          <div class="form-group">
            <label for="title">Title</label>
            <input type="text" name="title" class="form-control" id="title" placeholder="Please enter title" value="<?php echo $post['title'] ?>">
             
          </div> 
 
          <div class="form-group">
            <label for="description">Description</label>
            <input type="text" name="description" class="form-control" id="description" placeholder="Please enter description" value="<?php echo $post['description'] ?>">
             
          </div>   
 
          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
          
        </form>
      </div>
 
    </div>
  
</div>
<script>
   if ($("#post_form").length > 0) {
      $("#post_form").validate({
      
    rules: {
      title: {
        required: true,
      },
  
      description: {
        required: true,       
      },   
    },
    messages: {
        
      title: {
        required: "Please enter title",
      },
      description: {
        required: "Please enter description",       
      }, 
    },
  })
}
</script>
</body>
</html>

Now you can run the application on http://localhost/crud/public/posts

Phone: (+91) 8800417876
Noida, 201301