Display the result of a COUNT in the Database

Asked

Viewed 229 times

1

The PHP code looks like this:

$con = new PDO(SERVIDOR, USUARIO, SENHA);
        $sql = $con->prepare("SELECT COUNT(id) FROM quiz;");
        $sql->execute();
        $n = $sql->fetchObject();

And the HTML code looks like this:

<h1>0<?= print $n->COUNT(id);?></h1>

and the error that appears: Fatal error: Call to Undefined method Pdostatement::COUNT() in ............

someone could show me the error ?

  • pq vc n gives an alias for Count that call print $n->COUNT(id); is no stranger. Calls of total for example ;)

  • But how would be the right way to display the result of COUNT ?

3 answers

0


When trying to read a field like this $n->COUNT(id); php understands that you are calling a method called count() and past the constant id but this method does not exist in an object PDOStatement.

The solution is to give an alias to the field.

Change:

SELECT COUNT(id) FROM quiz

To:

SELECT COUNT(id) as total FROM quiz

In php call the property normally

<h1>0<?= print $n->total;?></h1>
  • Thank you so much I’m learning yet, helped me a lot.

0

Try it that way;

try {         
        $stmt = $con->prepare("SELECT COUNT(id) AS total FROM quiz");
        $stmt->execute(); 

        while ($linha = $stmt->fetch(PDO::FETCH_ASSOC)) {
             echo  "<label>Total:</b> ".$linha['total']."<label>";
           }
        } catch (PDOException $e) { }

0

In your query you have so:

$sql = $con->prepare("SELECT COUNT(id) FROM quiz;");

Try adding the AS id:

$sql = $con->prepare("SELECT COUNT(id) AS id FROM quiz;");

And when to display, simply show as if it were a normal variable of your database.

It will look something like Rafa_developer and the rray wrote.

Browser other questions tagged

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