Code Igniter is a simple and easy to use framework for PHP. If you are looking for a PHP framework to start with, to know how the MVC model or the basic functionality of a framework in general work, Code Igniter or CI is the perfect one for you. It has a lot of community support and also you can learn a lot by going through its proper documentation and user guide at https://ellislab.com/codeigniter/user-guide/toc.html and more specifically about database functions/queries at https://ellislab.com/codeigniter/user-guide/database/. You can download the latest CI at http://www.codeigniter.com/. If you face any difficulty in installing CI to your server or local machine, you can check out the user guide link mentioned above to help you out. There are already many tutorials about creating a CRUD app in CI, but I found them to be a bit difficult for a fresher. All they do is give you the code with a touch of some advance level functions like CI validation etc and don’t really explain which code relates to what in a MVC manner. I’ll try to do exactly that below, keeping the application simple, easy to understand in as less words as possible and hoping that I don’t miss anything crucial. So, here we go….

In an MVC model, MVC stands for M-Model, V-View, C-Controller. The model files are used for database handling i.e. queries, the view files are used to display data to the user and the main controller files are used to write the code to let the model and the view interact with each other and also add logic to your functions, if any. In addition to just using the MVC model, I’ll also try to explain using layouts or common template file structure.

CRUD stands for Create, Read, Update, Delete, i.e. we’ll create an entry in the database, read that entry, edit/update that entry and lastly delete that entry from the database. Now, conventionally you would like to be able to add an entry, but we’ll start first by reading an entry to boast the morale. To do this we’ll first need a database. You can download the employees/person database which I’ve used from here:
Download Employees database

This database has the following columns:
id (Auto increment),
fname,
lname,
email,
phone,
company

You can also create your own test database from generatedata.com/, which is a free website service to create 100 records database for you in a flash.

I assume that you know how to import this database in your server/phpmyadmin-MySql.

The general configuration of our CI installation is as follows:

File:
C:\xampp\htdocs\crud_ci\application\config\config.php
Settings:
$config[‘base_url’] = ‘http://localhost/crud_ci’;
$config[‘index_page’] = ”;

File:
C:\xampp\htdocs\crud_ci\application\config\database.php
Settings:
$db[‘default’][‘hostname’] = ‘localhost’;
$db[‘default’][‘username’] = ‘root’;
$db[‘default’][‘password’] = ”;
$db[‘default’][‘database’] = ‘crud_db’;
$db[‘default’][‘dbdriver’] = ‘mysql’;
$db[‘default’][‘dbprefix’] = ”;
$db[‘default’][‘pconnect’] = TRUE;
$db[‘default’][‘db_debug’] = TRUE;
$db[‘default’][‘cache_on’] = FALSE;
$db[‘default’][‘cachedir’] = ”;
$db[‘default’][‘char_set’] = ‘utf8’;
$db[‘default’][‘dbcollat’] = ‘utf8_general_ci’;
$db[‘default’][‘swap_pre’] = ”;
$db[‘default’][‘autoinit’] = TRUE;
$db[‘default’][‘stricton’] = FALSE;

File:
C:\xampp\htdocs\crud_ci\application\config\routes.php
Settings:
$route[‘default_controller’] = “crud”;

File:
C:\xampp\htdocs\crud_ci\.htaccess
Replace the inner content with:

RewriteEngine on
RewriteCond $1 !^(index\.php|assets|img)
RewriteRule ^(.*)$ ./index.php/$1 [L]

Next, open your root folder, open the application folder, open the controllers folder and create a file crud.php . On your local machine, using XAMPP, the path would be like this:
C:\xampp\htdocs\crud_ci\application\controllers\crud.php
Where crud_ci is your root folder.

We’ll first create a class Crud which will extend the class CI_Controller. All of our code will be written in this class. The first function we’ll create is the __construct function and load the files common to all the rest of the functions in this class, so they are readily available for them and we don’t have to load the files every time we create a new function. Check out the code below:

class Crud extends CI_Controller {

	function __construct(){
		parent::__construct();
		$data	= array();
		$this->load->model('crud_model');
		$this->load->helper('url');
	}

Next will be our index function. this is the function which is called when accessing the base url, so we’ll redirect this to show the list of employees from our database, which will be our main view.

public function index()
	{
		redirect('crud/view');
	}

Now, the main function:

//Function to view data in the webpage
	public function view() {

		$dataArr	= array();
		$dataArray	= array();
		$dataArray["empArr"]	=	$this->crud_model->view_data();
		//$this->load->view('crud/view_crud_view', $dataArray); // uncomment this code and comment all below if you don't want to display in the layout

		$dataArr["page_view"] = '';
		$dataArr["page_view"] =	$this->load->view('crud/view_crud_view', $dataArray, true);

		$this->load->view('layout/layout',$dataArr);

	}

As you can see, we’ve called the view_data() function from our crud_model file. Now we’ll create that function. Open your root folder, open the application folder, open the models folder and create a file crud_model.php . On your local machine, using XAMPP, the path would be like this:
C:\xampp\htdocs\crud_ci\application\models\crud_model.php
Where crud_ci is your root folder.

in this crud_model file we’ll create a Crud_model class which will extend the CI_Model class. All the functions would be written in this class. The first being the __construct and then our view_data() function.

class Crud_model extends CI_Model {

	/**
	 * Construct
	 * @access public
	 */
	function __construct() {
		parent::__construct();
	}

	function view_data() {

		$query	=	$this->db->get('employees');
		$result	=	$query->result_array();
		return $result;

	}

The $query variable is to get all the rows and columns of the table employees and then the $result variable will contain the result in an array. We’ll then return this result to the view function in the controller using the return statement. The return statement immediately ends execution of the current function, and returns its argument as the value of the function call.

Now, if you see the view() function in the controller file again, you’ll notice that this array result is associated with the $dataArray[“empArr”]. The named key of an array in the controller is available in the view as a variable. In this case the “empArr” will be available in the view as $empArr. We’ll then add this $dataArray to the $dataArr[“page_view”] array along with the view file for displaying our output. The third parameter is set to “true”, which means that you wish to pass it into the layout as $page_view. Then we’ll load the final view containing our layout and the result of our query using:

$this->load->view('layout/layout',$dataArr);

As you’ll notice, we’ve loaded the view view_crud_view. This will be called in the layout where our main content would be. The other files common to all the app functions are header, sidebar and footer.

Now we’ll create the view file to view our results.

Open your root folder, open the application folder, open the views folder, create a folder named “crud” and create a file view_crud_view.php in it. On your local machine, using XAMPP, the path would be like this:
C:\xampp\htdocs\crud_ci\application\views\crud\view_crud_view.php
Where crud_ci is your root folder.

In the view_crud_view file, copy and paste the following code:

	<table border="1" cellpadding="2" cellspacing="1" style="width:100%; padding:5px;" >
		<thead>
			<tr>
				<td colspan="7" align="right" ><a href="<?php base_url(); ?>add"><button type="button" >Add Data</button></a></td>
			</tr>
			<tr>
				<th>#ID</th>
				<th>First Name</th>
				<th>Last Name</th>
				<th>Email ID</th>
				<th>Phone no.</th>
				<th>Company</th>
				<th>Action</th>
			</tr>
		</thead>
		<tbody>
			<?php /* echo "<pre>"; print_r($empArr); die; */ foreach ($empArr as $val) { ?>
			<tr>
				<td><?php echo $val['id']; ?></td>
				<td><?php echo $val['fname']; ?></td>
				<td><?php echo $val['lname']; ?></td>
				<td><?php echo $val['email']; ?></td>
				<td><?php echo $val['phone']; ?></td>
				<td><?php echo $val['company']; ?></td>
				<td>
					<a href="<?php base_url(); ?>edit?id=<?php echo $val['id']; ?> " ><button type="button" >Edit</button></a>
					<a href="<?php base_url();?>delete?id=<?php echo $val['id']; ?>"><button type="button" >Delete</button></a>
				</td>
			</tr>
			<?php } ?>
		</tbody>
	</table>

As you’ll notice the empArr key is available to us as $empArr array variable. If you want to see what this variable contains, uncomment the code before the foreach loop and reload the page. Make sure you comment it as before when you’ve finished checking it out.

Now, go back to your views folder and create another folder named layout. Open and create the following files in:
layout.php
header.php
sidebar.php
footer.php

in the layout.php file, copy-paste the following code:

<html>
<head>
	<meta charset="utf-8" />
	<title>Basic CRUD in Code Igniter</title>
	<meta content="" name="description" />
	<meta content="" name="author" />
	<!-- BEGIN STYLES -->
	<!-- this demo file dosn't contain any styles, uncomment the below code to link to your stylesheet -->
		<!-- <link href="<?php echo base_url();?>css/styles.css" rel="stylesheet" type="text/css"/> -->
	<!-- END STYLES -->
</head>

<body>
	<div class="main-wrapper" style="width:80%; margin:0px auto;">
		<div class="header" style="background-color:#fff; width:100%; height:15%; float:left;">
			<?php $this->load->view('layout/header'); ?>
		</div>

		<div class="sidebar" style="background-color:#ddd; width:15%; height:100%; float:left;">
			<?php $this->load->view('layout/sidebar'); ?>
		</div>

		<div class="content" style="background-color:#eee; width:85%; height:100%; float:left; overflow:auto;">
			<?php echo $page_view; ?>
		</div>

		<div class="footer" style="background-color:#ccc; width:100%; float:left;">
			<?php $this->load->view('layout/footer'); ?>
		</div>	

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

in the header.php file, copy-paste the following code:

<div class="logo" align="left" style="float:left;">
	<a href="<?php base_url(); ?>view"><img src="../application/images/logo.jpg" height="99" width="342" alt="logo"></a>
</div>

<div class="menu" align="right" style="float:right; margin-right:2%">
	<ul style="list-style-type:none;">
		<li style="display:inline-block;"><a href="<?php base_url(); ?>view">Home</a></li> |
		<li style="display:inline-block;"><a href="<?php base_url(); ?>add">Add Data</a></li>
	</ul>
</div>

In your sidebar.php file, copy-paste the following code:

<ul class="page-sidebar-menu" style="list-style-type:none;">
	<li>
		<a href="<?php base_url(); ?>view">Home</a>
	</li>
	<br/>
	<li>
		<a href="<?php base_url(); ?>add">Add Data</a>
	</li>
</ul>

In your footer.php file, copy-paste the following code:

<p style="margin-left:10%"><?php echo date('Y'); ?> &copy; - For learning purposes only.</p>

The layout part is done and we don’t need to touch it again.

I haven’t used much style or even included a css stylesheet to make it look pleasing. I’m sorry for that but my main motive here is to show you the working of a CRUD application and not user interface development.

If done correctly, you should see something like the below image:

View data

Now, we’ll create the “add” function, which will enable us to add data to the end of this list.

In our crud.php controller file, add the following code:

//Function to add new data into the database
	public function add() {

		$dataArr	= array();
		$dataArray	= array();

		if ($_POST) {

			$dataArray = array(
					'fname' => $this->input->post('first_name'),
					'lname' => $this->input->post('last_name'),
					'email' => $this->input->post('email_id'),
					'phone' => $this->input->post('phone_no'),
					'company' => $this->input->post('company_name')
				);

			$res =	$this->crud_model->add_data($dataArray);
					if ($res) {
						redirect('crud/view');
						die();
					}
					else {
						echo "Error inserting data";
						die();
					}
		}

		//$this->load->view('crud/add_crud_view'); // uncomment this code and comment all below if you don't want to display in the layout

		$dataArr["page_view"] = '';
		$dataArr["page_view"] =	$this->load->view('crud/add_crud_view', $dataArray, true);

		$this->load->view('layout/layout',$dataArr);

	}

Again, we are adding the data which we’ll receive from the add_crud_view.php form into the $dataArray array and then adding this array into the $dataArr[“page_view”] array key, and then finally passing all of it to the layout. The model function we have called here is add_data($data), where $data will be whatever you’ll pass in the add_data() function in the controller, in our case it’s $dataArray.

In our crud_model.php file, add the following code:

function add_data($data) {

		return	$this->db->insert('employees', $data);

	}

We’ll also have to create a corresponding add_crud_view in which we’ll build a form to post data to the controller. In our views folder, open the crud folder and create a file name add_crud_view.php. In this file add the following code:

<form name="add_form" action="<?php base_url(); ?>add" method="post">
		<fieldset style="width:232px;" >
			<legend>Employee Details</legend>
			<table border="1" cellpadding="2" cellspacing="1" >
				<tr>
					<td>First Name:</td>
					<td><input type="text" name="first_name" /></td>
				</tr>
				<tr>
					<td>Last Name:</td>
					<td><input type="text" name="last_name" /></td>
				</tr>
				<tr>
					<td>Email ID:</td>
					<td><input type="email" name="email_id" /></td>
				</tr>
				<tr>
					<td>Phone no.:</td>
					<td><input type="text" name="phone_no" /></td>
				</tr>
				<tr>
					<td>Company:</td>
					<td><input type="text" name="company_name" /></td>
				</tr>
				<tr>
					<td colspan="2" ><a href="<?php base_url(); ?>view"><button style="width:50%;" type="button">Cancel</button></a><input style="width:50%;" type="submit" value="submit" /></td>
				</tr>
			</table>
		</fieldset>
	</form>

That’s it. you are done with the add functionality. When you’ll click on any of the Add Data button, you should see the following screen:

Add Data View

Now we’ll move on to the most important and complex functionality of all, the ‘edit’ of an entry functionality. It’s divided into two tasks. The first task is to take the user to a screen where he/she can edit or alter the details of the selected person and second is to update the database with those altered details.

If you check our view_crud_view file again, you’ll notice that we’ve anchored the Edit button to the url: “edit?id=“. This means that when clicked on a list entry having the id say “1”, we’ll be redirected to the link http://localhost/crud_ci/crud/edit?id=1. Knowing the id of the entry is crucial to display it’s corresponding value sin the edit screen for the user to edit. Now there are many other supposedly secure ways like using form and post, jQuery-AJAX etc to do this rather than getting the id via url, but then I’ll have to change the heading of this tutorial and remove the word “simple” from it. Anyhow, to take the user to the edit screen, first create a. edit() function in the controller i.e. in the crud.php file. Check out the function below:

public function edit() {

		$id=$_GET['id'];

		$dataArray	=	array();

		$output	=	$this->crud_model->edit_data($id);

		$dataArray['id']		=	$id;
		$dataArray['fname']		=	$output['fname'];
		$dataArray['lname']		=	$output['lname'];
		$dataArray['email']		=	$output['email'];
		$dataArray['phone']		=	$output['phone'];
		$dataArray['company']	        =	$output['company'];

		// $this->load->view('crud/edit_crud_view', $dataArray); // uncomment this code and comment all below if you don't want to display in the layout

		$dataArr["page_view"] = '';
		$dataArr["page_view"] =	$this->load->view('crud/edit_crud_view', $dataArray, true);

		$this->load->view('layout/layout',$dataArr);

	}

As you can see, we’ve received the specific id of the person using $_GET Super Global variable $_GET. Then we’ve called our query through the edit_data($id) function from the crud_model. The result of that query has been received in the controller as an array and we’ve assigned that result to the $output variable, which is further assigned to the $dataArray as per their respective key-value relation. Again the $dataArray is assigned to the $dataArr[“page_view”] array and submitted to the layout for final display.

Now, we’ll create the edit_data($id) function in the crud_model.php file and run our query in it to fetch the details of the person corresponding to the id. check out the function below:

function edit_data($id) {

		$this->db->SELECT('fname, lname, email, phone, company');
		$this->db->FROM('employees');
		$this->db->WHERE('id', $id);
		$query = $this->db->get();

		return $query->row_array(); 

	}

The query itself is quite clear. Although the main thing to notice here is that we returned the query to the controller in a row_array(). This is why we haven’t applied the foreach loop in the controller to get the $output values. row_array() returns an single dimension array result i.e. an associative array and result_array() returns double/multiple dimension array result.

If you’ll check the controller file again, we’ve also loaded the edit_crud_view file. this is the view which will display the current values of the person and also allow us to edit them. In your C:\xampp\htdocs\crud_ci\application\views\crud folder, create a file view_crud_view.php and copy-paste the below code into it:

<html>
<body>
<form name="update_form" action="<?php base_url(); ?>update" method="POST">
		<fieldset style="width:232px;" >
			<legend>Employee Details</legend>
			<table border="1" cellpadding="2" cellspacing="1" >
				<tr>
					<td>ID:</td>
					<td><input style="background-color:#eee;" type="text" name="id" value="<?php echo $id ; ?>" readonly /></td>
				</tr>
				<tr>
					<td>First Name:</td>
					<td><input type="text" name="first_name" value="<?php echo $fname; ?>" /></td>
				</tr>
				<tr>
					<td>Last Name:</td>
					<td><input type="text" name="last_name" value="<?php echo $lname; ?>" /></td>
				</tr>
				<tr>
					<td>Email ID:</td>
					<td><input type="email" name="email_id" value="<?php echo $email; ?>" /></td>
				</tr>
				<tr>
					<td>Phone no.:</td>
					<td><input type="text" name="phone_no" value="<?php echo $phone; ?>" /></td>
				</tr>
				<tr>
					<td>Company:</td>
					<td><input type="text" name="company_name" value="<?php echo $company; ?>" /></td>
				</tr>
				<tr>
					<td colspan="2" ><a href="<?php base_url(); ?>view"><button style="width:50%;" type="button">Cancel</button></a><input style="width:50%;" type="submit" value="submit" /></td>
				</tr>
			</table>
		</fieldset>
	</form>
</body>
</html>

It’s clear from the action attribute of the form that the submit will post all these details to the update function in the copntroller, which we’ll create next.

If the above is done correctly, then when clicked on the ‘Edit’ button in our main view with respect to the id say 3, you should see the screen below:

Edit Data Screen

All the fields are editable except the ‘id’ field.

Now, whatever you would’ve edited will be submitted to the update function in the crud.php controller file. Therefore, open your crud.php file, create a update() function in it and copy-paste the following code in it:

//Function to update data into the database
	public function update() {

			if($_POST){

				$id = $this->input->post('id');
				$data = array();
				$data = array(
								'fname' => $this->input->post('first_name'),
								'lname' => $this->input->post('last_name'),
								'email' => $this->input->post('email_id'),
								'phone' => $this->input->post('phone_no'),
								'company' => $this->input->post('company_name'),
							);

				$res	=	$this->crud_model->update_data($id, $data);

				if ($res) {
						redirect('crud/view');
						die();
					}
					else {
						echo "Error inserting data. Please contact system administrator";
						die();
					}
			} 

	}

The update function is also quite simple. We get our id. We also get our edited data and assign it to the respective database fields. And then we pass all this data to the update_data($id, $data) function in our crud_model file. If everything goes well, the user is redirected to the main view.

As aforementioned, we’ll now create the update_data($id, $data) function in our crud_model.php file. Open the file, create update_data($id, $data) and copy-paste the below code:

function update_data($id, $data) {

		$query	=	$this->db->WHERE('id', $id);
		$query 	=	$this->db->UPDATE('employees', $data);
		return $query;
		//return $this->db->update('employees', $data, array('id' => $id)); // optional method to update data in one line as an array; just remove the comment tag in front of 'return'.

	}

That’s it for the complete update functionality. We don’t need any view for the update function as it’s a server side action. The user can check out the updated person record in the main view.

The last functionality we have to achieve is to delete a record from the database through view. If you’ll check our main view one last time, you’ll notice that we’ve anchored the Delete button to the delete function of our crud controller file. Again we’ve passed the corresponding id of the record through the url using the ‘?’ query string, so that our controller will know which id to delete.

In our crud.php controller file, create the function delete_data($id) and copy-paste the below code into it:

//Function to delete data from the database
	function delete() {

		$id = $this->input->get('id');
		$this->crud_model->delete_data($id);

		redirect('crud/view');
	}

In this function we are receiving the id through get method; we could also get using the $_GET Super Global variable but this here is the actual and right way in Code Igniter to write the get method. The id is then passed to the delete_data($id) function in the crud_model.php file, where we’ll rite the query to delete the record. Lastly the user will be redirected to the main view.

Now, in the crud_model.php file we’ll write the last snippet of our code which will conclude our CRUD app. In the crud_model.php model file, create the delete_data($id) function and copy-paste the below code into it:

function delete_data($id) {

		 $this->db->where('id', $id);
		 $this->db->delete('employees');

		// $this->db->delete('employees', array('id' => $id)); // optional method to delete data in one line as an array; just remove the comment tag in front of 'return'.
	}

This concludes this tutorial. I hope my language was easy to understand and not that boring, and that I was able to help anyone learn something new.

You can play around with it after achieving this CRUD functionality, for example find out how to display the confirmation message after the user has added a record, or edited/update a record or deleted it. Try adding pagination or search bar to the main view. If you happen to know jQuery-AJAX, try as much as CRUD functionality using AJAX. Or, at least try giving it a better css 😉

If you have any queries, feedbacks, suggestions etc, feel free to contact me or comment below.

P.S.: You can download the complete CI app folder including the database file from HERE

Thank you.