skndstry
skndstry

Reputation: 671

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?

Upvotes: 7

Views: 10683

Answers (3)

mickmackusa
mickmackusa

Reputation: 47992

You won't need to check num_rows() if you null coaleace the returned value from ->row(). row() return an object or null.

return $this->db
    ->get_where('Table', ['field' => $value])
    ->row()
    ->field ?? null;

Or, more concisely use null-safe property access.

return $this->db
    ->get_where('Table', ['field' => $value])
    ->row()
    ?->field;

Both of the above will return null if there are no rows or the field value in the first row is null. The fail-safe script will emit a Warning if there is no field property in the object generated by row().

Upvotes: 0

NexusRex
NexusRex

Reputation: 2160

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;
}

Upvotes: 10

Ish
Ish

Reputation: 29586

$query->first_row()->field

Upvotes: 8

Related Questions