Forum Moderators: coopster

Message Too Old, No Replies

Counting queried MySQL rows

         

itledi

3:16 pm on Dec 5, 2007 (gmt 0)

10+ Year Member



Hello,

I wanted to output content from a MySQL table by an id. The id column is an auto_increment, so each value should be unique.

I also wanted to pull how many rows were returned by my query. Ideally there should be only 1 row pulled, but I would imagine 0 rows would be pulled if there wasn't a row with a matching id.

I used mysql_affected_rows to count the number of rows queried, and it seems to work but I'm hesitant. PHP.net says that mysql_affected_rows "Get[s] the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query..." I'm doing none of these operations.

I'm worried that just because its working for me and my sample set right now, it may be problematic in the future.

Is there a more appropriate way to count the number of rows queried?

Thank you for your input.

$data=mysql_fetch_array(mysql_query("SELECT * FROM table WHERE id='$id'"));
$rows=mysql_affected_rows();

ytswy

4:15 pm on Dec 5, 2007 (gmt 0)

10+ Year Member



Hi itledi, Welcome to WebmasterWorld!

There is a Count() function built into mysql which may be what you're looking for - more info here [dev.mysql.com] and here [dev.mysql.com].

mooger35

4:42 pm on Dec 5, 2007 (gmt 0)

10+ Year Member



mysql_num_rows [ca.php.net] would also give you what you are looking for if you're using SELECT or SHOW.

itledi

1:09 am on Dec 7, 2007 (gmt 0)

10+ Year Member



Thank you both for your replies.

I liked how the mysql command seemed specific for what I wanted, and not seemingly workaround like count, but when I tried mysql_num_rows I get an error of:

Wrong parameter count for mysql_num_rows(), I get the error "Wrong parameter count for mysql_num_rows()" with no rows counted at all.

Might I be misusing this?

Thanks

coopster

3:59 pm on Dec 7, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Sounds like it. Double check how to use the function in the link provided earlier.

itledi

9:39 pm on Dec 7, 2007 (gmt 0)

10+ Year Member



Ahh, that was it! Works great now.

Thanks everyone for your help. The new, improved code is as follows:

$query=mysql_query("SELECT * FROM table WHERE id='$id'");
$data=mysql_fetch_array($query);
$rows=mysql_num_rows($query);