簡體   English   中英

嘗試使用while循環獲取所有數據,但是已經獲取了第一個數據,不知道如何更改我的代碼。 (PHP)

[英]Trying to fetch all data with a while loop but the first data is already fetched, don't know how to change my code. (Php)

因此,這是一個示例代碼,用於顯示鏈接到某個postID的所有類別。 例如,帖子1的類別與之鏈接:蘋果,綠色和黃色。

但是我似乎無法正確地獲取數據,因為它已經在頂部被獲取了一次,因此我無法在Categories:的代碼中進行適當的while循環Categories:我嘗試在其中進行while循環的一部分。 while循環工作並獲取除第一個循環以外的所有類別,當我放置while循環時,

$行[ 'postTitle']

$行[ 'postCont']

不會再出現,因為它已被跳過。 我該如何解決這樣的問題? 謝謝。


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

更換:

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

附:

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

至於其他項目-顯然將它們放入循環而不是之后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM