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?
Instead of grabbing the result()
, just use the row()
method:
$first_result = $query->row();
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