Emiel
Emiel

Reputation: 21

php pdo loop through row skips 1st row

I am looping my rows from my database and it works except one thing. it skips the 1st id. it begins from the second record. any idea how to fix this? this is my code:

<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC)
?>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['name'];
$cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>

Upvotes: 1

Views: 870

Answers (4)

Guspan Tanadi
Guspan Tanadi

Reputation: 182

Don't fetch twice for a query.

<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();

foreach ($query as $row) {
$id = $row['id']; $n = $row['name']; $cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>

Upvotes: 0

Girijesh Kumar
Girijesh Kumar

Reputation: 126

Your code should be like this:

<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
?>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['name'];
$cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>

Upvotes: 0

Diego Molina
Diego Molina

Reputation: 333

<?php
 // your first error is here. You are fetching the first row
 $row = $query->fetch(PDO::FETCH_ASSOC)
 // And here you start from the second, since you already did ones above
 while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
  //...rest of oyur code
 }
?>

you have two way to accomplish your task

  <?php
  // Just add the PDO::FETCH_ASSOC constant while you are looping
  while($row = $query->fetch(PDO::FETCH_ASSOC)){
   //...Code here
  }

  // another way is adding the constant before using it 
  $query->setFetchMode(PDO::FETCH_ASSOC);
  while($row = $query->fetch()){
   //...Code here
  }
  ?>

Upvotes: 1

Jay Patel
Jay Patel

Reputation: 408

Remove

$row = $query->fetch(PDO::FETCH_ASSOC) after $query->execute();

just keep the while($row = $query->fetch(PDO::FETCH_ASSOC)) statement.

Upvotes: 0

Related Questions