Welcome Guest, Not a member yet? Register   Sign In
Illegal string offset error when returning one row with where clause
#1

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 ?>
Reply
#2

(This post was last modified: 06-12-2015, 12:48 AM by Avenirer. Edit Reason: a new approach added... )

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));
return 
$query->result_array(); 


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)
{
 
 if (isset($username))
 
 {
 
   $this->db->where('username',$username);
    
// you can also add a limit if you want...
    //$this->db->limit(1); 
 
 }
 
 $query $this->db->get('users');
 
 return $query->result_array();

Reply




Theme © iAndrew 2016 - Forum software by © MyBB