Introduction to CodeIgniter Basic With CRUD

Introduction to CodeIgniter Basic With CRUD

CodeIgniter (CI) is one of popular php framework. If you are already building PHP Application, CodeIgniter will help you to do it better and more easily. With CodeIgniter, you can save time, make your web more robust, your code will be easier to read and maintenance. It is free, lightweight, and simple to install. In this post, we will know more deep about CodeIgniter before write code.
Nice, CodeIgniter is small and lightweight framework. You don’t need long time to download it. You can get it from http://www.codeigniter.com. CI was written by Rick Ellis, rock musician turned programmer.
With CodeIgniter, you can cut down the amount of code you need to type. This is not just good for lazy, but: less type, fewer mistake, and less time for spend debugging.
But, CodeIgniter is not everything. We will not find ‘engine generator’ that can build page self. Several frameworks have features like that. For example, they can create web page (that to do basic Create, Read, Update, and Delete operation) automatically. CodeIgniter doesn’t do this.
This, I copy from their help page: “Our goal for CodeIgniter is maximum performance, capability, and flexibility in the smallest, lightest possible package.
From a technical and architectural standpoint, CodeIgniter was created with the following objectives:

  • Dynamic Instantiation. In CodeIgniter, components are loaded and routines executed only when requested, rather than globally. No assumptions are made by the system regarding what may be needed beyond the minimal core resources, so the system is very light-weight by default. The events, as triggered by the HTTP request, and the controllers and views you design will determine what is invoked.
  • Loose Coupling. Coupling is the degree to which components of a system rely on each other. The fewer components depend on each other the more reusable and flexible the system becomes. Our goal was a very loosely coupled system.
  • Component Singularity. Singularity is the degree to which components have a narrowly focused purpose. In CodeIgniter, each class and its functions are highly autonomous in order to allow maximum usefulness.

Nice feature, CodeIgniter is very flexible. We can apply at PHP 4.3.2 and above, or PHP 5.0 or above. CI support serveral database: MySQL, MySQLi, MS SQL, Postgre, Oracle, SQLite, and ODBC.
Ok, now, we will learn how to install CodeIgniter.
For this series i’ll be using the latest version of CodeIgniter at the time of writing; 2.10.
Installation
1. Head over to the CodeIgniter website http://codeigniter.com/ and download the source.
2. Extract the CodeIgniter files into an appropriate folder on your web server. if you want to work locally, use WAMP, MAMP or XAMPP.
3. Open your installation in a web browser and you should get the screen below.
CodeIgniter Basic Installation
Create your First Application with CodeIgniter
As usually, we will create first application by build hello application. But, before write code, we must know that we will build application use Model Controller View (MVC) pattern. First, we make controller, create a file name “hello.php” within: CodeIgniter \application\controllers. Enter following code:

<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
class Hello extends CI_Controller{
function __construct(){
parent::__construct();
}
function you(){
$this->load->view('you_view');
}
}
?>
  • · Next step, make a view. Create you_view.php within codeigniter\ application\views. Enter just simple line code like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>My First CodeIgniter Practice</title>
 </head>
 <body>
 <h1> HELLO CI Buddy...!</h1>
 </body>
 </html>

Now, test your application. Point your browser to http://localhost/codeigniter/index.php/Hello/you You should get like this:
First CodeIgniter
See, this flow:
first codeigniter controller

Creating and Sending Parameters between Controller and View

Now we will build controller and view better. Create parameters in controller and send it to view. It will make our application more flexible.

  1. Create a file name hello2.php within codeigniter/application/controller. write become like this:
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
class Hello2 extends CI_Controller{
// declare variables or class properties
var $name;
var $color;
function __construct(){
parent::__construct();
// give default value
$this->name="Abir";
$this->color="red";
}
function you(){
$data['name']=$this->name;
$data['color']=$this->color;
// define variable sent to views
$this->load->view('you_view2',$data);
}
}
?>
  1. Next step, make a view. Create you_view2.php within codeigniter\ application\views. Enter just simple line code like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My First CodeIgniter Practice</title>
</head>
<body>
<h1 style="color:<?php echo $color; ?>"> Hello <?php echo $name; ?>!</h1>
</body>
</html>

Point your browser to http://localhost/codeigniter/index.php/hello2/you.
Creating and Sending Parameters between Controller and View

Getting Parameters from GET

Now, we will learn how to get parameter from GET. As we know, we can see this parameter from Url. Example: http://localhost/index.php?name=Andi. Clear, we can get parameter name. How about in CodeIgniter?

  1. Ok, we learn by doing. Create a file name hello3.php within codeigniter//application/controller. write become like this:
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
class Hello3 extends CI_Controller{
// declare variables or class properties
var $name;
var $color;
function __construct(){
parent::__construct();
// give default value
$this->name="Faisal";
$this->color="red";
}
function you($firstname='', $lastname='')// Give variable that can GET value
{
$data['name']=($firstname)?$firstname.' '.$lastname:$this->name;
$data['color']=$this->color;
// define variable sent to views
$this->load->view('you_view2',$data);
}
}
?>

Now, try point your browser to http://localhost/codeigniter/index.php/hello3/you/Masud/Alam
Getting Parameters from GET

Setting Base Url Configuration

Please, open config.php within codeigniter\application\config. Set config like below:

CodeIgniter Configuration

Setting Database Configuration

Please, open database.php within codeigniter\application\config. Set config like below:

CodeIgniter Database settings

Make sure, it matches with your database.

Preparing Database

We will learn about showing data from database in CodeIgniter. But, before that, we prepare a database for practice. This post create a database named “ci_test” and a table named “users”. We use phpMyAdmin for easy.

  1. Open your phpmyadmin.
  2. Enter database name “ci_test” in create new database field.
  3. Click Create button. Your database will be created.
  4. Create new table by running this query in your sql window:

CREATE TABLE IF NOT EXISTS `users` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(50) NOT NULL,

`email` varchar(100) NOT NULL,

`address` varchar(255) NOT NULL,

`mobile` varchar(15) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;

  1. Insert some sample data to your users table by running this query in your sql window:

INSERT INTO `users` (`id`, `name`, `email`, `address`, `mobile`) VALUES

(1, 'Masud Alam', 'm@sud.com', 'ldsjfla lsdj lsdj flk', '9879879'),

(2, 'Sohel Alam', 'al@m.com', 'Dhaka,Bangladesh,BD', '09080'),

(8, 'Salim', 'salim.hossain@ebizzsol.com', 'test', '01717552181'),

(9, 'Syed Salim', 'salimhossain@gmail.com', 'Gulshan, Dhaka', '01717552181'),

(10, 'Salim Hossain', 'salimhossain@gmail.com', 'Gazipur-1700, Dhaka, Bangladesh.', '01717552181'),

(13, 'Galib', 'g@lib.com', 'Dhaka,Bangladesh', '987979');

Showing All Data from your users table:

Now, we learn how to show data in CodeIgniter. As we know, CodeIgniter use MVC pattern. We will use Model for retrieve data from database.

First, build a model. Create a file named “users_model.php” within codeigniter/application/models. Enter following code:


<?php

class Users_model extends CI_Model {

function __construct()

{

parent::__construct();

$this->load->database("ci_test");

}

public function get_all_users()

{

$query = $this->db->get('users');

return $query->result();

}

}

?>

Next, we make a view. Create a file named “show_users.php” within ci/application/views. Enter folowing code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>CI CRUD</title>

</head>

<body>

<h2> Simple CI CRUD Application </h2>

<table width="600" border="1" cellpadding="5">

<tr>

<th scope="col">Id</th>

<th scope="col">User Name</th>

<th scope="col">Email</th>

<th scope="col">Mobile</th>

<th scope="col">Address</th>

</tr>

<?php foreach ($user_list as $u_key){ ?>

<tr>

<td><?php echo $u_key->id; ?></td>

<td><?php echo $u_key->name; ?></td>

<td><?php echo $u_key->email; ?></td>

<td><?php echo $u_key->address; ?></td>

<td><?php echo $u_key->mobile; ?></td>

</tr>

<?php }?>

</table>

</body>

</html>

Build controller. Create a file named “users.php” within codeigniter\application\controllers. Enter following code:


<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {

function __construct()

{

parent::__construct();

#$this->load->helper('url');

$this->load->model('users_model');

}

public function index()

{

$data['user_list'] = $this->users_model->get_all_users();

$this->load->view('show_users', $data);

}

}

Now, try to point your browser to http://localhost/codeigniter/index.php/users/

Show Data with CodeIgniter

Now, we will add links for insert, edit, and delete links for create our crud system. We use URL Helper to build the links.

Update show_users.php (views) with following code :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>CI CRUD</title>

<script type="text/javascript">

function show_confirm(act,gotoid)

{

if(act=="edit")

var r=confirm("Do you really want to edit?");

else

var r=confirm("Do you really want to delete?");

if (r==true)

{

window.location="<?php echo base_url();?>index.php/users/"+act+"/"+gotoid;

}

}

</script>

</head>

<body>

<h2> Simple CI CRUD Application </h2>

<table width="600" border="1" cellpadding="5">

<tr>

<th scope="col">Id</th>

<th scope="col">User Name</th>

<th scope="col">Email</th>

<th scope="col">Mobile</th>

<th scope="col">Address</th>

<th scope="col" colspan="2">Action</th>

</tr>

<?php foreach ($user_list as $u_key){ ?>

<tr>

<td><?php echo $u_key->id; ?></td>

<td><?php echo $u_key->name; ?></td>

<td><?php echo $u_key->email; ?></td>

<td><?php echo $u_key->address; ?></td>

<td><?php echo $u_key->mobile; ?></td>

<td width="40" align="left" ><a href="#" onClick="show_confirm('edit',<?php echo $u_key->id;?>)">Edit</a></td>

<td width="40" align="left" ><a href="#" onClick="show_confirm('delete',<?php echo $u_key->id;?>)">Delete </a></td>

</tr>

<?php }?>

<tr>

<td colspan="7" align="right"> <a href="<?php echo base_url();?>index.php/user/add_form">Insert New User</a></td>

</tr>

</table>

</body>

</html>

Now Again try to point your browser to http://localhost/codeigniter/index.php/users/

Codeigniter Crud with Actions

Insert Data to our database using CodeIgniter

Now, we begin create a form for input data.

Create “insert.php” within codeigniter\application\views. Write following code:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>CI Insert Form</title>

</head>

<body>

<form method="post" action="<?php echo base_url();?>index.php/users/insert_user_db">

<table width="400" border="0" cellpadding="5">

<tr>

<th width="213" align="right" scope="row">Enter your username</th>

<td width="161"><input type="text" name="name" size="20" /></td>

</tr>

<tr>

<th align="right" scope="row">Enter your email</th>

<td><input type="text" name="email" size="20" /></td>

</tr>

<tr>

<th align="right" scope="row">Enter your Mobile</th>

<td><input type="text" name="mobile" size="20" /></td>

</tr>

<tr>

<th align="right" scope="row">Enter Your Address</th>

<td><textarea name="address" rows="5" cols="20"></textarea></td>

</tr>

<tr>

<th align="right" scope="row">&nbsp;</th>

<td><input type="submit" name="submit" value="Send" /></td>

</tr>

</table>

</form>

</body>

</html>

Now, we need to load Insert Form. Put at controller (users.php within codeigniter/application/controllers), add_form () method.


public function add_form()

{

$this->load->view('insert');

}

Now for insert data from our insert.php form to users table we need to create another method called insert_user_db() in our controllers with following code:

public function insert_new_user()

{

$udata['name'] = $this->input->post('name');

$udata['email'] = $this->input->post('email');

$udata['address'] = $this->input->post('address');

$udata['mobile'] = $this->input->post('mobile');

$res = $this->users_model->insert_users_to_db($udata);

if($res){

header('location:'.base_url()."index.php/users/".$this->index());

}

}

Now add new method insert_users_to_db in your models

public function insert_users_to_db($data)

{

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

}

Now, click your “Insert New User” link in your browser , you see your insert form like this:

CodeIgniter Insert Form

Ok. You can test it. Input some data to your insert form .

CodeIgniter Insert Form with sample data

Now, we create a method called getById() to get a single user information at our model

public function getById($id){
$query = $this->db->get_where('users',array('id'=>$id));
return $query->row_array();
}

After Create getById Method in our users_model, Now We Create edit Method to send a single user information to edit.php form as follows:

public function edit(){
$id = $this->uri->segment(3);
 $data['user'] = $this->users_model->getById($id);
$this->load->view('edit', $data);
}

Now we create edit.php form for update users:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>CI Insert Form</title>

</head>

<body>

<form method="post" action="<?php echo base_url();?>index.php/users/update">
<?php
extract($user);
?>
<table width="400" border="0" cellpadding="5">

<tr>

<th width="213" align="right" scope="row">Enter your username</th>

<td width="161"><input type="text" name="name" size="20" value="<?php echo $name; ?>" /></td>

</tr>

<tr>

<th align="right" scope="row">Enter your email</th>

<td><input type="text" name="email" size="20" value="<?php echo $email; ?>" /></td>

</tr>

<tr>

<th align="right" scope="row">Enter your Mobile</th>

<td><input type="text" name="mobile" size="20" value="<?php echo $mobile; ?>" /></td>

</tr>

<tr>

<th align="right" scope="row">Enter Your Address</th>

<td><textarea name="address" rows="5" cols="20"><?php echo $address; ?></textarea></td>

</tr>

<tr>

<th align="right" scope="row">&nbsp;</th>

<td>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="submit" name="submit" value="Update" /></td>

</tr>

</table>

</form>

</body>

</html>

After create edit form, now we add updating function.

First, create update_info () method at model “users_model.php”.


public function update_info($data,$id)

{

$this->db->where('users.id',$id);

return $this->db->update('users', $data);

}

Then, create update() method at your controller “users.php”:

public function update()

{

$mdata['name']=$_POST['name'];

$mdata['email']=$_POST['email'];

$mdata['address']=$_POST['address'];

$mdata['mobile']=$_POST['mobile'];

$res=$this->users_model->update_info($mdata, $_POST['id']);

if($res){

header('location:'.base_url()."index.php/users/".$this->index());

}

}

Deleting Data

Now, we create deleting function.

First, create a method delete_a_user() for deleting data at model.


public function delete_a_user($id)

{

$this->db->where('users.id',$id);

return $this->db->delete('users');

}

Then, create a method for deleting data at controller:

public function delete($id)

{

$this->users_model->delete_a_user($id);

$this->index();

}

Delete with CodeIgniter

Download

47 comments on “Introduction to CodeIgniter Basic With CRUD
  1. Thank you very much for this. It really helped me a lot. However, I can’t seem to make the insert new user and the edit work. I really have no idea what to do since I am still new with codeigniter. T_T

  2. Thank you Masud vai, thanks lots, it helpful for me. I need your help. please let me know your email or cell number. i want to learn more from you.

  3. Every weekend i used to pay a quick visit this website,
    because i wish for enjoyment, since this this web
    site conations genuinely pleasant funny data too.

  4. I have try but when in step loading data is error, appear in screen ”

    A Database Error Occurred
    Error Number: 1046
    No database selected
    SELECT * FROM (`users`)
    Filename: C:\xampp\htdocs\blog_ci\system\database\DB_driver.php

    what’s problem?

    Line Number: 330

  5. Mr. Masud Alam,

    I would like to put a very very special thanks for such a nice tutorial. Hope we can get more assistance from you by such a work….thank you once again.

    Firoz.

  6. I tried your code but this is what happens
    A PHP Error was encountered

    Severity: Notice

    Message: Undefined variable: user_list

    Filename: views/show_users.php

    Line Number: 19

    please advice, thanks

  7. I wondered to see it’s really a nice and fully functional post about the process of CI. It’s helped me a lot. Thank you

  8. I tried your code but this is what happens
    A PHP Error was encountered

    Severity: Notice

    Message: Undefined variable: user_list

    Filename: views/show_users.php

    Line Number: 19

    inform me plzzzzzzzzzzzz allotttt

  9. thank you soooooo much i will book mark your site so that i will help in google ranking ….. i found two errors and i fixed it and code is working very fine

  10. In regard to “they can create web page (that to do basic Create, Read, Update, and Delete operation) automatically. CodeIgniter doesn’t do this.”, can you please name these platform, if possible, of course.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>