Luke Luke - 3 months ago 9
SQL Question

PHP while loop loops everything except first query result

I am struggling to understand why while loop not looping through the first query result.

$pdo = new PDO('connection');
$stmt2 = $pdo->prepare("SELECT user FROM records
ORDER BY date DESC");

$stmt2->execute();
$r2 = $stmt2->fetch(PDO::FETCH_ASSOC);

while ($r2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}


I've read this thread but it is OOP. Any suggestions?

Answer

That's because you're fetching it twice. Remove the fetch just before while loop.

To something like this,

$pdo = new PDO('connection');
$stmt2 = $pdo->prepare("SELECT user FROM records
ORDER BY date DESC");

$stmt2->execute();
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
  echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
Comments