1

I want to fetch all the rows of a table but it only echos 1 row. (The latest) Tried much but nothing worked for me. Tried answers on stackoverflow but it is not working.

Here is the code that i use to fetch the rows:

$stmt = $pdo->prepare("SELECT * FROM admin");
$stmt->execute();
$result = $stmt->fetchAll();

foreach ($result as $row) {
    $gebruikersnaam = $row['gebruikersnaam'];
    $wachtwoord = $row['wachtwoord'];
}

Hope that anyone can help me with this.

1
  • every iteration, it gets overwritten, at the end, your left with the last result row Commented Apr 2, 2015 at 14:39

2 Answers 2

1

I want to fetch all the rows of a table but it only echos 1 row. (The latest)

foreach ($result as $row) {
    $gebruikersnaam = $row['gebruikersnaam'];
    $wachtwoord = $row['wachtwoord'];
}

I can bet 5 dollars on the assumption that you are using those variables outside the loop :) That's why you only see the last row's data. Either remove fetchAll() and fetch() them one by one or manipulate your variables within the loop so you get new values for every row.

Try this and you will know what i mean

foreach ($result as $row) {
   print_r($row);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Betting closed guys haha!, Yes i use it outside the loop. it fetches everything but.. in an if-statement i want to check if the value is equal to the value in the database. When i try that, i can only see that the last inserted value is equal.
How about you pass the value to the database (the one you want to check) and then you don't have perform comparison in PHP, you just ask your database whether something exists or not?
Why not check the value inside the loop? Even better why not act on N.B's advise?
0
$stmt = $pdo->prepare("SELECT * FROM admin");
$stmt->execute();
$result = $stmt->fetchAll();
$count = $stmt->rowCount();

for ($i=0; $i < $count; $i++) {
$gebruikersnaam = $result[$i]['gebruikersnaam'];
$wachtwoord = $result[$i]['wachtwoord'];

echo 'Gebruikersnaam is : '.$gebruikersnaam.'<br/>';
echo 'Wachtwoord is : '.$wachtwoord.'<br/>';
}

Or if you want to use foreach:

$stmt = $pdo->prepare("SELECT * FROM admin");
$stmt->execute();
$result = $stmt->fetchAll();

foreach ($result as $row) {
$gebruikersnaam .= $row['gebruikersnaam'];
$wachtwoord .= $row['wachtwoord'];
}

echo 'Gebruikersnamen zijn : '.$gebruikersnaam.'<br/>';
echo 'Wachtwoorden zijn : '.$wachtwoord.'<br/>';

you have to style it al little bit because it'll stick them all together.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.