With mysql_fetch_array I can easily count the rows returned. Can I do something similar with mysql_fetch_object?

David Rhoden picture David Rhoden · Jan 3, 2011 · Viewed 38.9k times · Source

(Apologies if necessary--my first Stack Overflow question. I'll be happy to modify it if anyone has suggestions. I have looked for an answer but I'm afraid my grasp of the terminology isn't good enough to make a complete search.)

I'm accustomed to using mysql_fetch_array to get records from a database. When getting records that way, mysql_num_rows gives me a count of the rows. On my current project, however, I'm using mysql_fetch_object. mysql_num_rows doesn't seem to work with this function, and when I do a 'count' on the results of the query I get the expected answer: 1 (one object).

Is there a way to 'see into' the object and count the elements inside it?

Answer

ehudokai picture ehudokai · Jan 3, 2011

The function mysql_num_rows works on your result resource, not your object row.

Example

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$sql = "SELECT id, name FROM myTable";

$result = mysql_query($sql, $link);

$rowCount = mysql_num_rows($result);

while($row = mysql_fetch_object){
    echo "id: ".$row->id." name: ".$row->name."<BR>";
}
echo "total: ".$rowCount;