
How to Develop Basic CRUD Operations in CodeIgniter
Today I am going to demonstrate the basic installation of CodeIgniter, a PHP Framework, and a simple example of building a CRUD (Create, Read/Retrieve, Update and Delete) with it.
Pre-requisites
It’s assumed that you have an intermediate level of understanding of the following:
PHP, MySQL, OOP, MVC
Installation
Download
To work with CodeIgniter, we have to download its latest version (2.1.4 at the time of this writing) from its download link at http://ellislab.com/codeigniter.
WAMP Server Environment
An environment with at least Apache and PHP is needed to work with CodeIgniter. For a Windows platform, WAMP server stack is readily available and its .exe can set up the environment in a few seconds. WAMP server setup can be downloaded from http://www.wampserver.com/en/.
Setup
Once the WAMP server is installed, please unzip the downloaded CodeIgniter file and rename the folder to “
Now place this
Configurations
In this section, we will configure settings for the database to help build this CRUD sample quickly but with ease of use, reusability and security features. We will also configure some other settings to benefit from the core libraries of this framework.
The first file to setup the configurations is C:WAMPwwwcisampleapplicationconfigconfig.php.
Set up the base URL to http://localhost/cisample.
Remove “index.php” from this line’s contents:
$config['index_page'] = 'index.php'
like this:
$config['index_page'] = '';
This will make the URLs clean.
What are clean URLs?
To understand this we look at two different examples of URLs:
Normal URL: http://www.example.com/page.php?id=45
Clean URL: http://www.example.com/page/id/45
The Normal URL has a ‘?’ (Query string character) in the URL which is neither user nor search engine friendly. Whereas the Clean URL looks
For database configuration, first of
There are a couple of settings needed in C:WAMPwwwcisampleapplicationconfigautoload.php.
To load the database library, change $autoload[‘libraries’] = array(); to $autoload[‘libraries’] = array(‘database’).
To load the URL and form helpers, change $autoload[‘helper’] = array(); to $autoload[‘herper’] = array(‘url’,’form’).
Auto loading of libraries and helpers makes life easier as one doesn’t have to load the libraries and helpers each and every time when they are needed. They are automatically loaded using the above configurations in the autoload.php file.
Example’s Introduction and Database Table Structure
This example will demonstrate a simple to-do List CRUD. It will also use a simple three column table to hold the to-do items. The name of the columns will be id, title, and detail.
It’s time to dive straight into the code.
1. Start the WAMP environment.
2. Create a table in the database with the following query:
CREATE TABLE IF NOT EXISTS `todos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` text NOT NULL,
`completed` int(1) NOT NULL,
PRIMARY KEY (`id`)
3. Create a controller file “application/controllers/todos.php” for to-dos with the following code:
class Todos extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library(‘form_validation’);
$this->load->model(‘todo_model’);
}
public function index()
{
$data[‘title’] = ‘To-Dos List’;
$data[‘todos’] = $this->todo_model->get_todos();
$this->load->view(‘templates/header’, $data);
$this->load->view(‘todos/index’, $data);
$this->load->view(‘templates/footer’);
}
public function view()
{
$id = $this->uri->segment(3);
if (empty($id))
{
show_404();
}
$data[‘title’] = ‘View a To-do item’;
$data[‘todo’] = $this->todo_model->get_todos($id);
$this->load->view(‘templates/header’, $data);
$this->load->view(‘todos/view’, $data);
$this->load->view(‘templates/footer’);
}
public function create()
{
$data[‘title’] = ‘Create a To-do item’;
$this->form_validation->set_rules(‘title’, ‘Title’, ‘required’);
$this->form_validation->set_rules(‘description’, ‘Description’, ‘required’);
if ($this->form_validation->run() === FALSE)
{
$this->load->view(‘templates/header’, $data);
$this->load->view(‘todos/create’);
$this->load->view(‘templates/footer’);
}
else
{
$this->todo_model->set_todos();
$this->load->view(‘todos/success’);
}
}
public function edit()
{
$id = $this->uri->segment(3);
if (empty($id))
{
show_404();
}
$data[‘title’] = ‘Edit a To-do item’;
$data[‘todo’] = $this->todo_model->get_todos($id);
$this->form_validation->set_rules(‘title’, ‘Title’, ‘required’);
$this->form_validation->set_rules(‘description’, ‘Description’, ‘required’);
if ($this->form_validation->run() === FALSE)
{
$this->load->view(‘templates/header’, $data);
$this->load->view(‘todos/edit’, $data);
$this->load->view(‘templates/footer’, $data);
}
else
{
$this->todo_model->set_todos($id);
redirect( base_url() . ‘todos’);
}
}
public function completed()
{
$id = $this->uri->segment(3);
if (empty($id))
{
show_404();
}
$this->todo_model->completed($id);
redirect( base_url() . ‘todos’);
}
}
The index method sets the page title, loads all the to-dos from the model and loads the index view to display the listing of all the to-dos.
The “view” method gets the to-do ID from the URL, checking to see whether the ID is empty or not. If it’s empty, then it throws a 404 page or gets the to-do item from the model based on the to-do ID and loads “view” to show the to-do item details.
The create method presents the user with a form to create a to-do, processes the input through validation rules and inserts a new record into the database upon form submission.
The edit method does the same as the view method, except it loads the to-do details in a form to edit and
The “complete” method updates the record based on the ID passed in the URL to complete the process.
4. Create a model file “application/models/todo_model.php” with the following code:
class Todo_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_todos($id = 0)
{
if ($id === 0)
{
$query = $this->db->get_where(‘todos’,array(‘completed’ => 0));
return $query->result_array();
}
$query = $this->db->get_where(‘todos’, array(‘id’ => $id));
return $query->row_array();
}
public function set_todos($id = 0)
{
$this->load->helper(‘url’);
$data = array(
‘title’ => $this->input->post(‘title’),
‘description’ => $this->input->post(‘description’),
);
if ($id === 0) {
return $this->db->insert(‘todos’, $data);
}
else {
$this->db->where(‘id’, $id);
return $this->db->update(‘todos’, $data);
}
}
public function completed($id)
{
$data = array(
‘completed’ => 1
);
$this->db->where(‘id’, $id);
$this->db->update(‘todos’, $data);
}
}
The get_todos method fetches all the to-dos from the database if no ID is passed, or if an ID is passed, it fetches the one to-do item based on that ID.
The set_todos method inserts new data into the database for permanent storage if no ID is passed, or it updates the existing data in the database if an ID is passed.
The completed method marks a record complete in the database.
5. Create the following view files in your application/views/todos/ directory with their respective code:
a) index.php
Create a To-do item
c) edit.php
Create a To-do item
d) view.php
e) success.php
Data inserted
6. Insert the following lines in your application/config/routes.php for todos just in case you want the fancy/different URLs from your application resources:
$route['todos/create'] = 'to-dos/create';
$route['todos/view/(:any)'] = 'to-dos/view/$1';
$route['todos/edit/(:any)'] = 'to-dos/edit/$1';
$route['todos/completed/(:any)'] = 'to-dos/completed/$1';
$route['todos'] = 'to-dos';
7. Make the following changes in your application/config/config.php for todos:
$config['base_url'] = 'http://localhost/cisample/';
$config['index_page'] = '';
8. Set the following parameters in your application/config/database.php depending upon your database server settings, mine are set to defaults so:
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'cisample_db';
9. Create a .htaccess file in the
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
10. Now check your Apache web server configuration to make sure that the mod_rewrite module is loaded.
11. Create each of the following files under the application/views/templates directory with its respective code for
a) header.php
<?php echo $title ?> - CodeIgniter Sample
CodeIgniter Sample Site
b) footer.php
12. Load your todos list with http://localhost/cisample/todos.
Making a CRUD using CodeIgniter is both easier and more fun than it seems. CRUD is the first step in learning any new technology where databases are involved. You can move from here to explore more areas and become more comfortable with CodeIgniter. You’ll find those areas of CodeIgniter as easy as this tutorial. Happy CodeIgniting!