How can I briefly get the first result in an Ignit Code request?

I tried to return an object representing the log obtained based on its identifier in the 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 throws an error declaring an unexpected open right bracket ([).

I ended up actually scrolling through an array of 1 object object to return it, which is stupid 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 shorter way to return this object?

+4
source share
4 answers

Instead of capturing result() just use the row() method:

 $first_result = $query->row(); 
+8
source
 public function getJournal($id) { return $this->db->where('id', $id)->get('journals')->row() ?: NULL; // (requires PHP 5.3) } 
+3
source

First of all, you should limit your request 1:

 SELECT * FROM journals WHERE id='$id' LIMIT 1 

Secondly, the reason was that there was an unexpected open right bracket. This is because the result method in codeigniter returns an object, not an array. You can use ->result_array(); if you want, but ... but if you decide to limit 1, you could just return the object ...

Good luck.

+1
source
 public function getJournal($id) { $id = (int) $id; $query = $this->db->query("SELECT * FROM journals WHERE id = $id limit 1"); if ($query->num_rows() == 1) { return $query->row(); } return NULL; } 
+1
source

Source: https://habr.com/ru/post/1402329/


All Articles