How to use "Count se" in PHP

Asked

Viewed 794 times

4

I need to make a count se in the PHP. I have a table with several status, and I want to count only a certain type. And I need to count by PHP. By SQL is unviable.

$data = Connection::Select('SELECT * FROM tabela');

$row = $data->fetchAll();

echo count($row->status === 1);

echo count($row->status === 2);

echo count($row->status === 3);

Has as?

1 answer

12


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.

  • Which is faster? by php’s if or internal if in the database?

  • 2

    @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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.