Site Admin
Site Admin Founder of MeaningArticles
617 Views

Codeigniter CRUD Operation with MySQL

Hello Dev.

In this article, we will learn how to construct a simple Codeigniter CRUD Operation with MySQL example functionality. CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are primary information manipulation for database. For knowing better way to any framwork we need to build fundamental crud generator. This tutorial incorporates Codeigniter crud software so that you can carry out a lot of these operations on a MySQL database table at one place. here will reveal simple First Codeigniter fundamental CRUD educational instance with mysql from scratch and little by little inclusive of data list, data insert, data update and data delete.


Step 1: Download Codeigniter Project

First we want to download the Codeigniter 3 project just go the Codeigniter website and download. After downloading extract the folder and upload it to your local system xampp/htdocs/.


Step 2: Basic Configurations

Now we will set a few basic configuration on config.php file, so permit’s go to application/config/config.php and add the base url something like below.

$config['base_url'] = 'http://localhost/codeigniter-crud';


Step 3: Setup Database

Now on this step we want to create database name codeigniter_crud, So open your phpmyadmin and create the database with the name codeigniter_crud. Then update the primary credentials in database.php file.
application/config/database.php

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'admin',
    'database' => 'codeigniter_crud',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);


Step 4: Create Database Table

Now run following SQL Query with selecting the database in phpmyadmin and create “tasks” table.

CREATE TABLE `tasks` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255),
 `description` text,
 PRIMARY KEY (`id`)
)


Step 5: Create Routes

Now add some routes for basic crud operation with codeigniter.
application\config\routes.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

$route['task'] = "Task/index";
$route['task/create'] = "Task/create";
$route['task/edit'] = "Task/edit/$1";
$route['task/store'] = "Task/store";
$route['task/show'] = "Task/show/$1";
$route['task/update/(:any)'] = "Task/update/$1";
$route['task/delete'] = "Task/delete";


Step 6: Create Controller

in this step we create a controller and upload the following methods for creating the crud tutorial in codeigniter. allow’s go to application/controllers/ and create a controller name Task.php. Now we add a few methods/functions call index, add, edit, show, delete, update for performing a crud operation.
application\controllers\Task.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Task extends CI_Controller {

    function __construct(){
      parent::__construct();
      $this->load->helper('url');
      $this->load->library('session');
      $this->load->database();
    }

  public function index()
  {
    $tasks = $this->db->get('tasks')->result();
    $this->load->view('task/index', ['tasks' => $tasks]);
  }

  public function create()
  {
    $this->load->view('task/create');
  }

  public function edit($id)
  {
    $task = $this->db->where(['id' => $id])->get('tasks')->row();
    $this->load->view('task/edit', ['task' => $task]);
  }

  public function store()
  {
      $this->load->library('form_validation');
      $this->form_validation->set_rules('title', 'Title', 'required');
      $this->form_validation->set_rules('description', 'Description','required');

      if ($this->form_validation->run()){
        $task = array (
          'title' => $this->input->post('title'),
          'description' => $this->input->post('description'),
        );

        $this->db->insert('tasks', $task);
      } 
      else {
        $errors = $this->form_validation->error_array();
        $this->session->set_flashdata('errors', $errors);
        redirect(base_url('task/create'));
      }

      redirect('/task');
  }

  public function update($id)
  {
    $this->load->library('form_validation');
    $this->form_validation->set_rules('title', 'Title', 'required');
    $this->form_validation->set_rules('description', 'Description', 'required');

    if ($this->form_validation->run()) {
      $task = array (
        'title' => $this->input->post('title'),
        'description' => $this->input->post('description'),
      );

       $this->db->where(['id' => $id])->update('tasks', $task);
    }
    else {
      $errors = $this->form_validation->error_array();
      $this->session->set_flashdata('errors', $errors);
      redirect(base_url('task/edit/'. $id));
    }

     redirect('/task');
  }

  public function show($id) 
  {
     $task = $this->db->where(['id' => $id])->get('tasks')->row();
     $this->load->view('task/show',['task' => $task]);
  }

  public function delete($id)
  {
     $this->db->where(['id' => $id])->delete('tasks');

     redirect('/task');
  }
}


Step 7: Create Views

Go to application/views/ and create a one folder name ‘task‘, inside the task folder we will create four views files as below list:

1. index.php
2. create.php
3. edit.php
4. show.php

First create index.php file and put the below code inside the file. This file show all tasks lists.
application\views\task\index.php

<!DOCTYPE html>
<html>
<head>
    <title>Simple Crud operation in Codeigniter</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-lg-12 margin-tb">
          <div class="pull-left">
              <h2>Codeigniter CRUD Example from scratch - meaningarticles.com</a></h2>
          </div>
          <div class="pull-right">
              <a class="btn btn-success" href="/task/create"> Create New Item</a>
          </div>
      </div>
    </div>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Title</th>
                <th>Description</th>
                <th width="220px">Action</th>
            </tr>
        </thead>
        <tbody>
          <?php foreach ($tasks as $task) { ?>
            <tr>
                <td><?php echo $task->title; ?></td>
                <td><?php echo $task->description; ?></td>
            <td>
              <form method="DELETE" action="<?php echo base_url('task/delete/'.$task->id);?>">
                <a class="btn btn-info" href="<?php echo base_url('task/show/'.$task->id) ?>"> show</a>
               <a class="btn btn-primary" href="<?php echo base_url('task/edit/'.$task->id) ?>"> Edit</a>
                <button type="submit" class="btn btn-danger"> Delete</button>
              </form>
            </td>
            </tr>
          <?php } ?>
        </tbody>
    </table>
  </div>
</body>
</html>

For creating new task we need to show the form using the create.php file, create and put the below code inside the file.
application\views\task\create.php

<!DOCTYPE html>
<html>
<head>
    <title>Basic Crud operation in Codeigniter 3</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
  <div class="container">
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Create Task</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="<?php echo base_url('task')?>"> Back</a>
            </div>
        </div>
    </div>
    <form method="post" action="<?php echo base_url('task/store')?>">
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Title:</strong>
                    <input type="text" name="title" class="form-control">
                    <?php
                      if (isset($this->session->flashdata('errors')['title'])){
                          echo '<div class="alert alert-danger mt-2">';
                          echo $this->session->flashdata('errors')['title'];
                          echo "</div>";
                      }
                    ?>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Description:</strong>
                    <textarea name="description" class="form-control"></textarea>
                    <?php
                      if (isset($this->session->flashdata('errors')['description'])){
                          echo '<div class="alert alert-danger mt-2">';
                          echo $this->session->flashdata('errors')['description'];
                          echo "</div>";
                      }
                    ?>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                    <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
    </form>
  </div>
</body>
</html>

Now edit the task using the edit.php file.
application\views\task\edit.php

<!DOCTYPE html>
<html>
<head>
    <title>Basic Crud application in Codeigniter 3</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
  <div class="container">
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Update Task</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="<?php echo base_url('task')?>"> Back</a>
            </div>
        </div>
    </div>
    <form method="post" action="<?php echo base_url('task/update/'.$task->id)?>">
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Title:</strong>
                    <input type="text" name="title" class="form-control" value="<?php echo $task->title; ?>">
                    <?php
                      if (isset($this->session->flashdata('errors')['title'])){
                          echo '<div class="alert alert-danger mt-2">';
                          echo $this->session->flashdata('errors')['title'];
                          echo "</div>";
                      }
                    ?>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Description:</strong>
                    <textarea name="description" class="form-control"><?php  echo $task->description; ?></textarea>
                    <?php
                      if (isset($this->session->flashdata('errors')['description'])){
                          echo '<div class="alert alert-danger mt-2">';
                          echo $this->session->flashdata('errors')['description'];
                          echo "</div>";
                      }
                    ?>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                    <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
    </form>
  </div>
</body>
</html>

Showing the task we need to create a show.php file.
application\views\task\show.php

<!DOCTYPE html>
<html>
<head>
    <title>Basic Crud operation in Codeigniter 3</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-lg-12 margin-tb">
          <div class="pull-left">
              <h2>Codeigniter CRUD Example from scratch - meaningarticles.com</h2>
          </div>
          <div class="pull-right">
              <a class="btn btn-success" href="/task"> Back</a>
          </div>
      </div>
    </div>

    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Title:</strong>
                <?php echo $task->title; ?>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Description:</strong>
                <?php echo $task->description; ?>
            </div>
        </div>
    </div>
  </div>
</body>
</html>

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.