Chris
Chris

Reputation: 115

MySQL Select Count and rowCount

I want to check how many B > 0 there are in my table. My Table looks like this:

+---A---+---B---+
|   x   |   0   | 
|   x   |   0   |
|  ...  |  ...  |        
-----------------

Column B is important. If there is no row > 0 then I wouldn't have run another code and could simply echo a text. If there is one row with B>0 then I need to know that.

I tried this so far, which gives me the result shown in the picture. And I checked the table, it's right.

"SELECT COUNT(*) FROM table
                WHERE B>0";

enter image description here

I tried to examine the 0 with the code below but I gives me 1 as result. Probably because it counts the row above in the picture.

$statement_count = $pdo->prepare($check);
$statement_count->execute(); 
$count = $statement_count->rowCount();
echo $count;

So, what can I do instead?

Upvotes: 0

Views: 1816

Answers (3)

Paul Spiegel
Paul Spiegel

Reputation: 31812

Your query always returns exactly 1 row. You need to read the value in that row. To read only one column from one row you can use PDOStatement::fetchColumn:

$count = $statement_count->fetchColumn();

Upvotes: 1

Lelio Faieta
Lelio Faieta

Reputation: 6689

If you do:

$check = "SELECT B FROM table WHERE B>0"
$statement_count = $pdo->prepare($check);
$statement_count->execute(); 
$count = $statement_count->rowCount();
echo $count;

It will echo the number of rows that match your criteria. if you apply rowCount on a query that do SELECT COUNT it will by definition return 1 because the query will always return one row

The other option is to run the count query you have

$check = "SELECT COUNT(*) FROM table WHERE B>0";
$statement_count = $pdo->prepare($check);
$statement_count->execute(); 
$count = $statement_count->fetchColumn();
echo $count;

Upvotes: 1

Abdulhafeth Sartawi
Abdulhafeth Sartawi

Reputation: 1166

You don't need to get the row count, you need to get the result of the query and parse it, then read the value for "count(*)"

Upvotes: 1

Related Questions