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
okey metin2 pvp serverler metin2 pvp
ataşehir escort maltepe escort bostancı escort kadıköy escort maltepe escort ataşehir escort tuzla escort pendik escort ümraniye escort kartal escort
pendik escort
izmir escort izmir escort izmir escort izmir escort denizli escort antalya escort antalya escort antalya escort izmir escort izmir escort izmir escort izmir escort izmir escort
antalya escort akseki escort aksu escort alanya escort bayan antalya escort antalya grup escort antalya masöz antalya rus escort antalya sınırsız escort antalya travesti escort bdsm escort beldibi escort bayan belek escort bayan çallı escort bayan çamyuva escort bayan demre escort bayan elmalı escort bayan fethiye escort bayan finike escort bayan göynük escort bayan güllük escort bayan ışıklar escort bayan kaş escort bayan kemer escort bayan konyaaltı altınkum escort bayan konyaaltı arapsuyu escort bayan konyaaltı escort bayan konyaaltı liman escort korkuteli escort bayan kültür escort kundu escort bayan lara escort bayan manavgat escort bayan muratpaşa escort bayan örnekköy escort bayan rus escort bayan serik escort bayan side escort bayan suriyeli escort tekirova escort bayan üniversiteli escort alanya escort mahmutlar escort alanya escort mahmutlar escort alanya escort mahmutlar escort istanbul escort avrupa yakası escort şişli escort topkapı escort istanbul vip escort maslak escort merter escort aksaray escort arnavutköy escort ataköy escort bağcılar escort bahçelievler escort bakırköy escort beşitaş escort beylikdüzü escort beyoğlu escort halkalı escort istanbul sınırsız escort kağıthane escort mecidiyeköy escort nişantaşı escort escort istanbul ataşehir escort beykoz escort çekmeköy escort kadıköy escort maltepe escort pendik escort sancaktepe escort şile escort sultanbeyli escort tuzla escort ümraniye escort üsküdar escort
beylikdüzü escort istanbul escort şişli escort beylikdüzü escort istanbul escort
kocaeli escort izmit escort bayan gebze escort izmit sınırsız escort escort bursa tuzla escort aydınlı escort orhanlı escort bursa escort escort bayan istanbul escort istanbul sınırsız escort istanbul bayan escort izmit escort izmit escort kocaeli escort sisli escort mecidiyekoy escort bursa escort bayan bursa görükle escort maltepe escort goztepe escort yakacik-yeni-escort bursa sınırsız escort sisli escort bayan taksim escort bursa escort porno izle sikiş izle atasehir escort antalya escort
ankara escort marmaris escort bursa escort mersin escort antalya escort izmir escort samsun escort bodrum escort çeşme escort kuşadası escort adana escort eskişehir escort gaziantep escort esenyurt escort pendik escort tuzla escort fatih escort ümraniye escort mecidiyeköy escort kartal escort bahçelievler escort bahçeşehir escort ataşehir escort bakırköy escort nişantaşı escort avcılar escort büyükçekmece escort kurtkoy escort konya escort beşiktaş escort taksim escort beylikdüzü escort malatya escort sakarya escort şişli escort maltepe escort kadıköy escort ataköy escort bostancı escort şirinevler escort bağcılar escort üsküdar escort etiler escort başaksehir escort ortaköy escort kağıthane escort sultangazi escort halkalı escort çekmeköy escort şaşkınbakkal escort mamak escort sincan escort keçiören escort çankaya escort beypazarı escort akyurt escort pursaklar escort kahramankazan escort göztepe escort alsancak escort bornova escort buca escort karabaglar escort karşıyaka escort konak escort narlıdere escort izmit escort başiskele escort kandira escort körfez escort karamürsel escort dilovası escort gölcük escort gebze escort kocaeli escort kayseri escort elazığ escort denizli escort diyarbakir escort adana escort ankara escort izmir escort antalya escort gaziantep escort kayseri escort konya escort mersin escort denizli escort kocaeli escort diyarbakır escort alanya escort manavgat escort bursa escort eskişehir escort sakarya escort samsun escort malatya escort trabzon escort adıyaman escort afyon escort ağrı escort aksaray escort amasya escort ardahan escort artvin escort aydın escort balikesir escort bartın escort batman escort bayburt escort bilecik escort bingöl escort bitlis escort bolu escort burdur escort çanakkale escort çankırı escort çorum escort düzce escort edirne escort elazığ escort erzincan escort erzurum escort giresun escort gümüşhane escort hatay escort ığdır escort ısparta escort maraş escort karabük escort karaman escort kars escort kastamonu escort kilis escort kırıkkale escort kırklareli escort kırşehir escort kütahya escort manisa escort mardin escort muğla escort muş escort nevşehir escort niğde escort ordu escort osmaniye escort rize escort urfa escort siirt escort sinop escort şırnak escort sivas escort ordu escort tokat escort tunceli escort usak escort van escort yalova escort yozgat escort zonguldak escort kıbrıs escort
adana escort ankara escort bursa escort diyarbakir escort eskisehir escort kayseri escort kocaeli escort konya escort malatya escort maras escort mersin escort ordu escort sakarya escort samsun escort hatay escort mardin escort tekirdag escort antalya escort aydin escort nigde escort nevsehir escort elazig escort manisa escort osmaniye escort denizli escort mugla escort
bedava bahis
tahmin
ankara escort - ankara escort
ataşehir escort ataşehir anadolu yakası escort ankara escort antalya escort antalya escort

flynta 5 mg

flynta 5 mg fiyat

orcafil 5 mg

lifta

degra

sildegra

combo 100 mg

degra 100 mg

vigrande

sinegra

jeligra

lifta 20

vigrande 100 mg

lifta 20 mg

lifta 5 mg

sildegra 100 mg

vigaroo

flynta 20 mg

viagra 100 mg fiyat

orijinal viagra

viagra 100 mg

eczane viagra

viagra sipariş

viagra satın al

viagra nedir

viagra yorum

viagra fiyat

viagra fiyatı 2021

cialis

cialis fiyat

cialis 20 mg

cialis 100 mg

cialis nedir

cialis 5 mg fiyatı

cialis hap

cialis 5 mg

cialis 20 mg eczane fiyatı

cialis 100 mg fiyat

cialis satış

izmir escort
ataşehir escort
pendik aktar