views:

185

answers:

3

I have the following problem:

public function row2Partner($row){
  echo $row->PartnerID;
}

public function main(){
  $query = "SELECT PartnerID, PartnerName FROM Partner";
  $result = mysql_query($query);
  $this->row2Partner(mysql_fetch_object($result));
}

This gives me the error in row2Partner(): Trying to get property of non-object

But $row is an Object! And if I do echo $row->PartnerID in the main function, it works.

Any ideas?

Thx, Martin

+1  A: 

If your result returns more than one row, your object is going to be multi-dimensional. I'm pretty sure you can do something like this if you just want to echo the first one:

public function row2Partner($row){ echo $row[0]->PartnerID; }

If you are looking for only one result, I would also limit my query to just one...

SELECT PartnerID, PartnerName FROM Partner LIMIT 1

If you want to echo out all your rows (in the case of multiple) results, you can do this:

public function row2Partner($row){ 
    foreach($row as $result) {
        echo $result->PartnerID; 
    }
}

Hope that helps.

PS Just as a sidenote, I tend to like to use associative arrays when dealing with MySQL results--it just makes more sense to me. In this case, you would just do this instead:

mysql_fetch_assoc($result)
KyleFarris
Looks good. This works great - I had the problem that the function got called twice, once with valid $row data, once with an empty one.Thanks a lot for the quick reply.
A: 

Are you sure that mysql_query() has executed the query successfully, and also that there is actually a row being returned? It might be worth checking it, e.g.

//check query executed ok
if ($result = mysql_query($query)) {
    //check there is actually a row
    if ($row = mysql_fetch_object($result)) {
        $this->row2Partner($row);
    } else {
        //no data
    }
} else {
    //error
    die(mysql_error());
}
Tom Haigh
A: 

Hi,

Best thing I can think of is that you may need to pass by reference rather than by value. Change your function declaration to

public function row2Partner(&$row)

Hope that helps, David

David Oakley