Blog

Display a Single MySQL Table 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
{

    // Show a single table row
    public function show_single_user($user_id)
    {
        return $this->db->query("SELECT * FROM users WHERE id = {$user_id}")->row_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 adminupdateuser($user_id)
    {
        // Assigns title tag
        $title_tag = 'Edit User';

        // Get single user
        $show_single_user = $this->UserDashboardModel->show_single_user($user_id);

        $this->load->view('userdashboard/admin_update_user', array('user_id' => $user_id, 'title_tag' => $title_tag, 'show_single_user' => $show_single_user));

    }

}
?>

View

<form action="<?php echo base_url() . 'users/edit/process/' . $show_single_user['id']; ?>" method="post" class="side-by-side-form">
    <input type="hidden" name="user_details_update"/>
    <p>
        <label for="email">Email:</label><br />
        <input type="text" name="email" value="<?php echo $show_single_user['email']; ?>"/>
    </p>

    <p>
        <label for="first_name">First Name:</label><br />
        <input type="text" name="first_name" value="<?php echo $show_single_user['first_name']; ?>"/>
    </p>

    <p>
        <label for="first_name">Last Name:</label><br />
        <input type="text" name="last_name" value="<?php echo $show_single_user['last_name']; ?>"/>
    </p>

    <p>
        <select name="user_level">
            <?php
            // Assign the user level option
            // tags to display with the "Admin"
            // first ONLY if user record is
            // for an admin
            if($show_single_user['user_level'] == 'admin')
            {
                $first_user_level = 'admin';
                $second_user_level = 'normal';
            }
            else
            {
                $first_user_level = 'normal';
                $second_user_level = 'admin';
            }
            ?>
            <option value="<?php echo  $first_user_level;?>"><?php echo ucfirst($first_user_level); ?></option>
            <option value="<?php echo  $second_user_level;?>"><?php echo ucfirst($second_user_level); ?></option>
        </select>
    </p>

    <p>&nbsp;</p>
    <p>
        <input type="submit" value="Update"/>
    </p>
</form>

Leave a Reply