CodeIgniter: Simple Add, Edit, Delete, View – MVC CRUD Application

This article shows how to create a simple CRUD (Create, Read, Update, Delete) application with CodeIgniter. CodeIgniter (CI) is a PHP framework that helps building a full-fledged web application.

This article is a continuation of the basic tutorial present in the official CodeIgniter site. The tutorial had view and add data part. But, it didn’t contain the update and delete part. I have just added update and delete functionality in it.

Here is the step-by-step guide on creating a CRUD (Add/Edit/Delete/Update) application in CodeIgniter.

Create Database and Table

First of all, we create database and table. For this article example, we will be creating database named test. We will be creating a table named news inside the database test.


--
-- Create database `test`
--

CREATE DATABASE `test`;

use `test`;

--
-- Table structure for table `news`
--

CREATE TABLE IF NOT EXISTS `news` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(128) NOT NULL,
  `slug` varchar(128) NOT NULL,
  `text` text NOT NULL,
  PRIMARY KEY (`id`),
  KEY `slug` (`slug`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

--
-- Dumping data for table `news`
--

INSERT INTO `news` (`id`, `title`, `slug`, `text`) VALUES
(1, 'Test', 'test', 'Hello World !!'),
(2, 'What is Lorem Ipsum?', 'what-is-lorem-ipsum', 'Lorem Ipsum is simply dummy text.');

I will present below the full code of controller, model, and views files. We will be adding, updating, deleting news item to our database table. News item just contains title and text content.

Database Config Settings

After you create your database, you need to specify your database host, database name, database username & database password in a database config file in codeigniter. The file is located at application/config/database.php.

My database host is localhost, database name is test (as created by above sql query), database username is root and database password is root.

Here is the config settings for this example:

File: application/config/database.php


$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',   
    'database' => 'test',   
    '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
);

Controller

(application/controllers/News.php)

First of all, we need a Controller which processes the input request from user, communicates with Model and then loads appropriate Views file.

In the below Controller class, we have different functions (actions) for different tasks. Like, the index() function is used for listing all news items, create() function is used to add a new news item, edit() function is used to edit the news item, and delete() function is used to delete the news item.


<?php
class News extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('news_model');
        $this->load->helper('url_helper');
    }

    public function index()
    {
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';

        $this->load->view('templates/header', $data);
        $this->load->view('news/index', $data);
        $this->load->view('templates/footer');
    }

    public function view($slug = NULL)
    {
        $data['news_item'] = $this->news_model->get_news($slug);
        
        if (empty($data['news_item']))
        {
            show_404();
        }

        $data['title'] = $data['news_item']['title'];

        $this->load->view('templates/header', $data);
        $this->load->view('news/view', $data);
        $this->load->view('templates/footer');
    }
    
    public function create()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $data['title'] = 'Create a news item';

        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('text', 'Text', 'required');

        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('templates/header', $data);
            $this->load->view('news/create');
            $this->load->view('templates/footer');

        }
        else
        {
            $this->news_model->set_news();
            $this->load->view('templates/header', $data);
            $this->load->view('news/success');
            $this->load->view('templates/footer');
        }
    }
    
    public function edit()
    {
        $id = $this->uri->segment(3);
        
        if (empty($id))
        {
            show_404();
        }
        
        $this->load->helper('form');
        $this->load->library('form_validation');
        
        $data['title'] = 'Edit a news item';        
        $data['news_item'] = $this->news_model->get_news_by_id($id);
        
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('text', 'Text', 'required');

        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('templates/header', $data);
            $this->load->view('news/edit', $data);
            $this->load->view('templates/footer');

        }
        else
        {
            $this->news_model->set_news($id);
            //$this->load->view('news/success');
            redirect( base_url() . 'index.php/news');
        }
    }
    
    public function delete()
    {
        $id = $this->uri->segment(3);
        
        if (empty($id))
        {
            show_404();
        }
                
        $news_item = $this->news_model->get_news_by_id($id);
        
        $this->news_model->delete_news($id);        
        redirect( base_url() . 'index.php/news');       
    }
}

Model

(application/models/News_model.php)

Model class communicates with the database. The main database logic is written here. This class is responsible for interacting with database for data select, insert, update and delete purposes.

In the below Model class, get_news() function fetches/selects news items by $slug name. get_news_by_id() function fetches news by it’s ID. set_news() function either edit or add news item. delete_news() function delets any particular news item.


<?php
class News_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }
    
    public function get_news($slug = FALSE)
    {
        if ($slug === FALSE)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }

        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
    }
    
    public function get_news_by_id($id = 0)
    {
        if ($id === 0)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }

        $query = $this->db->get_where('news', array('id' => $id));
        return $query->row_array();
    }
    
    public function set_news($id = 0)
    {
        $this->load->helper('url');

        $slug = url_title($this->input->post('title'), 'dash', TRUE);

        $data = array(
            'title' => $this->input->post('title'),
            'slug' => $slug,
            'text' => $this->input->post('text')
        );
        
        if ($id == 0) {
            return $this->db->insert('news', $data);
        } else {
            $this->db->where('id', $id);
            return $this->db->update('news', $data);
        }
    }
    
    public function delete_news($id)
    {
        $this->db->where('id', $id);
        return $this->db->delete('news');
    }
}

Template Header

(application/views/templates/header.php)

This is a template file common for all pages. We call header in all pages.


<html>
        <head>
                <title>CodeIgniter Tutorial</title>
        </head>
        <body>

                <h1>Simple CRUD</h1>
                <a href="<?php echo site_url('news'); ?>">Home</a> | <a href="<?php echo site_url('news/create'); ?>">Add News</a>

Template Footer

(application/views/templates/footer.php)

This is a template file common for all pages. We call footer in all pages.


<em>Copyright © 2016</em>
        </body>
</html>

Index View

(application/views/news/index.php)

This view file is called by index() function of our Controller class. It lists out all the news item.


<h2><?php echo $title; ?></h2>

<table border='1' cellpadding='4'>
    <tr>
        <td><strong>Title</strong></td>
        <td><strong>Content</strong></td>
        <td><strong>Action</strong></td>
    </tr>
<?php foreach ($news as $news_item): ?>
        <tr>
            <td><?php echo $news_item['title']; ?></td>
            <td><?php echo $news_item['text']; ?></td>
            <td>
                <a href="<?php echo site_url('news/'.$news_item['slug']); ?>">View</a> | 
                <a href="<?php echo site_url('news/edit/'.$news_item['id']); ?>">Edit</a> | 
                <a href="<?php echo site_url('news/delete/'.$news_item['id']); ?>" onClick="return confirm('Are you sure you want to delete?')">Delete</a>
            </td>
        </tr>
<?php endforeach; ?>
</table>

Detail View

(application/views/news/view.php)

This view file is called by view() function of our Controller class. It prints a particular news item.


<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo $news_item['text'];

Add View

(application/views/news/create.php)

This view file is called by create() function of our Controller class. It prints a form to add news item.


<h2><?php echo $title; ?></h2>

<?php echo validation_errors(); ?>

<?php echo form_open('news/create'); ?> 
    <table>
        <tr>
            <td><label for="title">Title</label></td>
            <td><input type="input" name="title" size="50" /></td>
        </tr>
        <tr>
            <td><label for="text">Text</label></td>
            <td><textarea name="text" rows="10" cols="40"></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" name="submit" value="Create news item" /></td>
        </tr>
    </table>    
</form>

Edit View

(application/views/news/edit.php)

This view file is called by edit() function of our Controller class. It prints a form to edit news item.


<h2><?php echo $title; ?></h2>

<?php echo validation_errors(); ?>

<?php echo form_open('news/edit/'.$news_item['id']); ?>
    <table>
        <tr>
            <td><label for="title">Title</label></td>
            <td><input type="input" name="title" size="50" value="<?php echo $news_item['title'] ?>" /></td>
        </tr>
        <tr>
            <td><label for="text">Text</label></td>
            <td><textarea name="text" rows="10" cols="40"><?php echo $news_item['text'] ?></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" name="submit" value="Edit news item" /></td>
        </tr>
    </table>
</form>

Add Success View

(application/views/news/success.php)

This view file is called after a new news item is added to database. This file is called in create() function of our Controller class.


News added successfully!

Config Routes

(application/config/routes.php)

Routing rules are defined here. Routes can either be specified using wildcards or Regular Expressions.


$route['news'] = 'news';
$route['news/create'] = 'news/create';

$route['news/edit/(:any)'] = 'news/edit/$1';

$route['news/view/(:any)'] = 'news/view/$1';
$route['news/(:any)'] = 'news/view/$1';

Now, you can access your application as http://your-website.com/news.

When you open your project in browser, you will get something like below image:

crud codeigniter

Download Source Code from GitHub

Hope this helps. Thanks.