Problem With PDO

Asked

Viewed 120 times

1

My problem is this when I run this code below echo returns me 3 repeated values I could not figure out why you could give me a strength? : D

<?php
    try{

        $sql = $pdo->prepare("select * from produtos");
        $sql->execute();
        $resultado = $sql->fetchObject();

        foreach ($resultado as $key) {
            echo $resultado->nome;
            echo $resultado->quantidade;

        }

        } catch (PDOException $e){
            echo "Erro:\n" . $e->getMessage();  
        }
    ?>

3 answers

1


If you want to return all products from this table, you will need to use the fetchAll instead of fetch or fetchObject as you are using. Whereas the fetchAll returns an array containing all values returned by the query, while methods fetch and fetchObject return only the first set of this query.

Just put this:

$resultado = $sql->fetchAll(PDO::FETCH_OBJ);
foreach ($resultado as $key) {
            echo $key->nome;
            echo $key->quantidade;

        }

Instead:

$resultado = $sql->fetchObject();
foreach ($resultado as $key) {
            echo $resultado->nome;
            echo $resultado->quantidade;

        }

Or if you want to keep your face, put the fetchObject in a loop to return the remaining values.

while($retorno = $sql->fetchObject()){
$resultado[] = $retorno;
}
foreach ($resultado as $key) {
        echo $key->nome;
        echo $key->quantidade;
    }

Another thing is that you can, run this query using only the function query and it does not receive any external parameter has no reason to parameterize the query.

  • Thanks well didactic congratulations :D

  • 1

    You’re welcome.

0

Your code is confused, you’re calling the key value, for it to be key, it would have to be $resultado as $key => $value, and yet, the fetchObject(), gets the next record and returns as an object, in this case you have to use while:

<?php
    try {
        $sql = $pdo->prepare("select * from produtos");
        $sql->execute();

        while ($resultado = $sql->fetchObject()) {
            echo $resultado->nome;
            echo $resultado->quantidade;
        }

    } catch (PDOException $e) {
        echo "Erro:\n" . $e->getMessage();  
    }
?> 

-1

You can use while in that case

while($resultado = $sql->fetchObject()) {
   echo $resultado->nome;
   echo $resultado->quantidade;
}

Browser other questions tagged

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