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.

1

2 Answers 2

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`;
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I tested it. Just cannot get from there to 3/9. I get something like 0101010101
You're probably echoing the object itself, not the results. You need to fetch the results.
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'];

3 Comments

Looks good. How do I execute the result? $result = $pdo->fetchAll(); and then foreach ($result as $row) { echo $row['totalCount'];}?
I tested it, but not getting the result. I must make a mistake somewhere. Let you know if I solved it
@Jarla added an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.