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!
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).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With