mysqli ignoring the first row in a table

◇◆丶佛笑我妖孽 提交于 2020-12-26 19:56:10

问题


Here is the code I'm using to pull the data from the table:

require_once 'connect.php';
$sql = "SELECT * FROM `db-news`";
$result = $mysqli->query($sql);
$row = mysqli_fetch_assoc($result);
while ($row = $result->fetch_assoc()) {
    printf ($row['pagename'].' - To edit this page <a href="editnews.php?id='.$row['id'].'">click here</a><br>');
}

Always the first row is ignored. I'm not calling mysqli_fetch_assoc twice as with some other examples on SO. I've tried changing echo to printf in the while loop and still the first row is ignored in the DB.

I'm at a loss as to what I should try next?


回答1:


mysqli not ignoring it but actually you are fetching first row before while loop

// $row = mysqli_fetch_assoc($result); //remove this line
 while ($row = $result->fetch_assoc()) {
   ....
 }



回答2:


The problem is the first row of the following excerpt:

$row = mysqli_fetch_assoc($result);
while ($row = $result->fetch_assoc()) {

The mysqli_fetch_assoc already gets the first row (and thus in the while loop you are already 1 step further). You should either put that line instead of the $reslut->fetch_assoc part into the while statement or delete it. That should solve the problem.




回答3:


mysqli_fetch_assoc() is the same as $result->fetch_assoc() and whenever you call this function it will advance an internal pointer to the next row. You are calling this function once just before the loop which means that you are reading the first row and ignoring the result. Remove that line.

If you need to fetch the first line and then still loop through the whole result use foreach instead of while. For example:

require_once 'connect.php';
$sql = "SELECT * FROM `db-news`";
$result = $mysqli->query($sql);
foreach($result as $row) {
    printf($row['pagename'].' - To edit this page <a href="editnews.php?id='.$row['id'].'">click here</a><br>');
}



回答4:


Use do while instead of while as it will not skip the first step.



来源:https://stackoverflow.com/questions/13358552/mysqli-ignoring-the-first-row-in-a-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!