phpcodeigniterresultset

Get a single field value from the first row of a query in CodeIgniter


I'm using CodeIgniter's active record class and the query looks something like this:

$query = $this->db
    ->get_where('Table', array('field' => $value));

What's the fastest way to get a field value from the first row?

Would $query->first_row->field; work?


Solution

  • Though fast is wonderful, errors aren't! Make sure you always check for results before trying to access them with ($query->num_rows() > 0)

    Fastest (most concise) way:

    $query = $this->db->get_where('Table', array('field' => $value));
    
    echo(($query->num_rows() > 0) ? $query->first_row()->field : 'No Results');
    

    Essentially the same as:

    $query = $this->db->get_where('Table', array('field' => $value));
    if($query->num_rows() > 0)
    {
        echo $query->first_row()->field;
    }
    else
    {
        echo 'No Results';
    }
    

    For multiple fields use:

    $query = $this->db->get_where('Table', array('field' => $value));
    
    if ($query->num_rows() > 0)
    {
        $row = $query->row(); 
    
        echo $row->title;
        echo $row->name;
        echo $row->body;
    }