If you REALLY want to count in PHP you will need something like this:
$row = $data->fetchAll();
$i = 0;
foreach($row as $item) {
if( $item['status'] === 1 ) ++$i;
// ^^^^^^^^^^^^^^^^^^^^^ aqui vai a condição desejada
}
echo $i; // $i tem o resultado total da contagem
In SQL you can do this if you want to return everything but count a special condition:
SELECT *, SUM( IF( campo atende condicao ), 1, 0 ) AS contados FROM tabela
In this way, everything is returned, but the SUM will add up to 1 for those who answer, 0 for those who do not answer, playing the role of a COUNT
conditional.
Note that by data volume, it may not compensate to do the count
return the sum on all lines, you need to choose the best solution as the case.
If you want the count separately, that’s it:
SELECT COUNT(*) AS contados FROM tabela WHERE status = condicao desejada
Exactly that @Bacco. Thank you.
– Eduardo Santos
Which is faster? by php’s if or internal if in the database?
– Rúbio Falcão
@Rúbiofalcão The speed is negligible, the most important is the context. If you’re going to iterate on all the items on the screen in PHP, adding in PHP doesn’t cost anything. If you take only the total, then it’s silly to transmit all the data from DB pro PHP, better do in SQL even, pq ai only comes the result. The important thing is to understand what is involved in each path.
– Bacco