Codeigniter Tutorial for Beginners [Best Practice]

Codeigniter Tutorial for Beginners [Best Practice]

I completely understand your anxiety when starting learn codeigniter.

Confused, what have to know, and don't know start from where.

The good news,

In this tutorial, I will share with you how to start learning codeigniter from the scratch.

Step by step.

if you are a beginner. You will love this tutorial.

Let’s dive right in.

 

1. Overview

Codeigniter is a Web Application Framework (WAF) designed specifically to facilitate web developers in developing web-based applications.

Codeigniter contains a collection of code in the form of libraries and tools combined into a framework.

Codeigniter is a web framework for the PHP programming language designed by Rick Ellis in 2006, founder of EllisLab.

Ellislab is a working team founded in 2002 and is engaged in software development and tools for web developers.

Since 2014 until now, EllisLab has awarded codeigniter ownership rights to the British Columbia Institute of Technology (BCIT) for further development process.

Codeigniter has many features (facilities) that help PHP developers to be able to make web applications easily and quickly.

Codeigniter has a simpler design and flexible.

Codeigniter allows web developers to use the framework partially or as a whole.

It's means that codeigniter still gives freedom to the developer to write certain parts of the code inside the app using the conventional way.

Codeigniter use the Model-View-Controller (MVC) design or architecture pattern that separates the code portion for business process handling with code sections for presentation purposes.

By using this design pattern, it allows web development to work on web-based applications together (teamwork).

That way the web developers are more focused on their respective parts without disturbing the other part.

So that the built application will be completed faster.

 

2. Codeigniter Advantages

Codeigniter is a toolkit devoted to you who want to build web based applications in PHP programming language.

The advantages offered by codeigniter are as follows:

1. Codeigniter is an open-source PHP framework.

2. Codeigniter has a small size compared to other frameworks. After the installation process, the Codeigniter framework is only about 2 MB.

3. Applications created using codeigniter can run fast.

4. Codeigniter uses a Model-View-Controller (MVC) design pattern so that one file does not contain too much code. This makes the code easier to read, understand, and maintain later on.

5. Codeigniter can be expanded as needed.

6. Codeigniter well-documented information about libraries and functions provided by codeigniter can be obtained through the documentation included in the distribution package.

7. Codeigniter has a complete library and helper.

8. Codeigniter has reliable security such as xss filtering, session encryption, and others.

9. Codeigniter allows web developers to use libraries or helper not provided by codeigniter like: Google Map API, Facebook API, fpdf, and others.

10. Codeigniter is flexible. So that giving freedom to web developers to develop web-based applications even without framework.

11. Codeigniter has a large community and spread all over the world, making it easier for web developers to solve problems faced by web developers in developing web-based applications.

12. Codeigniter support many RDBMS (Relational Database Management System) like MySQL, SQL Server, Oracle, Maria DB, PostgreSQL, SQLite, and others.  

13. Codeigniter basically embraces Clean URL and supports SEO (Search Engine Optimazation). So that, the application built using codeigniter is easier to index by popular search engines like google, yahoo, msn, and others.

 

3. Model-View-Controller (MVC)

mvc

As I mentioned earlier that the codeigniter adopts the Model-View-Controller (MVC) architecture.

So, It is very important for you to know the concept of MVC.

What is Model-View-Controller (MVC)?

MVC is a method to separate applications into three parts. Model, View, and Controller.

MVC making the structure to the application, so it can achieve "code reusability".

Here is an explanation about MVC:

1. Model

Models represent data that applications use, such as databases, RSS, or data obtained from API calls, and actions that involve the Create, Read, Update, and Delete operations.

2. View

View is the information displayed to the user through the browser. Usually in the form of HTML file or PHP code that compile template for a website.

In the codeigniter, the view can be parts of a page, template, or other types of pages or templates.

3. Controller

Controller is a "business logic" that served as a bridge between the model and view.

The controller will respond to HTTP requests coming from the user (via browser), from this request the controller will determine what to do.

In the codeigniter, in detail MVC is described as follows:

mvc codeigniter

In the picture above, the file "index.php" acts as the main controller that invokes the basic functions used to run the controller.

The router checks the HTTP request and then decides which Controller will be used to handle the request.

If the cache file is available, the application flow will be skipped and the cache file will be sent to the user's browser.

Before the controller is invoked, HTTP requests and user-submitted data will be first sorted for security reasons.

The controller calls the Model, Library, Helper, and other files needed to handle HTTP requests.

The end result will be displayed by the View file then sent to the user's browser to display.

If caching mode is enabled, the results of the view will be cached first.

So if later there is the same request, can be directly used.

 

4. Installing Codeigniter

Codeigniter is a PHP framework that the simplest way of installing than any other PHP framework.

You just need to extract it to your web server and install complete.

Easy right?

If you want to install codeigniter on localhost, there are some software that you can use.

Among the most popular are WAMPSERVER, MAMP, or XAMPP.

You can choose one of them.

Here I use WAMPSERVER, if you also use wampserver you will love this article.

But, if you use XAMPP.

No Problem,

Because I will show how to install on WAMP and XAMPP.

Alright, to install codeigniter. you can follow these steps below:

1.  Make sure Web Server is installed and running on your computer.

2.  Download codeigniter file on the official website: www.codeigniter.com

3.  Extract Codeigniter.zip to directory C:/wamp/www/ (if you use wampserver). But, if you use XAMPP. Extract Codeigniter.zip to directory C:/xampp/htdocs/.

4.  Go to  C:/wamp/www/ (If you using WAMP) and rename codeigniter folder you just extract to be your project name.

For example, here I rename to be "myproject". So it looks like the picture below:

project name

5.  Next, open your browser. here I use Mozilla Firefox. Then visit the URL below:

http://localhost/myproject/

If the installation is successful, it will look like the picture below:

Codeigniter Welcome Page

 

5. Codeigniter Basic Configuration

In starting the codeigniter, there are some basic configurations you need to know.

That is autoload.php, config.php, and database.php.

All configurations on codeigniter, located in one place that is inside the folder application/config.

Config Folder

How and what needs to be configured in autoload.php, config.php, and database.php files?

Here's the explanation.

1. Autoload.php

Autoload.php, this file is used to set the functions that will be automatically loaded at the beginning when the program is run.

To configure the autoload.php file, please open the folder:

application/config/autoload.php

like the picture below:

autoload

There are several things that can be loaded automatically include: packages, libraries, drivers, helper files, custom config files, language files, and models.  

For basic configuration you need to know are libraries and helper files.

It aims to have certain libraries and helper run automatically.

To configure the libraries, open the autoload.php file with a text editor such as notepad++, sublime text, or others.

And then find the code below:

$autoload['libraries'] = array();

Set to be like this:

$autoload['libraries'] = array('database');

In the above code, it means we load the library "database" automatically.

Thus you can use database functions on codeigniter.

Like function: Query Builder Class

Next, to configure the helper files, open the autoload.php file with the text editor.

And then find the code below:

$autoload['helper'] = array();

And set to be like this:

$autoload['helper'] = array('url');

In the above code, it means we load the "url" helper automatically.

Thus you can use the url functions on the codeigniter.

Like function: base_url (), site_url (), URI Segment, and others.

2. Config.php

In this file there are some configurations that have been configured by default.

But there are several configurations that need to be considered that is:

$config['base_url']
$config['index_page']
$config['encryption_key']

For basic configuration, you just need to know the base_url configuration

Base_url is the basic url of your project.

To configure base_url, open the config.php file with a text editor.

Config

And then find the code below:

$config['base_url'] = '';

And set to be like this:

$config['base_url'] = 'http://localhost/myproject/';

3. Database.php

Judging from the name of file then you can already capture what the function of this file.

The database.php file is used to configure the database configuration of the website to be created.

The configuration to note are: hostname, username, password, and database.

To configure database.php. Open the database.php file with a text editor.

database config

And then find the code below:

$active_group = 'default';
$query_builder = TRUE;

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

And set to be like this:

$active_group = 'default';
$query_builder = TRUE;

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

 

6. Hello World Codeigniter

If you are serious with codeigniter, you should understand how a controller works.

For more details, I am going to share a simple case so you can understand how the controller works.

Here I raised the case that is how to display text "Hello World" in browser using controller.

Let’s dive right in.

Create a controller named Hello.php like the following picture:

Hello Controller

Then type the code below:

<?php
class Hello extends CI_Controller{

  function index(){
      echo "Hello World";
  }

}

Note: Every writing of filenames and class names is always preceded by Capital letters.

After that save and open your browser, then visit the following url:

http://localhost/myproject/index.php/hello

Then will be seen text "Hello World" in your browser as follows:

Hello World

If you look carefully, basically the url on the codeigniter looks like the following picture:

Codeigniter URL

Where, there are protocol, primary domain, index.php, class name, and function name.

It may sound complicated, but it is not.

For more details please add one more function to Controller Hello.php. here I give the name "show".

So the Hello.php controller becomes as follows:

<?php
class Hello extends CI_Controller{

  function index(){
      echo "Hello World";
  }

  function show(){
      echo "I Make The World Better Place.";
  }

}

If you run it by visiting the following URL:

http://localhost/myproject/index.php/hello/show

Then, will appear the result as follows:

Better Place

 

7. Remove index.php from URL

Codeigniter is a php framework that supports clean URLs.

That way, you can create an easy-to-read and SEO Friendly URL.

In the "Hello World" application URL above, it can be seen that the index.php in the url looks annoying.

Is there a way to remove index.php from URL?

Of course, you can use the .htaccess file to remove it.

How to create .htaccess file?

Let’s begin.

Create a file named .htaccess on your web root and type the code below:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

Just like the picture below:

htaccess

Then open the application/config/config.php folder using the text editor.

config

And then find the code below:

$config['index_page'] = 'index.php';

And set to be like this:

$config['index_page'] = '';

Now please visit the following url for testing:

http://localhost/myproject/hello/show

Then the results will look like the picture below:

Better Place

In the picture above, it can be seen that the URL becomes more neat and SEO friendly by removing the index.php on the URL.

 

8. Controller and View

In the previous case, you already know how to display the text "Hello World" directly from the controller.

But, it should be done in view.

Now, I will show how to display view from controller.

Let’s begin.

First of all, create a file in the application/controller with the name Blog.php.

Then type the following code:

<?php
class Blog extends CI_Controller
{
  function __construct()
  {
      parent::__construct();
  }
  
  function index(){
      $this->load->view('blog_view');
  }
  
}

Second of all, create a file in application/views with the name of blog_view.php.

Then type the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>My Blog</title>
  </head>
  <body>
    <h1>Welcome To My Blog.</h1>
  </body>
</html>

Then, open your browser and access the Blog controller.

Then the results will look like the following:

My Blog

You can also send parameters to view via controller.

For example, please edit the Blog.php controller to be as follows:

<?php
class Blog extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    function index(){
        $data['title']   = "This Is Title";
        $data['content'] = "This Is The Contents";
        $this->load->view('blog_view',$data);
    }

}

Then edit the view blog_view.php be like the following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title><?php echo $title;?></title>
  </head>
  <body>
    <h1><?php echo $content;?></h1>
  </body>
</html>

Then, open your browser and access the Blog controller again. Then the results will look like the following:

The Content

I hope you can understand the difference.

 

9. Codeigniter and Bootstrap

In the previous case, you have understood how to call view via controller.

Now, there is a very important thing for you to know, that is about combine codeigniter with bootstrap.

What is BOOTSTRAP?

Bootstrap is an open source toolkit to be developed with HTML, CSS, and JS.

In other words, Bootstrap is a framework to beautify the user interface (UI).

Bootstrap is responsive.

In other words, renders well on various devices (platforms) such as tablets or mobile phones.

Awesome right?

So, How to combine codeigniter and bootstrap?

Let’s begin.

First of all, please download the bootstrap on the official website getbootstrap.com.

bootstrap

Second of all, create a new folder on your project (webroot).

Here I named "assets" folder.

And then, extract the bootstrap file you have downloaded earlier into the assets folder.

Like this:

Assets folder

Besides the bootstrap, we also need jquery for javascript on bootstrap to run optimally.

To download Jquery, please download from the official website jquery.com.

jquery

And then, put the jquery file into assets/js/ folder.

Like the picture below:

Jquery js

It may sound complicated, but it is not.

To help you understand what bootstrap looks like, please edit the view file blog_view.php to be as follows:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title><?php echo $title;?></title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>

    <div class="container">
      <div class="jumbotron jumbotron-fluid">
        <div class="container">
          <h1 class="display-4"><?php echo $content;?></h1>
          <p class="lead">This is my first blog.</p>
        </div>
      </div>
    </div>

    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

If you call the blog controller in the browser, it will look like the following results:

bootstrap

In the picture above, you can see that we don't need to create css code to provide a style on a website page.

Similarly, if you need a beautiful table. You also do not need to type css code to give a style to the table.

Instead, you can instantly have a beautiful table instantly.

For example, please edit the view file “blog_view.php” to be as follows:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title><?php echo $title;?></title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>

    <div class="container">
      <h1><?php echo $content;?></h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">First</th>
            <th scope="col">Last</th>
            <th scope="col">Handle</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row">1</th>
            <td>Mark</td>
            <td>Otto</td>
            <td>@mdo</td>
          </tr>
          <tr>
            <th scope="row">2</th>
            <td>Jacob</td>
            <td>Thornton</td>
            <td>@fat</td>
          </tr>
          <tr>
            <th scope="row">3</th>
            <td>Larry</td>
            <td>the Bird</td>
            <td>@twitter</td>
          </tr>
        </tbody>
      </table>

    </div>

    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

If you re-run the Blog controller in the browser, then you will get the following results:

Bootstrap Table

Awesome right?

Hopefully, you could understand so far.

 

10. Work with Database

In this segment, you will learn all the things you need to know about how to interact with the database using codeigniter.

Starting from Create, Read, Update, and Delete.

Let’s dive right in.

1. Database Preparation.

First of all, create a database. Here I created a database named "pos_db".

If you create a database with the same name, it's better.

To create a database, you can execute the query below:

CREATE DATABASE pos_db;

That query will create a database named "pos_db".

And then, create a table “product” with the structure below:

Database structure

You can execute the query below to generate a table with the structure as above:

CREATE TABLE product(
product_id INT PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(100),
product_price INT
);

Then input some data into the "product" table by executing the following query:

INSERT INTO product(product_name,product_price) VALUES 
('Coca Cola','5000'),
('Teh Botol','3700'),
('You C 1000','6300'),
('Ponds Men','18000'),
('Rexona Men','13000');

The next step is to connect the codeigniter with the database.

To connect codeigniter with database is very simple, please open application/config/database.php

database config

Open the database.php file with a text editor and find the following code:

$active_group = 'default';
$query_builder = TRUE;

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

And then set to be like this:

$active_group = 'default';
$query_builder = TRUE;

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

Please run your project again in browser, if no error means connection to database successfully.

2. Display data from database to view (Read).

In this segment, I will show you how to display data from database to view.

Let’s begin.

#1. Create a file into application/models. Here I named “Product_model.php”.

So look like the picture below:

Product Model

Open “Product_model.php” by using text editor. And then type the code below:

<?php
class Product_model extends CI_Model{

  function get_product(){
    $result = $this->db->get('product');
    return $result;
  }
  
}

#2. Create a file into application/controllers. Here I named “Product.php”.

Like the picture below:

Product Controller

Open the controller “Product.php” by using text editor. And then type the code below:

<?php
class Product extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('product_model');
  }
  function index(){
    $data['product'] = $this->product_model->get_product();
    $this->load->view('product_view',$data);
  }
}

#3. Create a view file with the name “product_view.php”.

Like the picture below:

Product view

And then type the code below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Product List</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>

    <div class="container">
        <h1><center>Product List</center></h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Product Name</th>
            <th scope="col">Price</th>
          </tr>
        </thead>
        <?php
          $count = 0;
          foreach ($product->result() as $row) :
            $count++;
        ?>
          <tr>
            <th scope="row"><?php echo $count;?></th>
            <td><?php echo $row->product_name;?></td>
            <td><?php echo number_format($row->product_price);?></td>
          </tr>
        <?php endforeach;?>
        </tbody>
      </table>

    </div>

    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

Then, run the "Product" controller through your browser, by visiting the following url:

http://localhost/myproject/product

Then the results will look like the following:

Product List

3. Insert data to database (Create).

In this segment, I will show you how to insert the data into the database.

Let’s begin.

#1. Open the model "Product_model.php" file. then add one more function like this:

<?php
class Product_model extends CI_Model{

  function get_product(){
    $result = $this->db->get('product');
    return $result;
  }
  function save($product_name,$product_price){
    $data = array(
      'product_name' => $product_name,
      'product_price' => $product_price
    );
    $this->db->insert('product',$data);
  }
}

#2. Open the controller "Product.php" file. then add some more functions like this:

<?php
class Product extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('product_model');
  }
  function index(){
    $data['product'] = $this->product_model->get_product();
    $this->load->view('product_view',$data);
  }
  function add_new(){
    $this->load->view('add_product_view');
  }
  function save(){
    $product_name = $this->input->post('product_name');
    $product_price = $this->input->post('product_price');
    $this->product_model->save($product_name,$product_price);
    redirect('product');
  }
}

#3. Create a new view file with the name "add_product_view.php". With code like the following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Add New Product</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>

    <div class="container">
      <h1><center>Add New Product</center></h1>
        <div class="col-md-6 offset-md-3">
        <form action="<?php echo site_url('product/save');?>" method="post">
          <div class="form-group">
            <label>Product Name</label>
            <input type="text" class="form-control" name="product_name" placeholder="Product Name">
          </div>
          <div class="form-group">
            <label>Price</label>
            <input type="text" class="form-control" name="product_price" placeholder="Price">
          </div>
          <button type="submit" class="btn btn-primary">Submit</button>
        </form>
      </div>
    </div>

    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

Then, go back to the browser and type in the following url on your browser:

http://localhost/myproject/product/add_new

Then the results will look like the following:

Add product

Enter product name and price in textbox, then click submit button.

Then the data will appear on the product list as follows:

Product List

4. Delete data to database (Delete).

In this segment, I will show you how to delete data to the database.

Let’s begin.

#1. Open the view file "product_view.php". Edit then edit to be like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Product List</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>

    <div class="container">
        <h1><center>Product List</center></h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Product Name</th>
            <th scope="col">Price</th>
			<th width="200">Action</th>
          </tr>
        </thead>
        <?php
          $count = 0;
          foreach ($product->result() as $row) :
            $count++;
        ?>
          <tr>
            <th scope="row"><?php echo $count;?></th>
            <td><?php echo $row->product_name;?></td>
            <td><?php echo number_format($row->product_price);?></td>
			<td>
				<a href="<?php echo site_url('product/delete/'.$row->product_id);?>" class="btn btn-sm btn-danger">Delete</a>
			<td>
          </tr>
        <?php endforeach;?>
        </tbody>
      </table>

    </div>

    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

In the "product_view.php" file above we add one more column to the product list table. That is the action column.

In the action column there is a delete button. So if you run Controller product, by visiting the following url:

http://localhost/myproject/product/

Then the results will look like the following:

Product List

#2. Add a delete function to the Product.php controller.

And then type the code below:

function delete(){
	$product_id = $this->uri->segment(3);
	$this->product_model->delete($product_id);
	redirect('product');
}

So look full code from the controller Product.php below:

<?php
class Product extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('product_model');
  }
  function index(){
    $data['product'] = $this->product_model->get_product();
    $this->load->view('product_view',$data);
  }
  function add_new(){
    $this->load->view('add_product_view');
  }
  function save(){
    $product_name = $this->input->post('product_name');
    $product_price = $this->input->post('product_price');
    $this->product_model->save($product_name,$product_price);
    redirect('product');
  }
  function delete(){
	$product_id = $this->uri->segment(3);
	$this->product_model->delete($product_id);
	redirect('product');
  }
}

#3. Add a delete function in Product_model.php model.

The code as follows:

function delete($product_id){
	$this->db->where('product_id', $product_id);
	$this->db->delete('product');
}

So look complete code from model Product_model.php below:

<?php
class Product_model extends CI_Model{
  function get_product(){
    $result = $this->db->get('product');
    return $result;
  }
  function save($product_name,$product_price){
    $data = array(
      'product_name' => $product_name,
      'product_price' => $product_price
    );
    $this->db->insert('product',$data);
  }
  function delete($product_id){
	$this->db->where('product_id', $product_id);
	$this->db->delete('product');
  }
}

Now go back to the browser and visit the following url:

http://localhost/myproject/product

It will show product list like the picture below:

Product List

Please click one of the delete buttons on the action column to delete the record.

That's it.

5. Update data to database (Update).

You already know how to display data (READ) from database to view, Insert data to database (CREATE), and delete data to database (DELETE).

Now its time to know how to change data to database (UPDATE).

Let’s begin.

#1. Open the view file "product_view.php". And then edit to the following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Product List</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>

    <div class="container">
        <h1><center>Product List</center></h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Product Name</th>
            <th scope="col">Price</th>
		<th width="200">Action</th>
          </tr>
        </thead>
        <?php
          $count = 0;
          foreach ($product->result() as $row) :
            $count++;
        ?>
          <tr>
            <th scope="row"><?php echo $count;?></th>
            <td><?php echo $row->product_name;?></td>
            <td><?php echo number_format($row->product_price);?></td>
		<td>
			<a href="<?php echo site_url('product/get_edit/'.$row->product_id);?>" class="btn btn-sm btn-info">Update</a>
			<a href="<?php echo site_url('product/delete/'.$row->product_id);?>" class="btn btn-sm btn-danger">Delete</a>
		<td>
          </tr>
        <?php endforeach;?>
        </tbody>
      </table>

    </div>

    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

In the "product_view.php" file above we add one more button to the action column. That is the edit button.

So if you run Controller product, by visiting the following url:

http://localhost/myproject/product/

Then the results will look like the following:

Product List Edit

#2. Add a function function get_edit on Product.php controller.

And then type the code below:

function get_edit(){
	$product_id = $this->uri->segment(3);
	$result = $this->product_model->get_product_id($product_id);
	if($result->num_rows() > 0){
		$i = $result->row_array();
		$data = array(
			'product_id' 	=> $i['product_id'],
			'product_name' 	=> $i['product_name'],
			'product_price' 	=> $i['product_price']
		);
		$this->load->view('edit_product_view',$data);
	}else{
		echo "Data Was Not Found";
	}
}

#3. Add a function “function get_product_id” on Product_model.php controller.

And then type the code below:

function get_product_id($product_id){
	$query = $this->db->get_where('product', array('product_id' => $product_id));
	return $query;
}

#4. Create one more view named "edit_product_view.php". Then type the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Edit Product</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>

    <div class="container">
      <h1><center>Edit Product</center></h1>
        <div class="col-md-6 offset-md-3">
        <form action="<?php echo site_url('product/update');?>" method="post">
          <div class="form-group">
            <label>Product Name</label>
            <input type="text" class="form-control" name="product_name" value="<?php echo $product_name;?>" placeholder="Product Name">
          </div>
          <div class="form-group">
            <label>Price</label>
            <input type="text" class="form-control" name="product_price" value="<?php echo $product_price;?>" placeholder="Price">
          </div>
		  <input type="hidden" name="product_id" value="<?php echo $product_id?>">
          <button type="submit" class="btn btn-primary">Update</button>
        </form>
      </div>
    </div>

    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

#5. Add a more function named “function update” on Product.php controller.

And then type the following code:

function update(){
	$product_id = $this->input->post('product_id');
	$product_name = $this->input->post('product_name');
    	$product_price = $this->input->post('product_price');
    	$this->product_model->update($product_id,$product_name,$product_price);
   	redirect('product');
}

So look full code from the controller Product.php below:

<?php
class Product extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('product_model');
  }
  function index(){
    $data['product'] = $this->product_model->get_product();
    $this->load->view('product_view',$data);
  }
  function add_new(){
    $this->load->view('add_product_view');
  }
  function save(){
    $product_name = $this->input->post('product_name');
    $product_price = $this->input->post('product_price');
    $this->product_model->save($product_name,$product_price);
    redirect('product');
  }
  function delete(){
	$product_id = $this->uri->segment(3);
	$this->product_model->delete($product_id);
	redirect('product');
  }
  function get_edit(){
	$product_id = $this->uri->segment(3);
	$result = $this->product_model->get_product_id($product_id);
	if($result->num_rows() > 0){
		$i = $result->row_array();
		$data = array(
			'product_id' 	=> $i['product_id'],
			'product_name' 	=> $i['product_name'],
			'product_price' => $i['product_price']
		);
		$this->load->view('edit_product_view',$data);
	}else{
		echo "Data Was Not Found";
	}
  }
  function update(){
	$product_id = $this->input->post('product_id');
	$product_name = $this->input->post('product_name');
    $product_price = $this->input->post('product_price');
    $this->product_model->update($product_id,$product_name,$product_price);
    redirect('product');
  }
}

#6. Add a function named "function update" to the Product_model.php model.

The code as follows:

function update($product_id,$product_name,$product_price){
	$data = array(
      'product_name' => $product_name,
      'product_price' => $product_price
    );
	$this->db->where('product_id', $product_id);
	$this->db->update('product', $data);
}

So look complete code from model Product_model.php as follows:

<?php
class Product_model extends CI_Model{

  function get_product(){
    $result = $this->db->get('product');
    return $result;
  }
  function save($product_name,$product_price){
    $data = array(
      'product_name' => $product_name,
      'product_price' => $product_price
    );
    $this->db->insert('product',$data);
  }
  function delete($product_id){
	$this->db->where('product_id', $product_id);
	$this->db->delete('product');
  }
  function get_product_id($product_id){
	$query = $this->db->get_where('product', array('product_id' => $product_id));
	return $query;
  }
  function update($product_id,$product_name,$product_price){
	$data = array(
      'product_name' => $product_name,
      'product_price' => $product_price
    );
	$this->db->where('product_id', $product_id);
	$this->db->update('product', $data);
  }
}

Now go back to the browser and visit the following url:

http://localhost/myproject/product

It will show product list as shown below:

Product List

Please click one of the edit buttons on the action column to update the record.

Then the edit form will appear as follows:

Edit Form

Change the data and then click the update button, then the record will update.

Product List Update

Done.

 

CONCLUSION

This discussion is about complete codeigniter tutorial for beginners.

Starting from the introduction of codeigniter, codeigniter superiority, MVC concept, codeigniter installation, and basic configuration on codeigniter.

You've also learned how a controller works, with the "hello world" case study.

You've also learned how to remove of index.php from the url, so the URL becomes cleaner as well as SEO Friendly.

You have also learned how to display a view through the controller.

You have also learned how to combine codeigniter with bootstrap.

Finally, you have learned how to work with databases.

And you've also learned how to create a CRUD (Create Read Update Delete) application with codeigniter and bootstrap.

So, what are you waiting for... Let’s coding.!

Download PDF

Share:



Sponsorship:

Comments (0)

Leave a Comment