php pdo loop through row跳过第1行

时间:2016-07-24 20:02:21

标签: php mysql pdo

我正在从我的数据库中循环我的行,它除了一件事之外还有效。它会跳过第一个ID。 它从第二条记录开始。任何想法如何解决这个问题? 这是我的代码:

<?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>';
}
?>

4 个答案:

答案 0 :(得分:0)

删除

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

之后

$query->execute();

保留while($row = $query->fetch(PDO::FETCH_ASSOC))声明。

答案 1 :(得分:0)

<?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
 }
?>

你有两种方法可以完成你的任务

  <?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
  }
  ?>

答案 2 :(得分:0)

您的代码应该是这样的:

<?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>';
}
?>

答案 3 :(得分:0)

不要为查询提取两次。

<?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>';
}
?>