Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concisely return the first result in a Code Igniter query?

I tried to return an object representing a journal retrieved based on its ID in a model.

public function getJournal($id) {
    $query = $this->db->query("SELECT * FROM journals WHERE id='$id'");
    return ($query->num_rows() == 1) ? ($query->result())[0] : NULL;
}

However, PHP issues an error declaring an unexpected open right bracket ([).

I ended up actually looping through the array of 1 object entity to return it, which is silly but works.

public function getJournal($id) {
    $query = $this->db->query("SELECT * FROM journals WHERE id='$id'");
    if ($query->num_rows() == 1) {
        foreach ($query->result() as $journal)
            return $journal;
    }
    else
        return NULL;
}

What is a more concise way to return this object?

like image 457
John Hoffman Avatar asked Dec 13 '22 04:12

John Hoffman


1 Answers

Instead of grabbing the result(), just use the row() method:

$first_result = $query->row();
like image 146
rjz Avatar answered Dec 22 '22 00:12

rjz