mockingbid
mockingbid

Reputation: 169

Sql query returns only first row

I'm try to display a result of a select query, but i only get duplicate first row not all the rows. here is my code :

$query = "SELECT Email from client";
$result = $db->query($query)->fetch();
foreach($result as $email){
    echo $email["Email"]."\n";
}

Connexion to database works fine.

Upvotes: 1

Views: 1533

Answers (2)

Niki van Stein
Niki van Stein

Reputation: 10724

The fetch() function only fetches one record.

Modify your code like this:

$query = "SELECT Email from client";
$res = $db->query($query);
while($result = $res->fetch()){
    echo $result["Email"]."\n";
}

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34416

You need to use fetchALL() as fetch() only returns one row according to the docs:

Fetches a row from a result set associated with a PDOStatement object.

$query = "SELECT Email from client";
$result = $db->query($query)->fetchALL();
foreach($result as $email){
    echo $email["Email"]."\n";
}

Upvotes: 7

Related Questions