Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a field from the first row of a query

I'm using Codeigniter's Active Record Class. So the query looks something like this:

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

Now, what's the fastest way to get a field from the first row? Would $query->first_row->field; work?

Thanks!

like image 755
skndstry Avatar asked Dec 06 '10 23:12

skndstry


People also ask

How do I select the first row of a group in SQL?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ). You assign the row numbers within each group (i.e., year).


1 Answers

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;
}
like image 157
NexusRex Avatar answered Sep 23 '22 14:09

NexusRex