Home » Php » php – Getting a field from the first row of a query

php – Getting a field from the first row of a query

Posted by: admin July 12, 2020 Leave a comment

Questions:

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!

How to&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;
}

Answer:

$query->first_row()->field