![]() |
Illegal string offset error when returning one row with where clause - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10) +--- Thread: Illegal string offset error when returning one row with where clause (/showthread.php?tid=62124) |
Illegal string offset error when returning one row with where clause - dutchlab - 06-11-2015 I followed the tutorial about News items and have a question as to why the error 'Illegal string offset' happens in the foreach on the view when you pass a value from the controller to the model so that the get_where is used. I am using a database that has a users table with one row for my testing since I am new to CodeIgniter. If I supply the value 'jdoe' I retrieve the same row as I do when I do not supply the value. Supplying the value causes a PHP error: Illegal string offset 'username' in the view foreach loop. I did notice that the var_dump($data); out put is formatted different with 'jdoe' then without. with: array(1) { ["users"]=> array(4) { ["username"]=> string(6) "jdoe" ["password"]=> string(32) "5f4dcc3b5aa765d61d8327deb882cf99" ["email"]=> string(18) "[email protected]" ["clientdatabase"]=> string(6) "acme" } } without: array(1) { ["users"]=> array(1) { [0]=> array(4) { ["username"]=> string(6) "jdoe" ["password"]=> string(32) "5f4dcc3b5aa765d61d8327deb882cf99" ["email"]=> string(18) "[email protected]" ["clientdatabase"]=> string(6) "acme" } } } Controller: public function index() { $data['users'] = $this->home_model->get_users('jdoe'); var_dump($data); $this->load->view('home',$data); } Model: public function get_users($username = FALSE) { if ($username === FALSE) { $query = $this->db->get('users'); return $query->result_array(); } $query = $this->db->get_where('users', array('username' => $username)); return $query->row_array(); } View: <?php foreach ($users as $users_item): ?> <div class="main"> <?php echo $users_item['username'] ?> </div> <?php endforeach ?> RE: Illegal string offset error when returning one row with where clause - Avenirer - 06-12-2015 Well... that is because when you retrieve a single row is not the same as when you retrieve more than one row. you could do something like this: PHP Code: $query = $this->db->get_where('users', array('username' => $username)); And then you would have the same format as a multirow result (with only one element...). You could also do something like this to do some DRY programming: PHP Code: public function get_users($username = NULL) |