phpmysqlcodeigniteractiverecordresultset

How to convert Codeigniter's CI_DB_mysql_result result object into an accessible array?


In my model I have this snippet

$this->db->select('*');
$this->db->from('User');
$this->db->where('email', $mail);
$query = $this->db->get();
return $query;

As far as I know, $query is an array (a set of results), I want to retrieve an specific value of a field in that array to return it or to assign it to another variable, the question is HOW?

I'd like to do something like this

$value = $query['first_field_of_resultset'];
return $value;

Solution

  • extending Johns answer, you need to cover yourself in case nothing comes back so in your model method:

    // make sure we have a result
    if ( $query->num_rows() == 1 ) 
    {  
    // assign the result 
    $user = $query->row();  
    // pull out the field you want 
    $value = $user->first_field_of_resultset;
    // return it
    return $value ; 
    }
    else { return FALSE; }
    

    Then in your controller, say if the model is called user_model

    if(! $value = $this->user_model->getUser($email) )
    {
     // boo hoo no results
    } 
    else
    {
    // success
    }
    

    And of course this assumes you have run $email through CI form validation to make sure it is a valid email -- before sending to your database.