Display the result of a COUNT in the Database

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

Could someone show me the error?

    
asked by anonymous 28.05.2018 / 23:34

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 passed the id constant to it but this method does not exist on a PDOStatement object. >

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 property normally

<h1>0<?= print $n->total;?></h1>
    
29.05.2018 / 00:39
0

Try this 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) { }
    
29.05.2018 / 05:27
0

Your query looks like this:

  

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

Try adding AS id :

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

And when it is to display, simply show it as a normal database variable.

It will look something like Rafa_Developer and the rray wrote.

    
29.05.2018 / 10:19