Page 1 of 1

Return all the mysql_fetch_object with an array - solved

Posted: Mon Jun 05, 2006 10:56 am
by bogdan
Hi, I have this portion of code that returns from sql - either a "describe" or a "select *".

Code: Select all

if ($sqlViewType==="describe")
   {
     $sqlCmd = "$sqlViewType $sqlTableName;";   
   }
   elseif ($sqlViewType==="select")
   {
      $sqlCmd = "$sqlViewType * from $sqlTableName;";
   }
   else
   {
      $this->sqlError = "please give a proper command \n\n";
      return false;
   }
   
   if (! $this->Exec($sqlCmd)) 
     return false;
   
   $res = mysql_fetch_object($this->sqlHandler);
   print_r($res);
Now the thing is this returns only the first row, for example running a "describe" from table A (name, address) would return only the name....

If I do this:

Code: Select all

if ($sqlViewType==="describe")
   {
     $sqlCmd = "$sqlViewType $sqlTableName;";   
   }
   elseif ($sqlViewType==="select")
   {
      $sqlCmd = "$sqlViewType * from $sqlTableName;";
   }
   else
   {
      $this->sqlError = "please give a proper command \n\n";
      return false;
   }
   
   if (! $this->Exec($sqlCmd)) 
     return false;
   
   $res = mysql_fetch_object($this->sqlHandler);
   print_r($res);
  $res = mysql_fetch_object($this->sqlHandler);
   print_r($res);    /////////// here I just doubled the $res and the print --- so now I have the address returned also
So I figured I must need an array for it...... just too tyred to think at the moment.

Regards, Bog

Posted: Mon Jun 05, 2006 11:04 am
by bdlang
First thing, don't use '===' comparison operator in your code; you're comparing a string, not a string TYPE. Use '==' to compare the value stored in $sqlViewType. You might consider using a switch() statement rather than the if-else you have as well; I prefer switch() in those cases, it makes it easier to remove / add options later on rather than having a nest of if-elseif-else statements.

Ok, on to the issue at hand. You most certainly expect to return more than a single record from the resultset, correct? Calling mysql_fetch_*() by itself will only fetch a single record, and in the case of a multiple record resultset, the last record. You need to feed it through a while() loop, such as

Code: Select all

while( $res = mysql_fetch_object($this->sqlHandler) ) {
    // do something here, either print out results, or store in an array
}

Posted: Mon Jun 05, 2006 11:16 am
by bogdan
Thanks a lot, sorted out .
Used a while and it solves it...

I will also look into it to use switch() as you sugested, makes sense :)


edit: I used mysql_fetch_assoc instead, I want the results as an array rather than objects.

Regards.