Blog
Delete a Database Row using CodeIgniter with Model, Controller, and View Code Examples
Posted on July 2, 2015 in CodeIgniter, MVC, MySQL, PHP by Matt Jennings
Model
<?php
class UserDashboardModel extends CI_Model
{
// After admin is logged in
// delete user
public function delete_user($product_id)
{
$this->db->query("DELETE FROM users WHERE id = $product_id");
}
}
?>
Controller
<?php
class UserDashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load the UserDashboardModel on all pages
$this->load->model('UserDashboardModel');
$this->output->enable_profiler();
}
public function deleteuser($user_id)
{
$this->UserDashboardModel->delete_user($user_id);
$this->session->set_flashdata("delete_success", "<p><strong>You have sucessfully deleted a user with the ID of <em>$user_id</em>.</strong></p>");
redirect(base_url() . 'dashboard/admin');
}
}
?>
View
<?php
// If the admin sessin variable DOESN'T exist
// redirect to home page
if(!$this->session->userdata('admin_session'))
{
redirect(base_url());
}
?>
<?php
echo $this->session->flashdata('delete_success');
?>
<table id="admin-dashboard-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>User Level</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
<?php
foreach(array_reverse($show_users) as $row) {
$first_last_name = $row['first_name'] . ' ' . $row['last_name'];
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><a href="<?php echo base_url() . 'dashboard/user/' . $row['id']; ?>"><?php echo $row['first_name'] . ' ' . $row['last_name']; ?></a></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['created_at']; ?></td>
<td><?php echo $row['user_level']; ?></td>
<td class="no-border"><a href="<?php echo base_url() . 'users/edit/' . $row['id']; ?>">edit</a></td>
<td><a href="<?php echo base_url() . 'dashboard/admin/delete/' . $row['id']; ?>">delete</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
Leave a Reply