phpcodeigniterquery-builderresultset

How to get a single column value with CodeIgniter's query builder


I'm trying to pull a column value out of the database. I'm using CodeIgniter's query builder.

My Model Function

public function getcolumn($field, $table, $kfield, $key)
{
    $this->db->select($field);
    $this->db->from($table);
    $this->db->where($kfield, $key);
    $query = $this->db->get();
    $results = $query->result();
    return $results;
}

My Controller has:

public function users()
{ 
    $body['handle'] = $this->admin->getcolumn('handle', 'users', 'userid', $userid)

    $this->load->view('template/header');
    $this->load->view('admin/users', $body);
    $this->load->view('template/footer');
}

now when I print_r that variable in my view I get:

Array (
    [0] => stdClass Object (
        [handle] => Zanigade
    )
)

Since I'm trying to use this function as a global "grab and go" function without writing a ton of functions, why won't it just return the name? What am I doing wrong?


Solution

  • Put it all together using the "chaining" capability like so

    $results = this->db->get()->row()->$field;
    

    We get() one row() which (should) contain a field named $field.