0

Maybe I have some misunderstanding in this part of the Array procedure/syntax...

What I'm wondering is why once I get the result from the db I HAVE to go thru a foreach or other kind of loop.

Let's say I know I'll only get ONE result from the query:

$query = $this->db->query("MY QUERY LIMIT 1");

Up to now I'll have to go thru it with a loop:

foreach ($query->result() as $row){
   echo $row->title;
   echo $row->name;
   echo $row->body;
}

Is there a way to get the item printed without a loop (for, foreach or other)? Like:

$query->result()->title;

//OR
$query->result()[0]

Or something else?

The above method I tried of course are not working...

Perhaps is just a bad practice. Is it impossible? Doable? Or...?

3 Answers 3

3

If you want to get only one result, use row() instead
(or row_array() if you want it as an array instead of an object)

row() returns only the first row in the dataset (no matter how many there are, but usually it's used when you only have one row).

$row = $this->db->query("MY QUERY LIMIT 1")->row();
echo $row->title;
echo $row->name;
echo $row->body;

as an array:

$row = $this->db->query("MY QUERY LIMIT 1")->row_array();
echo $row['title'];
echo $row['name'];
echo $row['body'];

Sidenote, you can also return a specific row by passing its number:

$row = $query->row(5); //works also for its analogue ->row_array(5)

For reference, check the manual here

Sign up to request clarification or add additional context in comments.

Comments

0

Yes you just try like this

$data = $query->result();
echo $data->title;

Comments

0

Try this

get result an object

$row = $this->db->query("MY QUERY LIMIT 1")->row();
echo $row->title;

Hope it will help

1 Comment

Did you not see the more detailed & similar answer by Damien ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.