0
$pdo = $db->query('SELECT * FROM data ;');
$total = $pdo->rowCount();  
echo $total;

The result is for example 3.

But I have a column named "done" in mySQL database where the possible value is 1 or 0.

I want now to count all rows with the value 1. So if there are for example in total 9 elements in the database and from them three items with the value 1 then the result should be:

3/9

I know only know how to do this with a second database request

 $pdo = $db->query('SELECT * FROM data WHERE done = "1"  ;');
 $done = $pdo->rowCount();  

 echo $done."/".$total;

But I was wondering if this is possible in just one database request.

peace_love
  • 6,229
  • 11
  • 69
  • 157
  • 1
    Careful , `rowcount()` is not consistent across all databases for SELECT statements - http://php.net/manual/en/pdostatement.rowcount.php – WillardSolutions Apr 19 '17 at 16:03

2 Answers2

4

Try this for the query, and get the info from the results (not row count)

SELECT `done`, count(*) as `numrows` FROM `data` GROUP BY `done`;
Sloan Thrasher
  • 4,953
  • 3
  • 22
  • 40
1

MySQL supports expressions in SUM, so if your looking to get a total count and a filtered count at the same time you can do this:

SELECT COUNT(*) as totalCount, SUM(`done`=1) as completeCount FROM `data`

You can also add in the "not done" count if needed:

SELECT COUNT(*) as totalCount, SUM(`done`=1) as completeCount, SUM(`done`=0) as incompleteCount FROM `data`

With your code:

$query = 'SELECT COUNT(*) as total, SUM(`done`=1) as complete FROM `data`';
$pdo = $db->query($query);
$data = $pdo->fetch(); // Uses PDO::FETCH_BOTH by default  
echo $data['complete']."/".$data['total'];
Lee
  • 10,496
  • 4
  • 37
  • 45