Codeigniter 3 - Basic CRUD application with MySQL Example with Demo

By Hardik Savani | November 4, 2017 | | 2853 Viewer | Category : PHP Bootstrap HTML jQuery MySql Codeigniter


Today I am going to share with you how to create insert update delete operation with validation in codeigniter 3 application with demo example.

this tutorial will help to create simple CRUD (Create Read Update Delete) Operation application using MySQL Database with validation. As we know well we always require to create basic CRUD module for products, items etc using mysql database. It is primary requirement for any web application. So in this example i will explain example of add, edit and delete record using codeigniter 3 and mysql database. I am extending this tutorial and will add functionality to insert update delete record from mysql database with demo.

Here i explain step by step process to create listing, add, edit and delete record using Codeigniter 3. You have to simple follow bellow few step to create basic CRUD application in codeigniter application.

There are listed bellow step you have to follow:

1) Download Codeigniter 3

2) Make Database and Configuration

3) Create Routes

4) Add ItemCRUD Controller

5) Create ItemCRUD Model

6) Create View Files

End of the example of this example you will get full CRUD app like as bellow screenshot.

Preview:

Step 1: Download Codeigniter 3

In this step we will download version of Codeigniter 3, so if you haven't download yet then download from here : Download Codeigniter 3.

After Download successfully, extract clean new Codeigniter 3 application.

Step 2: Make Database and Configuration

In second step we will create new database "test" and add new table "items" in test database. You can use following SQL Query for create "items" table. So let's create using bellow SQL query:

items table:

CREATE TABLE IF NOT EXISTS `items` (

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

`description` text COLLATE utf8_unicode_ci NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

After create database and table successfully, we have to configuration of database in our Codeigniter 3 application, so open database.php file and add your database name, username and password.

application/config/database.php

<?php

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


$active_group = 'default';

$query_builder = TRUE;


$db['default'] = array(

'dsn' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => 'root',

'database' => 'test',

'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: Create Routes

Here, we have to add some routes in your route file. So first we will create routes for itemCRUD modules for lists, create, edit, update and delete. so put the bellow content in route file:

application/config/routes.php

<?php

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


$route['default_controller'] = 'welcome';

$route['404_override'] = '';

$route['translate_uri_dashes'] = FALSE;


$route['itemCRUD'] = "itemCRUD/index";

$route['itemCRUD/(:num)'] = "itemCRUD/show/$1";

$route['itemCRUDCreate']['post'] = "itemCRUD/store";

$route['itemCRUDEdit/(:any)'] = "itemCRUD/edit/$1";

$route['itemCRUDUpdate/(:any)']['put'] = "itemCRUD/update/$1";

$route['itemCRUDDelete/(:any)']['delete'] = "itemCRUD/delete/$1";

Step 4: Add ItemCRUD Controller

Ok In this step, we will create one new controller ItemCRUD with method listing, create, edit, update and delete. so create ItemCRUD.php file in this path application/controllers/ItemCRUD.php and put bellow code in this file:

application/controllers/ItemCRUD.php

<?php

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

class ItemCRUD extends CI_Controller {


public $itemCRUD;


/**

* Get All Data from this method.

*

* @return Response

*/

public function __construct() {

parent::__construct();


$this->load->library('form_validation');

$this->load->library('session');

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


$this->itemCRUD = new ItemCRUDModel;

}


/**

* Display Data this method.

*

* @return Response

*/

public function index()

{

$data['data'] = $this->itemCRUD->get_itemCRUD();


$this->load->view('theme/header');

$this->load->view('itemCRUD/list',$data);

$this->load->view('theme/footer');

}


/**

* Show Details this method.

*

* @return Response

*/

public function show($id)

{

$item = $this->itemCRUD->find_item($id);


$this->load->view('theme/header');

$this->load->view('itemCRUD/show',array('item'=>$item));

$this->load->view('theme/footer');

}


/**

* Create from display on this method.

*

* @return Response

*/

public function create()

{

$this->load->view('theme/header');

$this->load->view('itemCRUD/create');

$this->load->view('theme/footer');

}


/**

* Store Data from this method.

*

* @return Response

*/

public function store()

{

$this->form_validation->set_rules('title', 'Title', 'required');

$this->form_validation->set_rules('description', 'Description', 'required');


if ($this->form_validation->run() == FALSE){

$this->session->set_flashdata('errors', validation_errors());

redirect(base_url('itemCRUD/create'));

}else{

$this->itemCRUD->insert_item();

redirect(base_url('itemCRUD'));

}

}


/**

* Edit Data from this method.

*

* @return Response

*/

public function edit($id)

{

$item = $this->itemCRUD->find_item($id);


$this->load->view('theme/header');

$this->load->view('itemCRUD/edit',array('item'=>$item));

$this->load->view('theme/footer');

}


/**

* Update Data from this method.

*

* @return Response

*/

public function update($id)

{

$this->form_validation->set_rules('title', 'Title', 'required');

$this->form_validation->set_rules('description', 'Description', 'required');


if ($this->form_validation->run() == FALSE){

$this->session->set_flashdata('errors', validation_errors());

redirect(base_url('itemCRUD/edit/'.$id));

}else{

$this->itemCRUD->update_item($id);

redirect(base_url('itemCRUD'));

}

}


/**

* Delete Data from this method.

*

* @return Response

*/

public function delete($id)

{

$item = $this->itemCRUD->delete_item($id);

redirect(base_url('itemCRUD'));

}

}

Step 5: Create ItemCRUD Model

In this step, we have to create ItemCRUD model for write database logic, here we will write database logic to fetch all data, insert new record, update and delete. So you have to create new ItemCRUD.php in models folder.

application/models/ItemCRUD.php

<?php


class ItemCRUDModel extends CI_Model{


public function get_itemCRUD(){

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("items");

return $query->result();

}


public function insert_item()

{

$data = array(

'title' => $this->input->post('title'),

'description' => $this->input->post('description')

);

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

}


public function update_item($id)

{

$data=array(

'title' => $this->input->post('title'),

'description'=> $this->input->post('description')

);

if($id==0){

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

}else{

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

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

}

}


public function find_item($id)

{

return $this->db->get_where('items', array('id' => $id))->row();

}


public function delete_item($id)

{

return $this->db->delete('items', array('id' => $id));

}

}

?>

Step 6: Create View Files

now we move in last step. In this step we have to create just php view files. So mainly we have to create layout file and then create new folder "itemCRUD" then create blade files of crud app. So finally you have to create following bellow view file:

1) header.php

2) footer.php

3) list.php

4) create.php

5) show.php

6) edit.php

So let's just create following file and put bellow code.

application/views/theme/header.php

<!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 class="container">

application/views/theme/footer.php

</div>

</body>

</html>

application/views/itemCRUD/list.php

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Codeigniter 3 CRUD Example from scratch</h2>

</div>

<div class="pull-right">

<a class="btn btn-success" href="<?php echo base_url('itemCRUD/create') ?>"> Create New Item</a>

</div>

</div>

</div>


<table class="table table-bordered">


<thead>

<tr>

<th>Title</th>

<th>Description</th>

<th width="220px">Action</th>

</tr>

</thead>


<tbody>

<?php foreach ($data as $item) { ?>

<tr>

<td><?php echo $item->title; ?></td>

<td><?php echo $item->description; ?></td>

<td>

<form method="DELETE" action="<?php echo base_url('itemCRUD/delete/'.$item->id);?>">

<a class="btn btn-info" href="<?php echo base_url('itemCRUD/'.$item->id) ?>"> show</a>

<a class="btn btn-primary" href="<?php echo base_url('itemCRUD/edit/'.$item->id) ?>"> Edit</a>

<button type="submit" class="btn btn-danger"> Delete</button>

</form>

</td>

</tr>

<?php } ?>

</tbody>


</table>

application/views/itemCRUD/create.php

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Add New Item</h2>

</div>

<div class="pull-right">

<a class="btn btn-primary" href="<?php echo base_url('itemCRUD');?>"> Back</a>

</div>

</div>

</div>


<form method="post" action="<?php echo base_url('itemCRUDCreate');?>">

<?php


if ($this->session->flashdata('errors')){

echo '<div class="alert alert-danger">';

echo $this->session->flashdata('errors');

echo "</div>";

}


?>


<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Title:</strong>

<input type="text" name="title" class="form-control">

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Description:</strong>

<textarea name="description" class="form-control"></textarea>

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12 text-center">

<button type="submit" class="btn btn-primary">Submit</button>

</div>

</div>


</form>

application/views/itemCRUD/show.php

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2> Show Item</h2>

</div>

<div class="pull-right">

<a class="btn btn-primary" href="<?php echo base_url('itemCRUD');?>"> Back</a>

</div>

</div>

</div>


<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Title:</strong>

<?php echo $item->title; ?>

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Description:</strong>

<?php echo $item->description; ?>

</div>

</div>

</div>

application/views/itemCRUD/edit.php

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Edit Item</h2>

</div>

<div class="pull-right">

<a class="btn btn-primary" href="<?php echo base_url('itemCRUD');?>"> Back</a>

</div>

</div>

</div>


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

<?php


if ($this->session->flashdata('errors')){

echo '<div class="alert alert-danger">';

echo $this->session->flashdata('errors');

echo "</div>";

}


?>


<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Title:</strong>

<input type="text" name="title" class="form-control" value="<?php echo $item->title; ?>">

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Description:</strong>

<textarea name="description" class="form-control"><?php echo $item->description; ?></textarea>

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12 text-center">

<button type="submit" class="btn btn-primary">Submit</button>

</div>

</div>


</form>

Ok, now we are ready to run our CRUD Application example. So let's run bellow command on your root directory for quick run:

php -S localhost:8000

Now you can open bellow URL on your browser:

http://localhost:8000/

If you are run using localhost:800 then you have to set base url in config:

application/config/config.php

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

I hope it can help you...






We are Recommending you: