1

I'm trying to query two values from database, with 2 different IDs and I need to get all the results on one array. This is part of my controller.

function account()
{
    $user_id = $this->session->userdata('user_id');
    $this->load->model("Site_model");
    $q = $this->Site_model->get_all_notify($user_id);
}

and here is the Model:

function get_user_data_by_id($id) {
    $this->db->where("id",$id);
    $q=$this->db->get("users");
    return  $q->result();
}

function get_all_notify($user_id) {
    $this->db->where("wanted_id",$user_id);
    $this->db->where("requests_id",1);
    $q=$this->db->get("intrested");
    foreach($q->result() as $row) {
        $user=$this->get_user_data_by_id($row->users_id);
    }
    return $user;
}

But when I print_r $q from controller I only get 1 row... but when I print_r $user I get all the results! Even with foreach nothing seems to work!

1
  • You are overwriting $user on each iteration of your loop. Commented Dec 17, 2013 at 19:59

1 Answer 1

4

You need to make array and store the users data in that,in current code the last iteration data from foreach will be return

$user=array();
foreach($q->result() as $row)
{
        $user[]=$this->get_user_data_by_id($row->users_id);
}
return $user;
Sign up to request clarification or add additional context in comments.

4 Comments

that worked for controller, but when I passed that variable who returned from Model to view like($this->load->view("include/template",$data); when I try to foreach it on view I can't access to any indexes, when I print_r $data it gives me the correct record as an array, but I need username index, I can't use $data['username'] or $data->username or $data[3]. How can I get any values from that array!!
In get_user_data_by_id($id) change $q->result(); to $q->row(); if there is only one user per passed id
Thank you very much! I was stuck for 5 hours you saved my days. I don't understand what was wrong though! what is wrong of sending ->row() or ->result()?
@yasser result() will returns the multiple records each record n array format and row() will give only one record

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.