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

(Sorry, if necessary, my first question is about stack overflow. I will be happy to change it if anyone has suggestions. I have been looking for an answer, but I'm afraid that my understanding of the terminology is not enough to do a full search.)

I'm used to using mysql_fetch_array to get records from a database. When retrieving records this way mysql_num_rows gives me the number of rows. However, in my current project, I am using mysql_fetch_object. mysql_num_rows does not seem to work with this function, and when I do a โ€œcountโ€ based on the query results, I get the expected response: 1 (one object).

Is there a way to โ€œseeโ€ an object and count the elements inside it?

+6
oop php mysql mysql-num-rows
source share
4 answers

The mysql_num_rows function works on your result resource, not on the line of your object.

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; 
+11
source share

Try count( (array)$object ) .

+2
source share

If you use it in a procedural style (i.e. mysql_fetch_object () vs. $ result-> fetch_object ()), mysql_num_rows should work just like you would with mysql_fetch_array (). Could you post some sample code?

0
source share
 <?php mysql_connect("localhost", "user", "password"); mysql_select_db("database"); $result = mysql_query("SELECT SQL_CALC_FOUND_ROWS * FROM table"); $countQuery = mysql_query("SELECT found_rows() AS totalRows"); $rows = mysql_fetch_object($countQuery); echo $rows->totalRows; ?> 

Hope this is helpful :)

0
source share

All Articles