Problem With PDO

1

My problem is the following when I execute this code below echo returns me 3 values Repeated I could not find out why you could give me a force? : 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();  
        }
    ?>
    
asked by anonymous 04.12.2015 / 10:47

3 answers

1

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

Simply put this:

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

        }

Instead of this:

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

        }

Or if you want to keep your expression, put 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 execute this query using only the query function, since it does not receive any external parameters, you do not have to parameterize the query.

    
04.12.2015 / 12:06
0

Your code is confusing, you are calling the value of key, so it is key, it would have to be $resultado as $key => $value , and even then, fetchObject() , gets the next record and returns it 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();  
    }
?> 
    
04.12.2015 / 12:36
-1

You can use while in this case

while($resultado = $sql->fetchObject()) {
   echo $resultado->nome;
   echo $resultado->quantidade;
}
    
04.12.2015 / 11:15