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

1

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

How can I make this code that probably has a logic error return all results from 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 ...
  

This returns all the results ....

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

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

}
    
asked by anonymous 24.09.2015 / 01:39

1 answer

1

A very simple way to do this 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 looping .

Doing, as 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 has not been instantiated before.

Given that the possible solutions would be:

1st

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

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

echo $row;

2

Instantiate the variable $row within the looping , only this time, as an array, and fill 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; 
}

3rd

Or this way, maybe the simplest one up.

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

There must be several other ways to do this, you just have to look for it, or use whatever you think is convenient.

PDO :: fetch ()

    
24.09.2015 / 02:29