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

4

8

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

Zeal answered 3/1, 2011 at 20:34 Comment(1)
nice, but you should ditch mysql_* function, replace it with mysqli, pdo (mysqli->num_rows is a property set to number of rows returned)Pendent
M
14

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;
Mcniel answered 3/1, 2011 at 20:47 Comment(1)
I think mysql_fetch_object in your while() should actually be mysql_fetch_object($result)Physician
L
2

Try count( (array)$object ).

Leastwise answered 3/1, 2011 at 20:41 Comment(1)
This gave me a different answer. It returned the number of fields in my SELECT query.Zeal
T
0

If you're using it in procedural style (i.e. mysql_fetch_object() vs. $result->fetch_object()), mysql_num_rows should work exactly the same way as when using mysql_fetch_array(). Could you post some sample code?

Thimbu answered 3/1, 2011 at 20:42 Comment(3)
I am using it this way (in procedural style). Should I not be?Zeal
No, using it procedurally is OK. Could you post a snippet of your code?Thimbu
At this point the code has changed so much it wouldn't be relevant. Thanks for asking.Zeal
M
0
<?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;
?>

I hope this is useful :)

Marrakech answered 3/1, 2011 at 21:11 Comment(1)
It's interesting (I wasn't aware of this kind of SELECT SQL_CALC_FOUND_ROWS), but I want to do other things besides just count the rows.Zeal

© 2022 - 2024 — McMap. All rights reserved.