• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple question : can't define query result without foreach ?! And I thought I wasn't a noob anymore ....

#1
[eluser]Dagobert Renouf[/eluser]
Hello everyone.

I'm facing a problem I'm sure will find a quick and efficient answer, as I'm stucked right here !

When you want to display mysql query results, you do this :

Code:
foreach($query->result() as $row)
{
     echo $row->id;
}

And this works fine.

However I'm having a ONE RESULT ONLY query running, and I want to do this to simplify things:

Code:
$row = $query->result();
echo $row->id;

Why does it return an error ?
Code:
Message: Trying to get property of non-object

#2
[eluser]kevinh21[/eluser]
Hi
I don't really know..but can you try this ?

if ($query->num_rows() > 0)
{
$row = $query->row();

echo $row->id;
}

#3
[eluser]Sumon[/eluser]
You can use...
Code:
$query = $this->db->query("SELECT * FROM member_profile WHERE member_id='$MemberId'");
if ($query->num_rows() > 0)
{
  $Result=$query->row_array();
  echo $Result['id'];
}
else
  return FALSE;

#4
[eluser]Zeeshan Rasool[/eluser]
Well , this can not work

$row = $query->result();
echo $row->id;

Bcoz , there is an array in $query->result()
so it does'nt work

#5
[eluser]Dagobert Renouf[/eluser]
thank you guys.

It works.

#6
[eluser]xwero[/eluser]
the result method returns an array filled with objects so in order to get the id property of the first object in the array you would have to do
Code:
$rows = $query->result();
$row = $rows[0];
echo $row->id;
Of course this can be cleaned up if you use
Code:
$row = $query->row();
echo $row->id;

#7
[eluser]xwero[/eluser]
Wow i'm a bit chocked three people responded and none of then suggest the row method :-S

#8
[eluser]Dagobert Renouf[/eluser]
sorry guys, XWERO owned you all :-D.

Thanks man.

#9
[eluser]Scriptor[/eluser]
Gah, xwero beat me to it. Still, kinda frightening so many haven't heard of row(), it's not like it's in the User Guide Wink


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.