john smith john smith - 7 months ago 97
PHP Question

codeigniter single result without foreach loop

I am using codeigniter to get a single result from the db, like this:

$user = $this->db->query("SELECT * FROM users LIMIT 1");


I am then getting the returned object and looping trough it, this way:

foreach ($user->result() as $row) { ... }


As you can imagine, there is not point in using the loop, since there is only one result. Is there a way to get users parameters without looping? Something among this line:

echo $user['name'];


Thanks in advance.

Answer
$user = $this->db->query("SELECT * FROM users LIMIT 1")->row();

for having it as an object ( echo $user->name;)

$user = $this->db->query("SELECT * FROM users LIMIT 1")->row_array();

for having is as an array ( echo $user['name']; );

$user = $this->db->limit(1)->get('users')->row(); //or ->row_array();

using AR;

$row = $user->first_row();

to get the first row out of a result set ($this->db->result()), as an object (default);

$row = $user->first_row('array');

to get the first row out of a result set, as an array;

$row = $user->row_array(1);

to return a specific row (first, in this case. Just pass the <N> of the row). Works also for $user->row(1);