views:

75

answers:

4

The result is always 1:

$sql = 'SELECT COUNT(Vote) FROM ' . $table;
$res = mysql_query($sql, $conn);
$vote_total = mysql_num_rows($res);

I ran the $sql query in phpMyAdmin and it returns 3, so the query is not the problem. $vote_total is initialized globally to 0, so that 1 is coming from somewhere. What other information do I need to provide to make helping me easier?

Thanks, Ryan

+7  A: 

mysql_num_rows returns the number of selected rows and not the fields of a certain row. Use mysql_fetch_row to fetch the row you have selected with your query:

$sql = 'SELECT COUNT(Vote) FROM ' . $table;
$res = mysql_query($sql, $conn);
$row = mysql_fetch_row($res);
$vote_total = $row[0];

You could also use mysql_result to fetch a row and get a certain field:

$vote_total = mysql_result($res, 0, 0);

This fetches the first row (zero based) and returns the first field (zero based).

Gumbo
In this case all I need to do is figure out how many rows there are in the table. So for that I can use mysql_num_rows. But the "Vote" column contains one of three values: either A, B, or C. If I now want to count how many times A, B, or C show up, I would also use num_rows, right? Fetch row is only when I need the data, correct? Thanks, Ryan.
Ryan S.
Actually, I guess not, because mysql_num_rows didn't work. Are you saying that the value that represents the amount of rows is stored in a field and that's why I need to get that field with either mysql_fetch_row or _array?
Ryan S.
@Ryan S.: You would need to use a different query: `SELECT Vote, COUNT(Vote) FROM table GROUP BY Vote`. This will return three rows (one for each *Vote* value) with two fields (*Vote* and the number of rows with that value).
Gumbo
Great! Thank you!
Ryan S.
+2  A: 

There will only ever be one row. And in that row will be the count of votes.

$sql = 'SELECT COUNT(Vote) FROM ' . $table;
$res = mysql_query($sql, $conn);
$vote_array = mysql_fetch_array($res);
$vote_total = $vote_array[0];

If you want to count the number of votes with mysql_num_rows, you have to select ALL of the rows.

Chacha102
To select all rows, that's done in the WHERE clause?
Ryan S.
+1  A: 

The tricky part is that even when the sql query contains a COUNT() statement, it is still a query result like any other. MySQL will return a row containg a single column with the number of rows that would have been returned, should you have issued a reglar query. mysql_num_rows() on the other hand, just counts the number of rows in the result of the query that was actually executed. In this case it is always a single row.

What you want is:

$sql = 'SELECT COUNT(Vote) FROM ' . $table;
$res = mysql_query($sql, $conn);
$data = mysql_fetch_row($res);
$vote_total = $data[0];
Emil H
+2  A: 

That query does return only one row. What you want is to retrieve the value from the query:

$row = mysql_fetch_array($res);
$vote_total = $row[0];
CanSpice