CodeIgniter 3 Simple CRUD Step-by-Step Tutorial

CodeIgniter 3 Simple CRUD Step-by-Step Tutorial

Avatar photoPosted by

Introduction:

In today’s tutorial, I will show you how to develop a CodeIgniter 3 Simple CRUD Application. This tutorial is made for starters on CodeIgniter 3.

CodeIgniter is an open-source web framework that is used for rapid web development. CodeIgniter follows the MVC (Model-View-Controller) architectural pattern. It is noted for its speed compared to other PHP web frameworks.

CRUD is an acronym for CREATE, READ, UPDATE, DELETE. The four basic functions in any type of programming. CRUD typically refers to operations performed in a database.

  • Create -Generate new record/s.
  • Read – Reads or retrieve record/s.
  • Update – Modify record/s.
  • Delete – Destroy or remove record/s.

Before proceeding on this tutorial, you must have an environment already setup to run and install CodeIgniter 3. If you haven’t, please do read my blog –How to Install CodeIgniter 3 in XAMPP Easy Tutorial.

Step 1: Download CodeIgniter 3

First you must download the CodeIgniter 3 on this link.

After downloading, extract the file and rename the folder as “project-manager” or anything you prefer.

Step 2: Set Database Configuration

Before configuring the database, we must first create a database named project_manager and create a table named projects:

Run this SQL query to create the projects table:

CREATE TABLE `projects` (
  `id` int(10) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `description` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Open the app folder and configure your database on this file “database.php“.

application/config/database.php

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'Your Username',
	'password' => 'Your Password',
	'database' => 'Your Database Name',
	'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 3: Update Config.php

Open the file config.php and find and update the base_url value.

application/config/config.php

$config['base_url'] = 'http://localhost/project-manager/index.php';

Step 4: Register Routes

And now we will register the routes for our CRUD app.

Open the routes.php file and register these route:

application/config/routes.php

$route['project'] = "project/index";
$route['project/create'] = "project/create";
$route['project/store']['post'] = "project/store";
$route['project/edit/(:num)'] = "project/edit/$1";
$route['project/update/(:num)']['put'] = "project/update/$1";
$route['project/delete/(:num)']['delete'] = "project/delete/$1";

Step 5: Create Controller

Go to this path “application/controllers/” and create a controller named Project.php. This will handle all our users actions. The controller will have these following methods.

  • index()
  • show($id)
  • create()
  • store()
  • edit($id)
  • update($id)
  • delete($id)

After creating the controller, insert the codes below:

application/controllers/Project.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Project extends CI_Controller {

   public function __construct() {
      parent::__construct(); 
      $this->load->library('form_validation');
      $this->load->library('session');
      $this->load->model('Project_model', 'project');

   }

   /*
      Display all records in page
   */
  public function index()
  {
    $data['projects'] = $this->project->get_all();
    $data['title'] = "CodeIgniter Project Manager";
    $this->load->view('layout/header');       
    $this->load->view('project/index',$data);
    $this->load->view('layout/footer');
  }

  /*

    Display a record
  */
  public function show($id)
  {
    $data['project'] = $this->project->get($id);
    $data['title'] = "Show Project";
    $this->load->view('layout/header');
    $this->load->view('project/show', $data);
    $this->load->view('layout/footer'); 
  }

  /*
    Create a record page
  */
  public function create()
  {
    $data['title'] = "Create Project";
    $this->load->view('layout/header');
    $this->load->view('project/create',$data);
    $this->load->view('layout/footer');     
  }

  /*
    Save the submitted record
  */
  public function store()
  {
    $this->form_validation->set_rules('name', 'Name', 'required');
    $this->form_validation->set_rules('description', 'Description', 'required');

    if (!$this->form_validation->run())
    {
        $this->session->set_flashdata('errors', validation_errors());
        redirect(base_url('project/create'));
    }
    else
    {
       $this->project->store();
       $this->session->set_flashdata('success', "Saved Successfully!");
       redirect(base_url('project'));
    }

  }

  /*
    Edit a record page
  */
  public function edit($id)
  {
    $data['project'] = $this->project->get($id);
    $data['title'] = "Edit Project";
    $this->load->view('layout/header');
    $this->load->view('project/edit', $data);
    $this->load->view('layout/footer');     
  }

  /*
    Update the submitted record
  */
  public function update($id)
  {
    $this->form_validation->set_rules('name', 'Name', 'required');
    $this->form_validation->set_rules('description', 'Description', 'required');

    if (!$this->form_validation->run())
    {
        $this->session->set_flashdata('errors', validation_errors());
        redirect(base_url('project/edit/' . $id));
    }
    else
    {
       $this->project->update($id);
       $this->session->set_flashdata('success', "Updated Successfully!");
       redirect(base_url('project'));
    }

  }

  /*
    Delete a record
  */
  public function delete($id)
  {
    $item = $this->project->delete($id);
    $this->session->set_flashdata('success', "Deleted Successfully!");
    redirect(base_url('project'));
  }


}

Step 6: Create Model

Go to this path “application/models/” and create a model named Project_model.php. This will handle all our query to the database. The model will have this following methods.

  • get_all()
  • store()
  • get($id)
  • update($id)
  • delete($id)

After creating the model, insert the code below:

application/models/Project_model.php

<?php


class Project_model extends CI_Model{

    public function __construct()
    {
        $this->load->database();
        $this->load->helper('url');
    }

    /*
        Get all the records from the database
    */
    public function get_all()
    {
        $projects = $this->db->get("projects")->result();
        return $projects;
    }

    /*
        Store the record in the database
    */
    public function store()
    {    
        $data = [
            'name'        => $this->input->post('name'),
            'description' => $this->input->post('description')
        ];

        $result = $this->db->insert('projects', $data);
        return $result;
    }

    /*
        Get an specific record from the database
    */
    public function get($id)
    {
        $project = $this->db->get_where('projects', ['id' => $id ])->row();
        return $project;
    }


    /*
        Update or Modify a record in the database
    */
    public function update($id) 
    {
        $data = [
            'name'        => $this->input->post('name'),
            'description' => $this->input->post('description')
        ];

        $result = $this->db->where('id',$id)->update('projects',$data);
        return $result;
                
    }

    /*
        Destroy or Remove a record in the database
    */
    public function delete($id)
    {
        $result = $this->db->delete('projects', array('id' => $id));
        return $result;
    }
    
}
?>

Step 7: Create View Files

We will now create the view files. The Views are the codes that what the user see and the code that the user can interact. We will create all these files:

  • header.php
  • footer.php
  • index.php
  • create.php
  • edit.php
  • show.php

application/views/layout/header.php

<!DOCTYPE html>
<html>
<head>
	<title>CodeIgniter Project Manager</title>
	<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.0/js/bootstrap.min.js" rel="stylesheet">
	<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
	<div class="container">
    

application/views/layout/footer.php

		</div>
	</body>
</html>

application/views/project/index.php

<h2 class="text-center mt-5 mb-3"><?php echo $title; ?></h2>
<div class="card">
    <div class="card-header">
        <a class="btn btn-outline-primary" href="<?php echo base_url('project/create/');?>"> 
            Create New Project
        </a>
    </div>
    <div class="card-body">
        <?php if ($this->session->flashdata('success')) {?>
            <div class="alert alert-success">
                <?php echo $this->session->flashdata('success'); ?>
            </div>
        <?php } ?>

        <table class="table table-bordered">
            <tr>
                <th>Name</th>
                <th>Description</th>
                <th width="240px">Action</th>
            </tr>

            <?php foreach ($projects as $project) { ?>      
            <tr>
                <td><?php echo $project->name; ?></td>
                <td><?php echo $project->description; ?></td>          
                <td>
                    <a 
                        class="btn btn-outline-info" 
                        href="<?php echo base_url('project/show/'. $project->id) ?>"> 
                        Show
                    </a>
                    <a 
                        class="btn btn-outline-success" 
                        href="<?php echo base_url('project/edit/'.$project->id) ?>"> 
                        Edit
                    </a>
                    <a 
                        class="btn btn-outline-danger" 
                        href="<?php echo base_url('project/delete/'.$project->id) ?>"> 
                        Delete
                    </a>
                </td>     
            </tr>
            <?php } ?>
        </table>
    </div>
</div>

application/views/project/create.php

<h2 class="text-center mt-5 mb-3"><?php echo $title; ?></h2>
<div class="card">
    <div class="card-header">
        <a class="btn btn-outline-info float-right" href="<?php echo base_url('project');?>"> 
            View All Projects
        </a>
    </div>
    <div class="card-body">
        <?php if ($this->session->flashdata('errors')) {?>
            <div class="alert alert-danger">
                <?php echo $this->session->flashdata('errors'); ?>
            </div>
        <?php } ?>
        <form action="<?php echo base_url('project/store');?>" method="POST">
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" class="form-control" id="name" name="name">
            </div>
            <div class="form-group">
                <label for="description">Description</label>
                <textarea class="form-control" id="description" rows="3" name="description"></textarea>
            </div>
         
            <button type="submit" class="btn btn-outline-primary">Save Project</button>
        </form>
      
    </div>
</div>

application/views/project/edit.php

<h2 class="text-center mt-5 mb-3"><?php echo $title;?></h2>
<div class="card">
    <div class="card-header">
        <a class="btn btn-outline-info float-right" href="<?php echo base_url('project/');?>"> 
            View All Projects
        </a>
    </div>
    <div class="card-body">
        <?php if ($this->session->flashdata('errors')) {?>
            <div class="alert alert-danger">
                <?php echo $this->session->flashdata('errors'); ?>
            </div>
        <?php } ?>

        <form action="<?php echo base_url('project/update/' . $project->id);?>" method="POST">
            <input type="hidden" name="_method" value="PUT">
            <div class="form-group">
                <label for="name">Name</label>
                <input 
                    type="text" 
                    class="form-control" 
                    id="name" 
                    name="name" 
                    value="<?php echo $project->name;?>">
            </div>
            <div class="form-group">
                <label for="description">Description</label>
                <textarea 
                    class="form-control" 
                    id="description" 
                    rows="3" 
                    name="description"><?php echo $project->description;?></textarea>
            </div>
         
            <button type="submit" class="btn btn-outline-primary">Save Project</button>
        </form>
      
    </div>
</div>

application/views/project/show.php

<h2 class="text-center mt-5 mb-3"><?php echo $title;?></h2>
<div class="card">
    <div class="card-header">
        <a class="btn btn-outline-info float-right" href="<?php echo base_url('project/');?>"> 
            View All Projects
        </a>
    </div>
    <div class="card-body">
       <b class="text-muted">Name:</b>
       <p><?php echo $project->name;?></p>
       <b class="text-muted">Description:</b>
       <p><?php echo $project->description;?></p>
    </div>
</div>

Finally all the components are done. Now we can test our CodeIgniter 3 Simple CRUD App by browsing this URL:

http://localhost/project-manager/index.php/project

Screenshots:

CodeIgniter 3 Simple CRUD App (index page):

ci-crud-index-page

CodeIgniter 3 Simple CRUD App (create page):

ci-crud-create-page

CodeIgniter 3 Simple CRUD App (edit page):

ci-crud-edit-page

CodeIgniter 3 Simple CRUD App (show page):

ci-crud-show-page