Simple CRUD implementation with CodeIgniter using Mysql, Ajax and Bootstrap Model

Simple CRUD implementation with CodeIgniter using Mysql, Ajax and Bootstrap Model, CRUD stand for basic operations like Create, Read, Update and Delete performed on the database.So in this post we will learn insert update delete in CodeIgniter using jQuery Ajax. We will cover this tutorial in easy steps with live demo to develop complete CRUD operations. We will also provide to download source code of live demo.

Step 1: Create MySQL Database and Table


//Table structure for table `employees`
CREATE TABLE `employees` (
`id` int(11) NOT NULL COMMENT 'primary key',
`name` varchar(255) NOT NULL COMMENT 'Employee Name',
`last_name` varchar(100) DEFAULT NULL,
`email` varchar(255) NOT NULL COMMENT 'Email Address',
`contact_no` varchar(16) DEFAULT NULL,
`address` text,
`salary` float(10,2) NOT NULL COMMENT 'employee salary'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table';

// Indexes for table `employees`

ALTER TABLE `employees` ADD PRIMARY KEY (`id`);

// AUTO_INCREMENT for table `employees`

ALTER TABLE `employees` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key', AUTO_INCREMENT=1;
?>


Step 2: Create a model file
Create a model file named "Curd_model.php" inside "application/models" folder.

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
* Description of Curd Model: CodeIgniter CRUD Operations with MySQL
*
* @author TechArise Team
*
* @email info@techarise.com
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');

class Curd_model extends CI_Model {

private $_empID;
private $_firstName;
private $_lastName;
private $_email;
private $_address;
private $_salary;
private $_contactNo;

public function setEmpID($empID) {
$this->_empID = $empID;
}
public function setFirstName($firstName) {
$this->_firstName = $firstName;
}
public function setLastName($lastName) {
$this->_lastName = $lastName;
}
public function setEmail($email) {
$this->_email = $email;
}
public function setAddress($address) {
$this->_address = $address;
}
public function setSalary($salary) {
$this->_salary = $salary;
}
public function setContactNo($contactNo) {
$this->_contactNo = $contactNo;
}
// get Employee List
public function getEmpList() {
$this->db->select(array('e.id', 'e.name', 'e.last_name', 'e.email', 'e.address', 'e.contact_no', 'e.salary'));
$this->db->from('employees e');
$this->db->order_by('e.id', 'DESC');
$query = $this->db->get();
return $query->result_array();
}
// create new Employee
public function createEmp() {
$data = array(
'name' => $this->_firstName,
'last_name' => $this->_lastName,
'email' => $this->_email,
'address' => $this->_address,
'contact_no' => $this->_contactNo,
'salary' => $this->_salary,
);
$this->db->insert('employees', $data);
return $this->db->insert_id();
}
// update Employee
public function updateEmp() {
$data = array(
'name' => $this->_firstName,
'last_name' => $this->_lastName,
'email' => $this->_email,
'address' => $this->_address,
'contact_no' => $this->_contactNo,
'salary' => $this->_salary,
);
$this->db->where('id', $this->_empID);
$this->db->update('employees', $data);
}
// for display Employee
public function getEmp() {
$this->db->select(array('e.id', 'e.name as first_name', 'e.last_name', 'e.email', 'e.address', 'e.contact_no', 'e.salary'));
$this->db->from('employees e');
$this->db->where('e.id', $this->_empID);
$query = $this->db->get();
return $query->row_array();
}

// delete Employee
public function deleteEmp() {
$this->db->where('id', $this->_empID);
$this->db->delete('employees');
}

// email validation
public function validateEmail($email)
{
return preg_match('/^[^\@]+@.*.[a-z]{2,15}$/i', $email)?TRUE:FALSE;
}

// mobile validation
public function validateMobile($mobile)
{
return preg_match('/^[0-9]{10}+$/', $mobile)?TRUE:FALSE;
}

}
?>


Step 3: Create a controller file
Next create a controller file named "Curd.php" inside "application/controllers" folder.


/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
* @package Curd : CodeIgniter CRUD Operations with MySQL
*
* @author TechArise Team
*
* @email info@techarise.com
*
* Description of Curd Controller
*/
if (!defined('BASEPATH'))
exit('No direct script access allowed');

class Curd extends CI_Controller {

public function __construct() {
parent::__construct();
$this->load->model('Curd_model', 'emp');
}
// Employee list method
public function index() {
$data['page'] = 'emp-list';
$data['title'] = 'Employee List | TechArise';
$data['empInfo'] = $this->emp->getEmpList();
$this->load->view('emp/index', $data);
}

// Employee save method
public function save() {
$json = array();
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$address = $this->input->post('address');
$contact_no = $this->input->post('contact_no');
$salary = $this->input->post('salary');

if(empty(trim($first_name))){
$json['error']['firstname'] = 'Please enter first name';
}
if(empty(trim($last_name))){
$json['error']['lastname'] = 'Please enter last name';
}

if(empty(trim($email))){
$json['error']['email'] = 'Please enter email address';
}

if ($this->emp->validateEmail($email) == FALSE) {
$json['error']['email'] = 'Please enter valid email address';
}
if(empty($address)){
$json['error']['address'] = 'Please enter address';
}
if($this->emp->validateMobile($contact_no) == FALSE) {
$json['error']['contactno'] = 'Please enter valid contact no';
}

if(empty($salary)){
$json['error']['salary'] = 'Please enter salary';
}

if(empty($json['error'])){
$this->emp->setFirstName($first_name);
$this->emp->setLastName($last_name);
$this->emp->setEmail($email);
$this->emp->setAddress($address);
$this->emp->setSalary($salary);
$this->emp->setContactNo($contact_no);
try {
$last_id = $this->emp->createEmp();
} catch (Exception $e) {
var_dump($e->getMessage());
}

if (!empty($last_id) && $last_id > 0) {
$empID = $last_id;
$this->emp->setEmpID($empID);
$empInfo = $this->emp->getEmp();
$json['emp_id'] = $empInfo['id'];
$json['first_name'] = $empInfo['first_name'];
$json['last_name'] = $empInfo['last_name'];
$json['email'] = $empInfo['email'];
$json['address'] = $empInfo['address'];
$json['contact_no'] = $empInfo['contact_no'];
$json['salary'] = $empInfo['salary'];
$json['status'] = 'success';
}
}
echo json_encode($json);
}

// Employee edit method
public function edit() {
$json = array();
$empID = $this->input->post('emp_id');
$this->emp->setEmpID($empID);
$json['empInfo'] = $this->emp->getEmp();

$this->output->set_header('Content-Type: application/json');
$this->load->view('emp/popup/renderEdit', $json);
}

// Employee update method
public function update() {
$json = array();
$emp_id = $this->input->post('emp_id');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$address = $this->input->post('address');
$contact_no = $this->input->post('contact_no');
$salary = $this->input->post('salary');

if(empty(trim($first_name))){
$json['error']['firstname'] = 'Please enter first name';
}
if(empty(trim($last_name))){
$json['error']['lastname'] = 'Please enter last name';
}

if(empty(trim($email))){
$json['error']['email'] = 'Please enter email address';
}

if ($this->emp->validateEmail($email) == FALSE) {
$json['error']['email'] = 'Please enter valid email address';
}
if(empty($address)){
$json['error']['address'] = 'Please enter address';
}
if($this->emp->validateMobile($contact_no) == FALSE) {
$json['error']['contactno'] = 'Please enter valid contact no';
}

if(empty($salary)){
$json['error']['salary'] = 'Please enter salary';
}

if(empty($json['error'])){
$this->emp->setEmpID($emp_id);
$this->emp->setFirstName($first_name);
$this->emp->setLastName($last_name);
$this->emp->setEmail($email);
$this->emp->setAddress($address);
$this->emp->setSalary($salary);
$this->emp->setContactNo($contact_no);
try {
$last_id = $this->emp->updateEmp();;
} catch (Exception $e) {
var_dump($e->getMessage());
}

if (!empty($emp_id) && $emp_id > 0) {
$this->emp->setEmpID($emp_id);
$empInfo = $this->emp->getEmp();
$json['emp_id'] = $empInfo['id'];
$json['first_name'] = $empInfo['first_name'];
$json['last_name'] = $empInfo['last_name'];
$json['email'] = $empInfo['email'];
$json['address'] = $empInfo['address'];
$json['contact_no'] = $empInfo['contact_no'];
$json['salary'] = $empInfo['salary'];
$json['status'] = 'success';
}
}
echo json_encode($json);
}

// Employee display method
public function display() {
$json = array();
$empID = $this->input->post('emp_id');
$this->emp->setEmpID($empID);
$json['empInfo'] = $this->emp->getEmp();

$this->output->set_header('Content-Type: application/json');
$this->load->view('emp/popup/renderDisplay', $json);
}

// Employee display method
public function delete() {
$json = array();
$empID = $this->input->post('emp_id');
$this->emp->setEmpID($empID);
$this->emp->deleteEmp();
$this->output->set_header('Content-Type: application/json');
echo json_encode($json);

}

}
?>

Step 4: Change Route file
So open "application/config/routes.php" file and add code like as bellow:

// create routes
$route['curd/edit'] = 'curd/edit';
$route['curd/display'] = 'curd/display';
$route['curd/delete'] = 'curd/delete';
$route['curd/save'] = 'curd/save';
$route['curd/update'] = 'curd/update';
?>

Step 5: Create a view
Create a view file named "index.php" inside "application/views/emp" folder


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


Simple CRUD implemention with Codeigniter using Mysql, Ajax and Bootstrap Model






















$element) { ?>










First Name Last Name Email Phone Salary Action







$this->load->view('templates/footer');
$this->load->view('emp/popup/add');
$this->load->view('emp/popup/edit');
$this->load->view('emp/popup/display');
$this->load->view('emp/popup/delete');
?>



Step 6: Create a view
Create a view file named "add.php" inside "application/views/emp/popup" folder






Step 7: Create a view
Create a view file named "display.php" inside "application/views/emp/popup" folder






Step 8: Create a view
Create a view file named "renderDisplay.php" inside "application/views/emp/popup" folder


$first_name = $empInfo['first_name'] ? $empInfo['first_name'] : '';
$last_name = $empInfo['last_name'] ? $empInfo['last_name'] : '';
$email = $empInfo['email'] ? $empInfo['email'] : '';
$address = $empInfo['address'] ? $empInfo['address'] : '';
$contact_no = $empInfo['contact_no'] ? $empInfo['contact_no'] : '';
$salary = $empInfo['salary'] ? $empInfo['salary'] : '';
?>


First Name:


Last Name:


Email:


Address:


Phone:


Salary:






Step 9: Create a view
Create a view file named "edit.php" inside "application/views/emp/popup" folder





Step 10: Create a view
Create a view file named "renderEdit.php" inside "application/views/emp/popup" folder


$id = $empInfo['id'] ? $empInfo['id'] : '';
$first_name = $empInfo['first_name'] ? $empInfo['first_name'] : '';
$last_name = $empInfo['last_name'] ? $empInfo['last_name'] : '';
$email = $empInfo['email'] ? $empInfo['email'] : '';
$address = $empInfo['address'] ? $empInfo['address'] : '';
$contact_no = $empInfo['contact_no'] ? $empInfo['contact_no'] : '';
$salary = $empInfo['salary'] ? $empInfo['salary'] : '';
?>







































































Step 11: Create a view
Create a view file named "delete.php" inside "application/views/emp/popup" folder






Step 12: Create a js file
Create a view file named “custom.js” inside “assets/js” folder




// view Emp details
jQuery(document).on('click', 'a.display-emp', function(){
var emp_id = jQuery(this).data('geteid');
jQuery.ajax({
type:'POST',
url:baseurl+'curd/display',
data:{emp_id: emp_id},
dataType:'html',
beforeSend: function () {
jQuery('#render-dispaly-data').html('
');
},
success: function (html) {
jQuery('#render-dispaly-data').html(html);

},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
// Edit Emp Details
jQuery(document).on('click', 'a.update-emp-details', function(){
var emp_id = jQuery(this).data('getueid');
jQuery.ajax({
type:'POST',
url:baseurl+'curd/edit',
data:{emp_id: emp_id},
dataType:'html',
beforeSend: function () {
jQuery('#render-update-data').html('
');
},
success: function (html) {
jQuery('#render-update-data').html(html);

},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
// set emp id for delete
jQuery(document).on('click', 'a.delete-em-details', function(){
var emp_id = jQuery(this).data('getdeid');
jQuery('button#delete-emp').data('deleteempid', emp_id);

});
// Edit Delete Details
jQuery(document).on('click', 'button#delete-emp', function(){
var emp_id = jQuery(this).data('deleteempid');
jQuery.ajax({
type:'POST',
url:baseurl+'curd/delete',
data:{emp_id: emp_id},
dataType:'html',
complete: function () {
setTimeout(function () {
jQuery('tr.empcls-'+emp_id).html('');
}, 3000);
jQuery('#delete-employee').modal('hide');
},
success: function (html) {
jQuery('tr.empcls-'+emp_id).html('Deleted Employee details successfully.');

},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});

// Emp Details Add
jQuery(document).on('click', 'button#add-emp', function(){
jQuery.ajax({
type:'POST',
url:baseurl+'curd/save',
data:jQuery("form#add-employee-form").serialize(),
dataType:'json',
beforeSend: function () {
jQuery('button#add-emp').button('loading');
},
complete: function () {
jQuery('button#add-emp').button('reset');
setTimeout(function () {
jQuery('span#success-msg').html('');
}, 5000);

},
success: function (json) {
//console.log(json);
$('.text-danger').remove();
if (json['error']) {
for (i in json['error']) {
var element = $('.input-emp-' + i.replace('_', '-'));
if ($(element).parent().hasClass('input-group')) {
$(element).parent().after('
' + json['error'][i] + '
');
} else {
$(element).after('
' + json['error'][i] + '
');
}
}
} else {
jQuery('span#success-msg').html('
Employee data has been successfully added.
');
var bindHtml = '';
bindHtml += '';
bindHtml += ''+json['first_name']+'';
bindHtml += ''+json['last_name']+'';
bindHtml += ''+json['email']+'';
bindHtml += ''+json['contact_no']+'';
bindHtml += ''+json['salary']+'';
bindHtml += '';
bindHtml += ' ';
bindHtml += ' ';
bindHtml += '';
bindHtml += '';
bindHtml += '';
jQuery('#render-emp-details').prepend(bindHtml);
jQuery('form#add-employee-form').find('textarea, input').each(function () {
jQuery(this).val('');
});
jQuery('#add-employee').modal('hide');

}

},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});

// Emp details update
jQuery(document).on('click', 'button#update-emp', function(){
jQuery.ajax({
type:'POST',
url:baseurl+'curd/update',
data:jQuery("form#update-employee-form").serialize(),
dataType:'json',
beforeSend: function () {
jQuery('button#update-emp').button('loading');
},
complete: function () {
jQuery('button#update-emp').button('reset');
setTimeout(function () {
jQuery('span#success-msg').html('');
}, 5000);

},
success: function (json) {
//console.log(json);
$('.text-danger').remove();
if (json['error']) {
for (i in json['error']) {
var element = $('.input-emp-' + i.replace('_', '-'));
if ($(element).parent().hasClass('input-group')) {
$(element).parent().after('
' + json['error'][i] + '
');
} else {
$(element).after('
' + json['error'][i] + '
');
}
}
} else {
jQuery('span#success-msg').html('
Employee data has been successfully updated.
');
var bindHtml = '';
bindHtml += ''+json['first_name']+'';
bindHtml += ''+json['last_name']+'';
bindHtml += ''+json['email']+'';
bindHtml += ''+json['contact_no']+'';
bindHtml += ''+json['salary']+'';
bindHtml += '';
bindHtml += '  ';
bindHtml += '  ';
bindHtml += '';
bindHtml += '';
jQuery('tr.empcls-'+json['emp_id']).html(bindHtml);
jQuery('form#update-employee-form').find('textarea, input').each(function () {
jQuery(this).val('');
});
jQuery('#update-employee').modal('hide');
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});

Demo  [sociallocker] Download[/sociallocker]

Komentar

Postingan Populer