CodeIgniter Basic Crud Application Part-III
16/04/2019 . 15 minutes, 10 seconds to read . Posted by Admin#php #learnphp #phpframework #phpcrud #crud #phptutorial #phpforms #phpcode #phpcodeigniter #codeigniter #phpdatabase #codeignitercrud
Overview
In the previous part of this tutorial, we have performed the first two basic operations of the crud(create, read).In this part of the tutorial, we will perform the last two basics operations of the crud(update, delete).Before getting started with this part of the tutorial go through the part II click here to view the part-II.
We will proceed with by step define as
- Update Record
- Delete Record
Let's get started step by step
Step 1: Update Record
When a record already exists in the database and we will make changes in the existing record this approach called update. In the part-II of the tutorial, we have read all records from the database and displayed all these records in the table as mention below in the image.
You can see in the above image every record has edit button in the table this button will be used to edit the record. Let's write the code for the edit button when we will click on the edit button it will call the controller method which will accept Id as a parameter and fetch the record against the id.Add the href="<?=base_url()?>index.php/user/edit/<?=$user['id']?>" of the edit button in the application/views/user/index.php or copy the given below code.
application/views/user/index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Codeginiter CRUD Application</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<?php if(isset($value) && isset($msg)) { ?>
<div class="alert alert-<?=($value==1)?'success':'danger'?>">
<?=$msg?>
</div>
<?php } ?>
<div class="page-header">
<h1>Users List</h1>
</div>
<br />
<a href='<?=base_url()?>/index.php/user/add' class='btn btn-primary m-b-1em'>Add New User</a>
<br />
<table class='table table-hover table-responsive table-bordered'>
<br />
<?php if(count($users)>0){?>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<tbody>
<?php $count=1;
foreach($users as $user){ ?>
<tr>
<td> <?= $count++ ?> </td>
<td> <?= $user['first_name'] ?> </td>
<td> <?= $user['last_name'] ?> </td>
<td> <?= $user['email'] ?> </td>
<td>
<a href="<?=base_url()?>index.php/user/edit/<?=$user['id']?>" class='btn btn-primary m-r-1em'>Edit</a>
<a href="#" onclick='return confirm("Do you want to delete")'
class='btn btn-danger'>Delete</a>
</td>
</tr>
</tbody>
<?php } }
else{
echo "<div class='alert alert-danger'>No records found.</div>";
}
?>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
In the above code, we have linked a controller function with the edit button, if we run the above code we will get an error because the edit function does not exist in our controller, open application/controllers/User.php define a new method in user controller and name it edit this method will accept id as a parameter and pass the id to the UserModel function getById and model will return the array of the specific record where id matches. Copy the given below code which includes edit method and inside edit method call to a model function getById.
application/controllers/User.ph
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->Model('UserModel');
}
public function index()
{
$data['users']=$this->UserModel->read();
$this->load->view('user/index',$data);
}
public function add()
{
$this->load->view('user/add');
}
public function save()
{
$post=$this->input->post();
$res=$this->UserModel->insert($post);
if($res)
{
$data['value']=1;
$data['msg']='record added successfully';
}
else
{
$data['value']=0;
$data['msg']='record added failed';
}
$this->load->view('user/add',$data);
}
public function edit($id)
{
$data['user_edit']=$this->UserModel->getById($id);
}
}
?>
In the above code, we have called a getById of the UserModel method that does not exists in the Model class let's create the method in the model. Open application/models/UserModel.php in the UserModel define the function getById which has Id as a parameter and write select query including where clause inside the method or copy the code given below.
application/models/UserModel.php
<?php
class UserModel extends CI_Model
{
public function insert($data)
{
return $this->db->insert('user',$data);
}
public function read()
{
return $this->db->get('user')
->result_array();
}
public function getById($id)
{
return $this->db->where('id',$id)
->get('user')
->row_array();
}
}
?>
In the above code, we have return data of the row where id matches using row_array() method, next step is to pass the data to the view, add this line $this->load->view('user/edit.php') in application/controllers/User.php in user controller or copy the below-given code.
application/controllers/User.php
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->Model('UserModel');
}
public function index()
{
$data['users']=$this->UserModel->read();
$this->load->view('user/index',$data);
}
public function add()
{
$this->load->view('user/add');
}
public function save()
{
$post=$this->input->post();
$res=$this->UserModel->insert($post);
if($res)
{
$data['value']=1;
$data['msg']='record added successfully';
}
else
{
$data['value']=0;
$data['msg']='record added failed';
}
$this->load->view('user/add',$data);
}
public function edit($id)
{
$data['user_edit']=$this->UserModel->getById($id);
$this->load->view('user/edit',$data);
}
}
?>
Once we have passed the data to the view we need to display the values of the data in the view to do this create a new view in application/views/user and name it edit.php inside the view make an HTML form used to edit the record the code for the form is given below.
application/views/user/edit.php
<!DOCTYPE HTML>
<html>
<head>
<title>Codeginiter Basic CRUD Application</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<br>
<?php if(isset($value)&&isset($msg)) {?>
<div class="alert alert-<?=($value==1)?'success':'danger'?>">
<?=$msg?>
</div>
<?php }?>
<div class="page-header">
<h1>Create User</h1>
</div>
<form action="<?=base_url()?>index.php/user/update/<?=$user_edit['id']?>" method="post">
First Name
<input type='text' name='first_name' class='form-control' value="<?=$user_edit['first_name']?>" />
<br>
Last Name
<input type='text' name='last_name' class='form-control' value="<?=$user_edit['last_name']?>" />
<br>
Email
<input type='email' name='email' class='form-control' value="<?=$user_edit['email']?>" />
<br>
Password
<input type='password' name='password' class='form-control' value="<?=$user_edit['first_name']?>" />
<br>
<input type='submit' value='Update' class='btn btn-primary' />
<a href="<?=base_url()?>" class='btn btn-danger'>Back to User List</a>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Run the application by typing localhost/codeigniter-crud in your browser and you will see the following output mention below in the image.
output
Click on the edit button and you will redirect to the edit page and you will see following output given below in the image.
output
In the above image, you can see edit page where user can easily edit a record. Before updating the record we need to make a function in the controller that will carry data from the view. Open application/controllers/User.php in the user controller define a method update in the method definition request input data by adding this line of code $this->input->post() and pass this data with the id to a model function by adding this line of code $this->UserModel->updateRecord() the update record function will have two parameters the id of the record and the array of values and keys. For more see the code given below.
application/controllers/User.php
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->Model('UserModel');
}
public function index()
{
$data['users']=$this->UserModel->read();
$this->load->view('user/index',$data);
}
public function add()
{
$this->load->view('user/add');
}
public function save()
{
$post=$this->input->post();
$res=$this->UserModel->insert($post);
if($res)
{
$data['value']=1;
$data['msg']='record added successfully';
}
else
{
$data['value']=0;
$data['msg']='record added failed';
}
$this->load->view('user/add',$data);
}
public function edit($id)
{
$data['user_edit']=$this->UserModel->getById($id);
$this->load->view('user/edit',$data);
}
public function update($id)
{
$post=$this->input->post();
$res=$this->UserModel->updateRecord($id,$post);
if($res)
{
$data['value']=1;
$data['msg']='record Updated successfully';
}
else
{
$data['value']=0;
$data['msg']='record Update failed';
}
$data['users']=$this->UserModel->read();
$this->load->view('user/index',$data);
}
}
?>
In the above code, we have called UserModel function updateRecord that does not exist. Let's create the updateRecord method in the UserModel.php which will accept two parameters the record Id and the array of values. Open application/model/UserModel.php define a new method in the UserModel and in the method write update query the code for the query is given below.
application/models/UserModel.php
<?php
class UserModel extends CI_Model
{
public function insert($data)
{
return $this->db->insert('user',$data);
}
public function read()
{
return $this->db->get('user')
->result_array();
}
public function getById($id)
{
return $this->db->where('id',$id)
->get('user')
->row_array();
}
public function updateRecord($id,$data)
{
return $this->db->update('user',$data)
->where('id',$id);
}
}
?>
In the above code, we have added update query lets run the code and update the record .Type http://localhost/codeigniter-crud/ in the browser and click on the edit button and you will see a form containing some values see the below-given example.
Make desired changes in the values and click on update button. I am going to change the user email from hasnainriazkayani786@gmail to hasnainriaz@coderanks.com. When I will click on the update button it will update the record and load updated user list with a success message on the top of the screen as given below in the image.
You can see in the above image that we have successfully updated a record. In the next step, we will see how to delete a record from the database.
Step 2: Delete Record
Deleting a record from the database has the same logic we used early in updating a record. In the above image, you can see a delete button when we will click on the delete button it will ask for confirmation do you want to delete the record if you will click on yes it will call controller function name delete and pass it record id, the code for delete button is given below.
application/views/user/index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Codeginiter CRUD Application</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<?php if(isset($value)&&isset($msg)) {?>
<div class="alert alert-<?=($value==1)?'success':'danger'?>">
<?=$msg?>
</div>
<?php }?>
<br>
<div class="page-header">
<h1>Users List</h1>
</div>
<br />
<a href='<?=base_url()?>/index.php/user/add' class='btn btn-primary m-b-1em'>Add New User</a>
<br />
<table class='table table-hover table-responsive table-bordered'>
<br />
<?php if(count($users)>0){?>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<tbody>
<?php $count=1;
foreach($users as $user){ ?>
<tr>
<td> <?= $count++ ?> </td>
<td> <?= $user['first_name'] ?> </td>
<td> <?= $user['last_name'] ?> </td>
<td> <?= $user['email'] ?> </td>
<td>
<a href="<?=base_url()?>index.php/user/edit/<?=$user['id']?>" class='btn btn-primary m-r-1em'>Edit</a>
<a href="<?=base_url()?>index.php/user/delete/<?=$user['id']?>" onclick='return confirm("Do you want to delete")'
class='btn btn-danger'>Delete</a>
</td>
</tr>
</tbody>
<?php } }
else{
echo "<div class='alert alert-danger'>No records found.</div>";
}
?>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
In the above, we have call delete function of the controller which in undefined go to application/controllers/user.php and define the delete method with a single parameter of record id and in the delete, the method call the model method deleteRecord which will accept record id as a parameter and delete the record for the matched id. The same syntax will be followed as given below in the code.
application/controllers/User.php
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->Model('UserModel');
}
public function index()
{
$data['users']=$this->UserModel->read();
$this->load->view('user/index',$data);
}
public function add()
{
$this->load->view('user/add');
}
public function save()
{
$post=$this->input->post();
$res=$this->UserModel->insert($post);
if($res)
{
$data['value']=1;
$data['msg']='record added successfully';
}
else
{
$data['value']=0;
$data['msg']='record added failed';
}
$this->load->view('user/add',$data);
}
public function edit($id)
{
$data['user_edit']=$this->UserModel->getById($id);
$this->load->view('user/edit',$data);
}
public function update($id)
{
$post=$this->input->post();
$res=$this->UserModel->updateRecord($id,$post);
if($res)
{
$data['value']=1;
$data['msg']='record Updated successfully';
}
else
{
$data['value']=0;
$data['msg']='record Update failed';
}
$data['users']=$this->UserModel->read();
$this->load->view('user/index',$data);
}
public function delete($id)
{
$res=$this->UserModel->deleteRecord($id);
if($res)
{
$data['value']=1;
$data['msg']='record Deleted successfully';
}
else
{
$data['value']=0;
$data['msg']='record Delete failed';
}
$data['users']=$this->UserModel->read();
$this->load->view('user/index',$data);
}
}
?>
In the above code, we called the deleteRecord method of the User Model which is not defined. Let's define the method go to application/models/UserModel.php define a method name it deleteRecord has one parameter record ID using the id the Record will be deleted from the database by delete query for the example see the code given below.
application/models/UserModel.php
<?php
class UserModel extends CI_Model
{
public function insert($data)
{
return $this->db->insert('user',$data);
}
public function read()
{
return $this->db->get('user')
->result_array();
}
public function getById($id)
{
return $this->db->where('id',$id)
->get('user')
->row_array();
}
public function updateRecord($id,$data)
{
return $this->db->where('id',$id)
->update('user',$data);
}
public function deleteRecord($id)
{
return $this->db->where('id',$id)
->delete('user');
}
}
?>
We have written complete code to delete a code let's check the output http://localhost/codeigniter-crud/ you will see User list and with delete button click on the delete button you will see following output given below in the image
In the above image you can see when we click on delete button it is asking for confirmation our goal is to delete a record click on OK button it willl delete the record and show success message on the top of the screen as mention below in the image.
In the above image it shows that no record found beacuse we had only one record which was deleted. You can add more records in the database just by click on add new user button.We have successfully deleleted record from the database and with it we have completed our basic crud application in codeiginiter.