Reputation: 21
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
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
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
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
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