php – while($stmt-> fetch())没有获取所有行

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – while($stmt-> fetch())没有获取所有行脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用while循环显示属于登录用户的所有食谱.我注意到,让我们说,用户有4个食谱,第一个不会显示,导致表中只出现3个食谱.如果用户有3个食谱,则不会显示一个食谱,导致仅显示2个食谱,依此类推.

我做了我的研究,发现这是因为第一行将被忽略,因此不会显示.

是否有人可以建议我应该对循环进行哪种修正以解决这个问题?我的代码涉及显示在表中,这就是为什么我仍然无法弄清楚应该做什么尽管已经查看了其他问题已经发布并回答了.

非常感谢!

<?PHP

// 0: Instead of hard coding I shall declare the value First

$userid = $_SESSION['userid'];

// 1: Connect to forumdb database

$MysqLi = new MysqLi("localhost","root",null,"reciPEdb") or exIT("Error connecting to database");

// 2: PRepare the statement to select recipename,recipeid,imagefile belonging to the $userid From recipe table

$stmt = $MysqLi->prepare("Select recipename,imagefile from recipe where userid=?");

// 3: Bind the values

$stmt->bind_param("s",$userid);

// 4: Execute the statement

$stmt->execute();

// TODO 5: bind results into $recipename,$recipeid and $imagefile

$stmt->bind_result($recipename,$recipeid,$imagefile);

if ($stmt->fetch() == null) {
    echo "You did not have any recipes yet.<br />";
}
else {
    echo "<table style=width:100% >";
    echo "<tr><td><b>Recipe</b></td><td><b>Actions</b></td></tr>";

    // Use while loop to fetch messages and put in a <table>
    // if

    while ($stmt->fetch()) {
        echo "<tr>";

        // 6: In 1st <td>,display recipename,imagefile

        echo "<td><b>$recipename</b><br /><b>Recipe ID:</b>$recipeid<br /> <img src='images/$imagefile'    height='125' width='125'              >   </td>";

        // 7: In 2nd <td>,display View hyperlink
        // The View hyperlink links to recipedetails.PHP
        // The delete hyperlink links to deleterecipes.PHP

        echo "<td> <a href='recipedetails.PHP?recipeid=$recipeid'>View</a>&amp;nbsp";
        echo "<a href='deleteconfirmation.PHP?recipeid=$recipeid'>Delete</a>&nbsp";
        echo "</tr>";
    }

    echo "</table>";
}

// 8: close the statement

$stmt->close();

// 9: close $MysqLi

$MysqLi->close();
?>

解决方法

如你所说,当你这样做:

if($stmt->fetch()==null)

代码获取第一行.如果它不存在,则触发条件.否则,它继续,当你开始“真实地”获取行时,第一个已被提取.

你可以做的是检查返回的行数:

$stmt->Store_result();
if ($stmt->num_rows == 0) {
    echo "You did not have any recipes yet.<br>";
}

脚本宝典总结

以上是脚本宝典为你收集整理的php – while($stmt-> fetch())没有获取所有行全部内容,希望文章能够帮你解决php – while($stmt-> fetch())没有获取所有行所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。