0

I have been trying to get the CodeIgniter view to work with passing an object and an array at the same time, however it seems to break when I add the object.

Generally in CodeIgniter, when you create a variable in the Controller:$data['title'] = 'Welcome to CodeIgniter', you would access that variable in the View as: $title,

I need to pass my userdata which I retrieve by:

$data['title'] = 'welcome to codeigniter';
$this-db->where('id', $id);
$user = $this->db->get('users')->row();

$this->load->view('welcome', [
    'data' => $data,
    'user' => $user
]);

However, when I get to my view, $active is undefined, and I have to access the it by $data['title']

I have also tried adding everything to one array:

$data = array(
     'title' => 'welcome to codeigniter',
    'active' => 'home', 
     'user' => $user,
);

However, it did not work.

If this doesn't make sense I apologize, I am trying to explain my issue as best as I can, if you need further information, please let me know.

Thanks, Moonblaze

2
  • In your first example, you have not defined $active in your view array so that is expected. In your 2nd example, what is "it did not work" actually look like? Commented Dec 9, 2016 at 5:45
  • My apologies, I ment to type $title, not $active.. Commented Dec 9, 2016 at 5:46

3 Answers 3

2

you can do like this:

$data['title'] = 'welcome to codeigniter';
$this-db->where('id', $id);
$data['user'] = $this->db->get('users')->row();
$this->load->view('welcome', $data );

In view you can access like:

echo $title; //will print the 'welcome to codeigniter'
print_r($user); // will hold the resource of query
Sign up to request clarification or add additional context in comments.

Comments

0
$data['title'] = 'welcome to codeigniter';
$this-db->where('id', $id);
$user = $this->db->get('users')->row();
$data[user]=$user;
$this->load->view('welcome', $data );

You can use $title and $user in your view

3 Comments

This wouldn't work, as I am almost sure php would try and process the [data] and [user] as constants... I tried it just to double check, and yeah it did.
yes , use can use $data variable onlu istead id $data_new . but it will also work (no recommended) as the answer by @Suresh Kamrushi is most efficient .
I see where you were going with this, it's very similar with the now accepted answer, however you would need to change $data[user]=$user to $data['user']=$user`
0

//Controller

$data['title'] = 'welcome to codeigniter';
$data['user'] = $this->db->get('users')->row();

$this->load->view('welcome', $data);

//View

<?=$title?>
<?=print_r($user)?>

Comments

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.