Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

(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?

like image 821
David Rhoden Avatar asked Jan 03 '11 20:01

David Rhoden


People also ask

What is the difference between mysql_fetch_array and Mysql_fetch_object?

The mysqli_fetch_object() function returns objects from the database, whereas mysqli_fetch_array() function delivers an array of results. This will allow field names to be used to access the data.

What is the difference between mysql_fetch_array () and mysql_fetch_assoc ()?

Difference: mysql_fetch_assoc() will always assing a non-secuencial key (like "color" and not a number). mysql_fetch_array() will assing a number key if there are not "word" key (0 and not "color" if there are not "color") but, you can choose to assing of key with a parameter...

What does mysql_fetch_row () function do?

The fetch_row() / mysqli_fetch_row() function fetches one row from a result-set and returns it as an enumerated array.

How can I count the number of rows in Mysqli using PHP?

We can get the total number of rows in a table by using the MySQL mysqli_num_rows() function. Syntax: mysqli_num_rows( result ); The result is to specify the result set identifier returned by mysqli_query() function.


2 Answers

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;
like image 63
ehudokai Avatar answered Sep 26 '22 22:09

ehudokai


Try count( (array)$object ).

like image 43
simshaun Avatar answered Sep 23 '22 22:09

simshaun