How to return all results from the [PDO] database?

Asked

Viewed 920 times

1

I’m doing a function to return all the results of a database. The function in this exact format returns me only one result but putting echo in each statement returns me all the results.

How can I make this code that probably has a logic error return me all the results of the database?

try {

    // PDO em ação!
    $pdo = new PDO ( "mysql:host=localhost;dbname=nomedobanco", "usuariodobanco", "senhadobanco", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "SELECT * FROM wp_posts ORDER BY post_date ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    while ( $linha = $stmt->fetch ( PDO::FETCH_OBJ ) ) {

        $conteudo = $linha->post_title . "<br>" . $linha->post_date . "<br>";
        return $conteudo;

    }

} catch ...

Thus returns all results ....

while ( $linha = $stmt->fetch ( PDO::FETCH_OBJ ) ) {

    echo $linha->post_title . "<br>" . $linha->post_date . "<br>";

}
  • 1

    fetchAll() in place of fetch()

1 answer

1


A very simple way to do this task is by doing the following:

try {
    $pdo = new PDO("mysql: hostname=localhost; dbname=example;", "root", "");   
} catch(PDOException $e){
    return $e->getMessage();    
}

// echo $pdo ? "Sim" : "Nao";

$consulta = $pdo->query("SELECT * FROM jogos");

while($linhas = $consulta->fetch(PDO::FETCH_OBJ)){
    print $linhas->nome . "<br/>";
    // print $linhas->nome . "\t";
}

This includes the output of all values in the looping.

Doing, the way you did above:

while($linhas = $consulta->fetch(PDO::FETCH_OBJ)){
    $row = $linhas->nome . "<br/>"; 
}

The variable $row stores the results in the output order, but only the last value will persist, because it is not a array, and also for not having been instantiated before.

And the possible solutions would be:

first

Declare the variable $row outside the looping, and then go concatenating the results.

$row="";
while($linhas = $consulta->fetch(PDO::FETCH_OBJ)){
    $row .= $linhas->nome . "<br/>";    
}

echo $row;

2nd

Instantiate the variable $row within the looping, only this time, as array, and go filling each position of that array with the respective number of results returned.

while($linhas = $consulta->fetch(PDO::FETCH_OBJ)){
    $row[] = $linhas->nome . "<br/>";   
}

echo $row; // retorna o Notice: Array to string conversion, por se tratar agora de uma array;

foreach($row as $nome){
    echo $nome; 
}

Or so this way, maybe the simplest way up.

while($linhas = $consulta->fetch(PDO::FETCH_OBJ)){
    print $linhas->nome . "<br/>";
    // print $linhas->nome . "\t";
}

There must be a lot of other ways to do that, you just have to look around, or use the one you think is convenient.

PDO::fetch()

Browser other questions tagged

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