PHP Codeigniter 3 – Basic CRUD Operation with MySQL Database with example

PHP Codeigniter 3 – Basic CRUD Operation with MySQL Database with example

In this crud in codeigniter post we will give you information about PHP Codeigniter 3 – Basic CRUD Operation with MySQL Database with example. Hear we will give you detail about PHP Codeigniter 3 – Basic CRUD Operation with MySQL Database with example And how to use it also give you demo for it if it is necessary.

Codeigniter 3 – Basic CRUD Operation with MySQL Database with example

In this tutorial, I will tell you the basic CRUD operation with MySQL database with example in Codeigniter 3.

You will find the step by step process to build a simple application having crud functionality in Codeigniter 3 with MySQL Database.

CRUD operation is a common thing in the application of familiarity with basic create, read, update and delete functionality of the Database.

Step 1: Install Codeigniter 3

Codeigniter 3 is one of the most popular PHP Framework and you can easily install it in your system.

You can easily download it from here : Download Codeigniter 3

As we know Plagiarism Checker, CodeIgniter is very lightweight framework so it will not take long time to download.

After download successfully, extract it in your working directory where you run your PHP script.

Step 2: Database Configuration

To perform crud operation, We will need to have a database with tables so first I will create a demo database and then create a products table within the database.

Run the following sql query to create a table :

CREATE TABLE 'products' (
 'id' int(11) NOT NULL AUTO_INCREMENT,
 'title' varchar(255) NOT NULL,
 'description' varchar(255) NOT NULL,
 'created_at' datetime NOT NULL,
 'updated_at' datetime NOT NULL,
 PRIMARY KEY ('id')
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1

Now I have a products table on which i will perform the crud functionality.

Ok, let’s configure the database with codeigniter application so open the database.php file and put your database credentials (database name, username and password) there.

See also :  php get_headers

You will find the database.php file in following path application/config/database.php.

$active_group=’default’;
$query_builder= TRUE;

$db[‘default’]=array(
‘dsn’    =>”,
‘hostname’=>’localhost’,
‘username’=>’root’,
‘password’=>’xxxx’,
‘database’=>’demo’,
‘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
);


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

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

Step 3: Route

In this step, I will add routes in application/congif/routes.php file to handle the request.

$route[‘default_controller’]=’welcome’;
$route[‘404_override’]=”;
$route[‘translate_uri_dashes’]= FALSE;

$route[‘products’]=”products/index”;
$route[‘productsCreate’][‘post’]=”products/store”;
$route[‘productsEdit/(:any)’]=”products/edit/$1″;
$route[‘productsUpdate/(:any)’][‘put’]=”products/update/$1″;
$route[‘productsDelete/(:any)’][‘delete’]=”products/delete/$1″;


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;


$route['products'] = "products/index";
$route['productsCreate']['post'] = "products/store";
$route['productsEdit/(:any)'] = "products/edit/$1";
$route['productsUpdate/(:any)']['put'] = "products/update/$1";
$route['productsDelete/(:any)']['delete'] = "products/delete/$1";

In routes “products/index”, the first segment will be remapped to the controller class and second will be remapped with the method of that controller.

Step 4: Create Controller

In this step, I will create a controller to handle the method for product listing, create, edit, update and delete.

Now I will create a Products.php file in following path application/controllers/.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Products extends CI_Controller {

/**
* Get All Data from this method.
*
* @return Response
*/
public function__construct(){
//load database in autoload libraries
parent::__construct();
$this->load->model('ProductsModel');
}
public functionindex()
{

$products=new ProductsModel;
$data['data']=$products->get_products();
$this->load->view('includes/header');
$this->load->view('products/list',$data);
$this->load->view('includes/footer');

}

public functioncreate()
{
$this->load->view('includes/header');
$this->load->view('products/create');
$this->load->view('includes/footer');
}

/**
* Store Data from this method.
*
* @return Response
*/
public functionstore()
{
$products=new ProductsModel;
$products->insert_product();
redirect(base_url('products'));
}

/**
* Edit Data from this method.
*
* @return Response
*/
public functionedit($id)
{
$product=$this->db->get_where('products',array('id'=>$id))->row();
$this->load->view('includes/header');
$this->load->view('products/edit',array('product'=>$product));
$this->load->view('includes/footer');
}

/**
* Update Data from this method.
*
* @return Response
*/
public functionupdate($id)
{
$products=new ProductsModel;
$products->update_product($id);
redirect(base_url('products'));
}

/**
* Delete Data from this method.
*
* @return Response
*/
public functiondelete($id)
{
$this->db->where('id',$id);
$this->db->delete('products');
redirect(base_url('products'));
}

}

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Products extends CI_Controller {

   /**
    * Get All Data from this method.
    *
    * @return Response
   */
   public function __construct() {
    //load database in autoload libraries 
      parent::__construct(); 
      $this->load->model('ProductsModel');         
   }
   public function index()
   {

       $products=new ProductsModel;
       $data['data']=$products->get_products();
       $this->load->view('includes/header');       
       $this->load->view('products/list',$data);
       $this->load->view('includes/footer');

   }

   public function create()
   {
      $this->load->view('includes/header');
      $this->load->view('products/create');
      $this->load->view('includes/footer');      
   }

   /**
    * Store Data from this method.
    *
    * @return Response
   */
   public function store()
   {
       $products=new ProductsModel;
       $products->insert_product();
       redirect(base_url('products'));
    }

   /**
    * Edit Data from this method.
    *
    * @return Response
   */
   public function edit($id)
   {
       $product = $this->db->get_where('products', array('id' => $id))->row();
       $this->load->view('includes/header');
       $this->load->view('products/edit',array('product'=>$product));
       $this->load->view('includes/footer');   
   }

   /**
    * Update Data from this method.
    *
    * @return Response
   */
   public function update($id)
   {
       $products=new ProductsModel;
       $products->update_product($id);
       redirect(base_url('products'));
   }

   /**
    * Delete Data from this method.
    *
    * @return Response
   */
   public function delete($id)
   {
       $this->db->where('id', $id);
       $this->db->delete('products');
       redirect(base_url('products'));
   }

}

Step 4: Create Model

See also :  PHP Curl Get Request with Parameters Example

In this step, I will create a model file to define some common functionality that will interact with the database table.

Create a ProductsModel.php file in following path application/models.

<?php

class ProductsModel extends CI_Model{

public functionget_products(){

if(!empty($this->input->get("search"))){
$this->db->like('title',$this->input->get("search"));
$this->db->or_like('description',$this->input->get("search"));
}
$query=$this->db->get("products");
return$query->result();
}

public functioninsert_product()
{
$data=array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
return$this->db->insert('products',$data);
}

public functionupdate_product($id)
{
    $data=array(
            'title'=>$this->input->post('title'),
            'description'=>$this->input->post('description')
    );
    if($id==0){
        return$this->db->insert('products',$data);
    }else{
        $this->db->where('id',$id);
        return$this->db->update('products',$data);
    }

}
}

?>

<?php

class ProductsModel extends CI_Model{
	
    public function get_products(){

        if(!empty($this->input->get("search"))){
          $this->db->like('title', $this->input->get("search"));
          $this->db->or_like('description', $this->input->get("search")); 
        }
        $query = $this->db->get("products");
        return $query->result();
    }

    public function insert_product()
    {    
        $data = array(
            'title' => $this->input->post('title'),
            'description' => $this->input->post('description')
        );
        return $this->db->insert('products', $data);
    }

    public function update_product($id) 
    {
    	$data=array(
			'title' => $this->input->post('title'),
			'description'=> $this->input->post('description')
    	);
    	if($id==0){
    		return $this->db->insert('products',$data);
    	}else{
    		$this->db->where('id',$id);
    		return $this->db->update('products',$data);
    	}    	

    }
}

?>

Step 5: Create View File

In this step, I will create different view files that will be use in this crud application :

    • includes/header.php

 

    • includes/footer.php

 

    • products/list.php

 

    • products/create.php

 

    products/edit.php

includes/header.php

<!DOCTYPEhtml>
<html>
<head>
    <title>Basic Crud operation in Codeigniter 3</title>
    <linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
<body>
<divclass="container">

<!DOCTYPE html>
<html>
<head>
	<title>Basic Crud operation in Codeigniter 3</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div >

includes/footer.php

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

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

products/list.php

<divclass="row">
    <divclass="col-lg-12">
<h2>Products CRUD
<divclass="pull-right">
<aclass="btn btn-primary"href="<?php echo base_url('products/create') ?>"> Create New Product</a>
</div>
</h2>
</div>
</div>
<divclass="table-responsive">
<tableclass="table table-bordered">
<thead>
    <tr>
        <th>Title</th>
        <th>Description</th>
<th>Action</th>

    </tr>
</thead>
<tbody>
<?php foreach ($data as $d) { ?>
    <tr>
        <td><?php echo $d->title; ?></td>
        <td><?php echo $d->description; ?></td>
<td>
<formmethod="DELETE"action="<?php echo base_url('products/delete/'.$d->id);?>">
<aclass="btn btn-info btn-xs"href="<?php echo base_url('products/edit/'.$d->id) ?>"><iclass="glyphicon glyphicon-pencil"></i></a>

<buttontype="submit"class="btn btn-danger btn-xs"><iclass="glyphicon glyphicon-remove"></i></button>
</form>


</td>

    </tr>
    <?php } ?>
</tbody>
</table>
</div>

<div >
	<div >           
        <h2>Products CRUD           
            <div >
               <a  href="<?php echo base_url('products/create') ?>"> Create New Product</a>
            </div>
        </h2>
     </div>
</div>
<div >
<table >
  <thead>
  	<tr>
  		<th>Title</th>
  		<th>Description</th>
      <th>Action</th>

  	</tr>
  </thead>
  <tbody>
   <?php foreach ($data as $d) { ?>  	
  	<tr>
  		<td><?php echo $d->title; ?></td>
  		<td><?php echo $d->description; ?></td>  		
      <td>
        <form method="DELETE" action="<?php echo base_url('products/delete/'.$d->id);?>">
         <a  href="<?php echo base_url('products/edit/'.$d->id) ?>"><i ></i></a>

          <button type="submit" ><i ></i></button>
        </form>


      </td>     

  	</tr>
  	<?php } ?>
  </tbody>
</table>
</div>

products/create.php

<formmethod="post"action="<?php echo base_url('productsCreate');?>">
    <divclass="row">
        <divclass="col-md-8 col-md-offset-2">
            <divclass="form-group">
                <labelclass="col-md-3">Title</label>
                <divclass="col-md-9">
                    <inputtype="text"name="title"class="form-control">
                </div>
            </div>
        </div>
        <divclass="col-md-8 col-md-offset-2">
            <divclass="form-group">
                <labelclass="col-md-3">Description</label>
                <divclass="col-md-9">
                    <textareaname="description"class="form-control"></textarea>
                </div>
            </div>
        </div>
        <divclass="col-md-8 col-md-offset-2 pull-right">
            <inputtype="submit"name="Save"class="btn">
        </div>
    </div>

</form>

<form method="post" action="<?php echo base_url('productsCreate');?>">
	<div >
		<div >
			<div >
				<label >Title</label>
				<div >
					<input type="text" name="title" >
				</div>
			</div>
		</div>
		<div >
			<div >
				<label >Description</label>
				<div >
					<textarea name="description" ></textarea>
				</div>
			</div>
		</div>
		<div >
			<input type="submit" name="Save" >
		</div>
	</div>
	
</form>

products/edit.php

<formmethod="post"action="<?php echo base_url('products/update/'.$product->id);?>">

    <divclass="row">
        <divclass="col-md-8 col-md-offset-2">
            <divclass="form-group">
                <labelclass="col-md-3">Title</label>
                <divclass="col-md-9">
                    <inputtype="text"name="title"class="form-control"value="<?php echo $product->title; ?>">
                </div>
            </div>
        </div>
        <divclass="col-md-8 col-md-offset-2">
            <divclass="form-group">
                <labelclass="col-md-3">Description</label>
                <divclass="col-md-9">
                    <textareaname="description"class="form-control"><?php echo $product->description; ?></textarea>
                </div>
            </div>
        </div>
        <divclass="col-md-8 col-md-offset-2 pull-right">
            <inputtype="submit"name="Save"class="btn">
        </div>
    </div>

</form>

<form method="post" action="<?php echo base_url('products/update/'.$product->id);?>">

	<div >
		<div >
			<div >
				<label >Title</label>
				<div >
					<input type="text" name="title"  value="<?php echo $product->title; ?>">
				</div>
			</div>
		</div>
		<div >
			<div >
				<label >Description</label>
				<div >
					<textarea name="description" ><?php echo $product->description; ?></textarea>
				</div>
			</div>
		</div>
		<div >
			<input type="submit" name="Save" >
		</div>
	</div>
	
</form>

If you will get the error of undefined function base_url() then follow the URL :
Call to undefined function base_url() in Codeigniter

See also :  is_array in php - PHP is_array() Examples

Click here to know how to implement CRUD Operation in Laravel PHP Framework :

Laravel CRUD Example

Try this code and feel free to give your suggestion.

Hope this code and post will helped you for implement PHP Codeigniter 3 – Basic CRUD Operation with MySQL Database with example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs.

Leave a Comment