Blog

Display all MySQL Table Rows 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
{
    // Get all rows from "users" table
    public function show_all_users()
    {
        return $this->db->query("SELECT * FROM users")->result_array();
    }

}
?>

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 admin()
    {
        // Assigns title tag
        $title_tag = 'Admin Dashboard';

        // Assigns if the user is admin or normal user
        $user_type = 'admin';

        // Load the model method to
        // display all rows from the "users" table
        $show_users = $this->UserDashboardModel->show_all_users();

        $this->load->view('userdashboard/admin', array('title_tag' => $title_tag, 'user_type' => $user_type, 'show_users' => $show_users));
    }
}
?>

View

<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

To Top ↑