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

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

In this post we will give you information about PHP CodeIgniter 4 – Basic CRUD operation with MySQL Database with example. Hear we will give you detail about PHP CodeIgniter 4 – Basic CRUD operation with MySQL Database with exampleAnd how to use it also give you demo for it if it is necessary.

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 AppModels;
use CodeIgniterDatabaseConnectionInterface;
use CodeIgniterModel;
 
classPostModelextends 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.
<?phpnamespace AppControllers;
 
use CodeIgniterController;
use AppModelsPostModel;
 
classPostsextends Controller
{
 
    publicfunctionindex()
    {    
        
        $model=new PostModel();
 
        $data['posts'] =$model->orderBy('id', 'DESC')->findAll();
        
        return view('posts', $data);
    }    
 
    publicfunctioncreate()
    {    
        return view('create-post');
    }
 
    publicfunctionstore()
    {  
 
        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') );
    }
 
    publicfunctionedit($id=null)
    {
    
     $model=new PostModel();
     
     $data['post'] =$model->find($id);
      
     return view('edit-post', $data);
    }
 
    publicfunctionupdate()
    {  
 
        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') );
    }
 
    publicfunctiondelete($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>
<htmllang="en">
  <head>
  <metacharset="utf-8">
  <metaname="viewport"content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 CRUD Tutorial -  posts List Example - Expertphp.in</title>
  <linkrel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <linkrel="stylesheet"type="text/css"href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">

</head>
<body>
 
<divclass="container mt-5">
    <ahref="<?php echo base_url('posts/create') ?>"class="btn btn-sm btn-success">Create</a>
   
  <divclass="row mt-3">
     <tableclass="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>
              <ahref="<?php echo base_url('posts/edit/'.$post['id']);?>"class="btn btn-sm btn-success">Edit</a>
              <ahref="<?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>
 <linkrel="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>
 <divclass="container">
    <br>
    <?= ConfigServices::validation()->listErrors(); ?>
 
    <spanclass="d-none alert alert-success mb-3"id="res_message"></span>
 
    <divclass="row">
      <divclass="col-md-9">
        <formaction="<?php echo base_url('posts/store');?>"name="post_form"id="post_form"method="post"accept-charset="utf-8">
 
          <divclass="form-group">
            <labelfor="title">Title</label>
            <inputtype="text"name="title"class="form-control"id="title"placeholder="Please enter title">
             
          </div> 
 
          <divclass="form-group">
            <labelfor="email">Description</label>
            <inputtype="text"name="description"class="form-control"id="email"placeholder="Please enter description">
             
          </div>   
 
          <divclass="form-group">
           <buttontype="submit"id="send_form"class="btn btn-success">Submit</button>
          </div>
          
        </form>
      </div>
 
    </div>
  
</div>
 <script>
   if ($("#post_form").length >) {
      $("#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>
 <linkrel="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>
 <divclass="container">
    <br>
    <?= ConfigServices::validation()->listErrors(); ?>
 
    <spanclass="d-none alert alert-success mb-3"id="res_message"></span>
 
    <divclass="row">
      <divclass="col-md-9">
        <formaction="<?php echo base_url('posts/update');?>"name="post_form"id="post_form"method="post"accept-charset="utf-8">
 
           <inputtype="hidden"name="id"class="form-control"id="id"value="<?php echo $post['id'] ?>">
 
          <divclass="form-group">
            <labelfor="title">Title</label>
            <inputtype="text"name="title"class="form-control"id="title"placeholder="Please enter title"value="<?php echo $post['title'] ?>">
             
          </div> 
 
          <divclass="form-group">
            <labelfor="description">Description</label>
            <inputtype="text"name="description"class="form-control"id="description"placeholder="Please enter description"value="<?php echo $post['description'] ?>">
             
          </div>   
 
          <divclass="form-group">
           <buttontype="submit"id="send_form"class="btn btn-success">Submit</button>
          </div>
          
        </form>
      </div>
 
    </div>
  
</div>
<script>
   if ($("#post_form").length >) {
      $("#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

PHP Codeigniter 3 – Basic CRUD Operation with MySQL Database with example

Hope this code and post will helped you for implement PHP CodeIgniter 4 – Basic CRUD operation with MySQL Database with example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

62  +    =  67

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US