mysql with unique result in PDO

2

I'm trying to create a query as follows:

I have a table in the database with this structure:

  

name | address | status

The status field only has 2 types of values 1 or 0. I want to count all records that have status 0

I made the following query:

select count(*) as total from sv_mensagens where status = 0

In PHP I made the following code using PDO:

$this->pdo = ConnDB::conexao();

$query3 = "select count(*) as total from sv_mensagens where status = 0";
$conta2 = $this->pdo->prepare($query3);
$conta2->execute();

while ($result = $conta2->fetchAll()){
    echo $result['total'];
}

Only error occurs and does not work What I want to bring is the result of counting all the records that have the status at 0.

    
asked by anonymous 06.03.2017 / 20:32

2 answers

1

You are calling the fetchAll function within a loop.

The function fetchAll will return an array with all the results.

In your case, you should be returning the following array:

$resultado = array(
  array(
    'total' => 'Algum Numero'
  )
);

Try using the fetch function. Note that you must also pass the Fetch type you want.

The final code looks like this:

$this->pdo = ConnDB::conexao();

$query3 = "select count(*) as total from sv_mensagens where status = 0";
$conta2 = $this->pdo->prepare($query3);
$conta2->execute();

$result = $conta2->fetchAll(\PDO::FETCH_ASSOC));
echo $result[0]['total'];
    
06.03.2017 / 20:40
0

Try this:

 select count(status) as total from sv_mensagens where status = 0
    
06.03.2017 / 20:41