1

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.

4
  • You only get one row because you only call fetch() once. Commented Apr 8, 2016 at 14:50
  • "Connexion to database works fine." - Which is what, MySQLi_ or PDO? Both have fetch(). php.net/manual/en/mysqli-stmt.fetch.php and php.net/manual/en/pdostatement.fetch.php Commented Apr 8, 2016 at 14:56
  • PDO but it was fetchALL that i needed to use. Thank you. Commented Apr 8, 2016 at 15:18
  • @magentonewbie Ok. I had to be sure as it could have swung either way. Commented Apr 8, 2016 at 15:21

2 Answers 2

7

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";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.