2016-07-24 58 views
0

我从我的数据库循环我的行,它的工作原理除了一件事。它跳过第一个ID。 它从第二条记录开始。任何想法如何解决这个问题? 这是我的代码:php pdo循环通过行跳过第1行

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

您提前调用'fetch'将这些数据放在地上吗? PHP在做这正是你要求在这里。 – tadman

+0

但我如何让它从第一条记录算起呢? – Emiel

+1

逐行浏览代码并思考PHP在这里做了什么,问题会变得很明显。提示:'while'立即执行该语句,并且当且仅当该值在逻辑上为false时才会跳到块的结尾。 – tadman

回答

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

$query->execute();

删除

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

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