doumo0206 2014-06-27 12:16
浏览 204
已采纳

尝试使用while循环获取所有数据但第一个数据已被提取,不知道如何更改我的代码。 (PHP)

So here's an example code I use to show all the categories that are linked to a certain postID. For example post 1 has the categories: Apple, Green and Yellow linked to it.

But I can't seem to fetch the data correctly since it has already been fetched once at the top i can't do a proper while loop at the Categories: part of my code where I try to do a while loop. The while loop works and fetches all the categories except the First one and also when I place the while loop the

$row['postTitle']

and

$row['postCont']

won't appear anymore because it's being skipped. How would I fix something like this? Thanks.


<?php require('includes/config.php'); 

$stmt = $db->prepare("  SELECT * 
                        FROM blog_posts 
                        LEFT JOIN  blog_posts_categories ON blog_posts.postID=blog_posts_categories.postID 
                        INNER JOIN blog_categories ON blog_posts_categories.catID=blog_categories.catID 
                        WHERE blog_posts.postID = :postID");

$stmt->execute(array(':postID' => $_GET['id']));
$row = $stmt->fetch();

//if post does not exists redirect user to homepage.
if($row['postID'] == ''){
    header('Location: ./');
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?php echo $row['postTitle'];?> | Website</title>
    <link rel="stylesheet" href="style/normalize.css">
    <link rel="stylesheet" href="style/main.css">
</head>
<body>

    <div id="wrapper">

        <h1>Single Post Page</h1>
        <hr />
        <p><a href="./">Home</a> | 

            Categories: 

            <?php while($row = $stmt->fetch())
            {
                //the first category is being skipped? How to fix?
                echo $row['catName'];
            } ?>

        </p>
        <div>
            <?php 
                //these won't appear because of the while loop. It's being skipped.
                echo '<h1>'.$row['postTitle'].'</h1>';
                echo '<p>'.$row['postCont'].'</p>'; 
            ?>
        </div>

    </div>

</body>
</html>
  • 写回答

1条回答 默认 最新

  • dousi7579 2014-06-27 12:18
    关注

    Replace:

            while($row = $stmt->fetch())
            {
                echo $row['catName'];
            }
    

    With:

            do {
                echo $row['catName'];
            } while($row = $stmt->fetch());
    

    As for the other items - put them inside the loop obviously instead of afterwards.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记