Martin M
Martin M

Reputation:

Pass result of mysql_fetch_object() to a function does not work

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

Upvotes: 1

Views: 1217

Answers (3)

David Oakley
David Oakley

Reputation: 408

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

Upvotes: 0

Tom Haigh
Tom Haigh

Reputation: 57815

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());
}

Upvotes: 0

KyleFarris
KyleFarris

Reputation: 17548

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)

Upvotes: 1

Related Questions