phparrayscodeigniterresultset

How to access the a specific field value in the first row of a CodeIgniter query result set?


This is fairly simple and I'm even doing something similar in a different part of the site and it works.

I'm getting this error:

Message: Undefined index: username

function add($file)
{
    $user = $this->session->userdata('userid');
    $query = $this->db->query("SELECT username FROM users WHERE ID = '$user'");
    $result = $query->result_array();
    echo var_dump($result);
    echo '<br />';
    echo $result['username'];
    //........

When I echo a var_dump, I get the following:

array(1) {
    [0]=> object(stdClass)#20 (1) {
        ["username"]=> string(5) "jesse"
    }
}

Solution

  • If you want to access username from result array you should use a foreach for that

    But I guess in your case you are getting only one record from your query

    So you can use row_array() instead of result_array().

    In this case (using row_array()), you can access username as $result["username"].