Introduction to CodeIgniter Basic With CRUD

  CodeIgniter, PHP, Xampp

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:

1 <?php
2 if(!defined('BASEPATH')) exit('No direct script access allowed');
3 class Hello extends CI_Controller{
4 function __construct(){
5 parent::__construct();
6 }
7 function you(){
8 $this->load->view('you_view');
9 }
10 }
11 ?>
  • · Next step, make a view. Create you_view.php within codeigniter\ application\views. Enter just simple line code like:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2  <html xmlns="http://www.w3.org/1999/xhtml">
3  <head>
4  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5  <title>My First CodeIgniter Practice</title>
6  </head>
7  <body>
8  <h1> HELLO CI Buddy...!</h1>
9  </body>
10  </html>

Now, test your application. Point your browser tohttp://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:
1 <?php
2 if(!defined('BASEPATH')) exit('No direct script access allowed');
3 class Hello2 extends CI_Controller{
4 // declare variables or class properties
5 var $name;
6 var $color;
7 function __construct(){
8 parent::__construct();
9 // give default value
10 $this->name="Abir";
11 $this->color="red";
12 }
13 function you(){
14 $data['name']=$this->name;
15 $data['color']=$this->color;
16 // define variable sent to views
17 $this->load->view('you_view2',$data);
18 }
19 }
20 ?>
  1. Next step, make a view. Create you_view2.php within codeigniter\ application\views. Enter just simple line code like:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>My First CodeIgniter Practice</title>
6 </head>
7 <body>
8 <h1 style="color:<?php echo $color; ?>"> Hello <?php echo $name; ?>!</h1>
9 </body>
10 </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:
1 <?php
2 if(!defined('BASEPATH')) exit('No direct script access allowed');
3 class Hello3 extends CI_Controller{
4 // declare variables or class properties
5 var $name;
6 var $color;
7 function __construct(){
8 parent::__construct();
9 // give default value
10 $this->name="Faisal";
11 $this->color="red";
12 }
13 function you($firstname='', $lastname='')// Give variable that can GET value
14 {
15 $data['name']=($firstname)?$firstname.' '.$lastname:$this->name;
16 $data['color']=$this->color;
17 // define variable sent to views
18 $this->load->view('you_view2',$data);
19 }
20 }
21 ?>

Now, try point your browser tohttp://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:
1 CREATE TABLE IF NOT EXISTS `users` (
2
3 `id` int(11) NOT NULL AUTO_INCREMENT,
4
5 `name` varchar(50) NOT NULL,
6
7 `email` varchar(100) NOT NULL,
8
9 `address` varchar(255) NOT NULL,
10
11 `mobile` varchar(15) NOT NULL,
12
13 PRIMARY KEY (`id`)
14
15 ) 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:
1 INSERT INTO `users` (`id`, `name`, `email`, `address`, `mobile`) VALUES
2
3 (1, 'Masud Alam', 'm@sud.com', 'ldsjfla lsdj lsdj flk', '9879879'),
4
5 (2, 'Sohel Alam', 'al@m.com', 'Dhaka,Bangladesh,BD', '09080'),
6
7 (8, 'Salim', 'salim.hossain@ebizzsol.com', 'test', '01717552181'),
8
9 (9, 'Syed Salim', 'salimhossain@gmail.com', 'Gulshan, Dhaka','01717552181'),
10
11 (10, 'Salim Hossain', 'salimhossain@gmail.com', 'Gazipur-1700, Dhaka, Bangladesh.', '01717552181'),
12
13 (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:

1 <?php
2
3 class Users_model extends CI_Model {
4
5 function __construct()
6
7 {
8
9 parent::__construct();
10
11 $this->load->database("ci_test");
12
13 }
14
15 public function get_all_users()
16
17 {
18
19 $query = $this->db->get('users');
20
21 return $query->result();
22
23 }
24
25 }
26
27 ?>

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

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
3 <html xmlns="http://www.w3.org/1999/xhtml">
4
5 <head>
6
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
8
9 <title>CI CRUD</title>
10
11 </head>
12
13 <body>
14
15 <h2> Simple CI CRUD Application </h2>
16
17 <table width="600" border="1" cellpadding="5">
18
19 <tr>
20
21 <th scope="col">Id</th>
22
23 <th scope="col">User Name</th>
24
25 <th scope="col">Email</th>
26
27 <th scope="col">Mobile</th>
28
29 <th scope="col">Address</th>
30
31 </tr>
32
33 <?php foreach ($user_list as $u_key){ ?>
34
35 <tr>
36
37 <td><?php echo $u_key->id; ?></td>
38
39 <td><?php echo $u_key->name; ?></td>
40
41 <td><?php echo $u_key->email; ?></td>
42
43 <td><?php echo $u_key->address; ?></td>
44
45 <td><?php echo $u_key->mobile; ?></td>
46
47 </tr>
48
49 <?php }?>
50
51 </table>
52
53 </body>
54
55 </html>

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

1 <?php
2
3 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
4
5 class Users extends CI_Controller {
6
7 function __construct()
8
9 {
10
11 parent::__construct();
12
13 #$this->load->helper('url');
14
15 $this->load->model('users_model');
16
17 }
18
19 public function index()
20
21 {
22
23 $data['user_list'] = $this->users_model->get_all_users();
24
25 $this->load->view('show_users', $data);
26
27 }
28
29 }

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 :

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
3 <html xmlns="http://www.w3.org/1999/xhtml">
4
5 <head>
6
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
8
9 <title>CI CRUD</title>
10
11 <script type="text/javascript">
12
13 function show_confirm(act,gotoid)
14
15 {
16
17 if(act=="edit")
18
19 var r=confirm("Do you really want to edit?");
20
21 else
22
23 var r=confirm("Do you really want to delete?");
24
25 if (r==true)
26
27 {
28
29 window.location="<?php echo base_url();?>index.php/users/"+act+"/"+gotoid;
30
31 }
32
33 }
34
35 </script>
36
37 </head>
38
39 <body>
40
41 <h2> Simple CI CRUD Application </h2>
42
43 <table width="600" border="1" cellpadding="5">
44
45 <tr>
46
47 <th scope="col">Id</th>
48
49 <th scope="col">User Name</th>
50
51 <th scope="col">Email</th>
52
53 <th scope="col">Mobile</th>
54
55 <th scope="col">Address</th>
56
57 <th scope="col" colspan="2">Action</th>
58
59 </tr>
60
61 <?php foreach ($user_list as $u_key){ ?>
62
63 <tr>
64
65 <td><?php echo $u_key->id; ?></td>
66
67 <td><?php echo $u_key->name; ?></td>
68
69 <td><?php echo $u_key->email; ?></td>
70
71 <td><?php echo $u_key->address; ?></td>
72
73 <td><?php echo $u_key->mobile; ?></td>
74
75 <td width="40" align="left" ><a href="#" onClick="show_confirm('edit',<?php echo $u_key->id;?>)">Edit</a></td>
76
77 <td width="40" align="left" ><a href="#" onClick="show_confirm('delete',<?php echo $u_key->id;?>)">Delete </a></td>
78
79 </tr>
80
81 <?php }?>
82
83 <tr>
84
85 <td colspan="7" align="right"> <a href="<?php echo base_url();?>index.php/user/add_form">Insert New User</a></td>
86
87 </tr>
88
89 </table>
90
91 </body>
92
93 </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:

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
3 <html xmlns="http://www.w3.org/1999/xhtml">
4
5 <head>
6
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
8
9 <title>CI Insert Form</title>
10
11 </head>
12
13 <body>
14
15 <form method="post" action="<?php echo base_url();?>index.php/users/insert_user_db">
16
17 <table width="400" border="0" cellpadding="5">
18
19 <tr>
20
21 <th width="213" align="right" scope="row">Enter your username</th>
22
23 <td width="161"><input type="text" name="name" size="20" /></td>
24
25 </tr>
26
27 <tr>
28
29 <th align="right" scope="row">Enter your email</th>
30
31 <td><input type="text" name="email" size="20" /></td>
32
33 </tr>
34
35 <tr>
36
37 <th align="right" scope="row">Enter your Mobile</th>
38
39 <td><input type="text" name="mobile" size="20" /></td>
40
41 </tr>
42
43 <tr>
44
45 <th align="right" scope="row">Enter Your Address</th>
46
47 <td><textarea name="address" rows="5" cols="20"></textarea></td>
48
49 </tr>
50
51 <tr>
52
53 <th align="right" scope="row">&nbsp;</th>
54
55 <td><input type="submit" name="submit" value="Send" /></td>
56
57 </tr>
58
59 </table>
60
61 </form>
62
63 </body>
64
65 </html>

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

1 public function add_form()
2
3 {
4
5 $this->load->view('insert');
6
7 }

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:

1 public function insert_new_user()
2
3 {
4
5 $udata['name'] = $this->input->post('name');
6
7 $udata['email'] = $this->input->post('email');
8
9 $udata['address'] = $this->input->post('address');
10
11 $udata['mobile'] = $this->input->post('mobile');
12
13 $res = $this->users_model->insert_users_to_db($udata);
14
15 if($res){
16
17 header('location:'.base_url()."index.php/users/".$this->index());
18
19 }
20
21 }

Now add new method insert_users_to_db in your models

1 public function insert_users_to_db($data)
2
3 {
4
5 return $this->db->insert('users', $data);
6
7 }

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

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

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:

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

Now we create edit.php form for update users:

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2
3 <html xmlns="http://www.w3.org/1999/xhtml">
4
5 <head>
6
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
8
9 <title>CI Insert Form</title>
10
11 </head>
12
13 <body>
14
15 <form method="post" action="<?php echo base_url();?>index.php/users/update">
16 <?php
17 extract($user);
18 ?>
19 <table width="400" border="0" cellpadding="5">
20
21 <tr>
22
23 <th width="213" align="right" scope="row">Enter your username</th>
24
25 <td width="161"><input type="text" name="name" size="20" value="<?php echo $name; ?>" /></td>
26
27 </tr>
28
29 <tr>
30
31 <th align="right" scope="row">Enter your email</th>
32
33 <td><input type="text" name="email" size="20" value="<?php echo $email; ?>" /></td>
34
35 </tr>
36
37 <tr>
38
39 <th align="right" scope="row">Enter your Mobile</th>
40
41 <td><input type="text" name="mobile" size="20" value="<?php echo $mobile; ?>" /></td>
42
43 </tr>
44
45 <tr>
46
47 <th align="right" scope="row">Enter Your Address</th>
48
49 <td><textarea name="address" rows="5" cols="20"><?php echo $address; ?></textarea></td>
50
51 </tr>
52
53 <tr>
54
55 <th align="right" scope="row">&nbsp;</th>
56
57 <td>
58 <input type="hidden" name="id" value="<?php echo $id; ?>" />
59 <input type="submit" name="submit" value="Update" /></td>
60
61 </tr>
62
63 </table>
64
65 </form>
66
67 </body>
68
69 </html>

After create edit form, now we add updating function.

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

1 public function update_info($data,$id)
2
3 {
4
5 $this->db->where('users.id',$id);
6
7 return $this->db->update('users', $data);
8
9 }

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

1 public function update()
2
3 {
4
5 $mdata['name']=$_POST['name'];
6
7 $mdata['email']=$_POST['email'];
8
9 $mdata['address']=$_POST['address'];
10
11 $mdata['mobile']=$_POST['mobile'];
12
13 $res=$this->users_model->update_info($mdata, $_POST['id']);
14
15 if($res){
16
17 header('location:'.base_url()."index.php/users/".$this->index());
18
19 }
20
21 }

Deleting Data

Now, we create deleting function.

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

1 public function delete_a_user($id)
2
3 {
4
5 $this->db->where('users.id',$id);
6
7 return $this->db->delete('users');
8
9 }

Then, create a method for deleting data at controller:

1 public function delete($id)
2
3 {
4
5 $this->users_model->delete_a_user($id);
6
7 $this->index();
8
9 }

Delete with CodeIgniter

LEAVE A COMMENT