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.

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

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证