Raja
Raja

Reputation: 368

Output the results of the SQL query in CodeIgniter is not displaying

I'm trying to learn the MVC approach using CodeIgniter and I'm stuck with trying to display the results of the SQL query to the view. I'm using the method binding way as I've heard its secure with escaping variables when writing SQL queries.

Here's the model:

public function getuser_id()
{
    $this->db->select('id')->from('users')->where('email', $this->session->userdata('email'));
    $query = $this->db->get();
}

Here's the controller:

public function members()
{
    if ($this->session->userdata('is_logged_in'))
    {
        $data['title'] = 'Members Page';
        $this->load->model('model_users');
        $data['uid'] = $this->model_users->getuser_id();
        $this->load->view('members', $data);
    }
    else 
    {
        redirect('main/restricted');
    }
}

The view simply does echo $uid;. All I want to do is print the user ID on the screen. I believe that the issue lies in the getuser_id() function. The profiler says that the query is being executed on the page but I am not seeing a result. The data definitelythere exists in the database.

Any help would be greatly appreciated!

Upvotes: 1

Views: 2655

Answers (1)

Jeemusu
Jeemusu

Reputation: 10533

There are a few problems with your code.

Firstly, instead of accessing the session directly in the model. You should access it in the controller, and pass the data to the model as a parameter of the getuser_id() function.

Secondly, you are making a query but not returning the data from it. To do this you will need to amend the line:

$query = $this->db->get();

To be one of the following, depending on your preference:

$query = $this->db->get()->result(); //returns results as an object $query = $this->db->get()->result_array(); // returns results as an array

More info on returning results here. http://ellislab.com/codeigniter/user-guide/database/results.html

Thirdly, you dont pass any data from your model back to your controller. You need to add a return $your_data to the end of the models function.

Updated Model:

public function getuser_id($user_email)
{
    $this->db->select('id')->from('users')->where('email', $user_email);
    $query = $this->db->get()->result_array();

    return $query; // Don't forget to return your results!

}

Here's the controller:

public function members()
{
    if ($this->session->userdata('is_logged_in'))
    {
        $data['title'] = 'Members Page';
        $this->load->model('model_users');
        $user_email = $this->session->userdata('email');
        $data['uid'] = $this->model_users->getuser_id($user_email);
        $this->load->view('members', $data);
    }
    else 
    {
        redirect('main/restricted');
    }
}

Upvotes: 2

Related Questions