mysql with single PDO result

Asked

Viewed 572 times

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 are 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 that error occurs and does not work what I want to bring is the result of counting all records that are status in 0.

  • Which error is it? could post message?

  • I tried to improve the question, to be easier to understand, in case you think it better to go back to the old one, just click here and click on reverter

  • To query when executed in Mysql works normally?

  • thanks bonifazio get the will thank you even :D

2 answers

1

You are calling the function fetchAll within a loop.

The function fetchAll will return an array with all results.

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

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

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

The final code would look 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'];
  • 3

    @Bonifazio this was done to avoid namespaces, if you are inside a namespace and do not use can give problem. Related: http://answall.com/q/78007/3635

  • 1

    Guy thanks even gave right what I wanted so thank you for the great help thank you even though God bless you.

  • mine is namespace and working well

  • 2

    @mfurlan, enjoy that you are new and from a stride on tour

  • didn’t quite understand your question. Do you want to take the result in php and make more conditions? If that’s it, just assign to a variable to use: $meuValor = $result[0]['total'];

0

Try this:

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

Browser other questions tagged

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