Search code examples
phpcodeigniterresultset

Are there any alternatives to access the results of a query that will only produce one row?


I query a table on it's primary index, and it will produce only one row result.

$query= $this->db->query('SELECT Name FROM people WHERE PersonID = 1');

To now access that 'Name', it seems to me that I have to always iterate through the result set.

foreach ($query->result() as $row)  {
    echo $row->Name;
}

Does one always have to iterate through the resultset? I understand there maybe good reasons for it, but is it absolutely required in all situations? Is there no way to just go straight to something like

echo $query->result()->Name     //pseudo code - won't actually work

(This is PHP / CodeIgniter)


Solution

  • $query->first_row()->Name
    

    https://www.codeigniter.com/user_guide/database/results.html