Heriberto Juarez
Heriberto Juarez

Reputation: 271

PDO foreach echoing the same value

Hi I'm using PDO to connect to a database and I have a class which has a function to see the results of a query, in a table I have the same names Juan and Pedro but when i print them using the foreach loop I get Juan printed 7 times

class Posts extends Connection{
    public function __construct(){
        parent::__construct();
    }
    public function get_result(){
        $res=self::$conn->prepare("SELECT * FROM POSTS");
        $res->execute();
        $array=$res->fetch(PDO::FETCH_ASSOC);
        foreach($array as $value){
            echo $array['AUTHOR'] . "<br>";
        }
    }
}

Upvotes: 0

Views: 165

Answers (2)

Jeff
Jeff

Reputation: 6953

You use PDOStatement::fetch(), which will only get one (the first, next) row. So you iterated over one row, which gave you 7 turnes (because you obviously have 7 columns) the same result for $array['AUTHOR'].

As you want the whole result set you need to use fetchAll().
This will return an array of all rows, that you then can iterate over.

public function get_result(){
    $res=self::$conn->prepare("SELECT * FROM POSTS");
    $res->execute();
    $array=$res->fetchAll(PDO::FETCH_ASSOC);
    foreach($array as $row){
        echo $row['AUTHOR'] . "<br>";
    }
}

Upvotes: 1

u_mulder
u_mulder

Reputation: 54796

Here's the problem

public function get_result(){
    $res=self::$conn->prepare("SELECT * FROM POSTS");
    $res->execute();
    $array = $res->fetch(PDO::FETCH_ASSOC);
    // $array has fields for ONE fetched row.

    // here you iterate over fields of ONE fetched row
    // and echo one field `AUTHOR`
    foreach ($array as $value) {
        echo $array['AUTHOR'] . "<br>";
    }
}

Solution - rows must be fetched in a loop, usually it's a while loop:

public function get_result(){
    $res=self::$conn->prepare("SELECT * FROM POSTS");
    $res->execute();

    // here your fetch every row of a result set
    while ($array = $res->fetch(PDO::FETCH_ASSOC)) {
        echo $array['AUTHOR'] . "<br>";
    }
}

Upvotes: 3

Related Questions