[英]Multiple Categories for a single Article (PHP MYSQL)
需要幫助顯示單個文章的所有類別。
這是我的數據庫結構:
blog_posts 表
postID int,主要,自動遞增。
postTitle varchar
postCont 文字
blog_categories 表
catID int,主要,自動遞增。
catName varchar
blog_posts_categories 表
postID int
catID int
數據庫內容:
blog_posts
postID | postTitle | postCont
1 Post1 Cont1
2 Post2 Cont2
3 Post3 Cont3
4 Post4 Cont4
5 Post5 Cont5
blog_categories
catID | catName
1 Music
2 Games
3 Technology
blog_posts_categories
postID | catID
1 1
1 2
1 3
2 2
3 3
4 1
4 2
5 2
5 3
這是我用來將數據獲取到單個帖子的代碼。 帖子頁面URL的示例如下所示: http : //domain.com/viewpost.php?postID=1
<?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 echo ''.$row['catName'].''; ?></p>
<div>
<?php
echo '<h1>'.$row['postTitle'].'</h1>';
echo '<p>'.$row['postCont'].'</p>';
?>
</div>
</div>
</body>
</html>
現在,此代碼僅回顯1的單個Category名稱,但我非常希望它能順序顯示鏈接到該帖子的所有類別。 我只是無法解決這個問題,也不知道該打什么,我還是一個初學者。 無論如何,謝謝您的時間!
如果查詢返回多行,則必須循環查詢結果以實現所需的結果。
一個例子可以是:
while($row = $stmt->fetch()) { // Your stuff here }
如果使用PDO,則可以使用fetchAll
而不是fetch
,並且將獲得數組而不是單行(但始終需要循環)。
那已經在多行中為您帶來期望的結果。 您只在獲取第一個。 因此,結果中只有一個類別。
一種執行所需操作的方法是:
SELECT *, GROUP_CONCAT(catName) AS allCategories FROM ...
這樣一來,您只會得到一條結果行。 用$row['allCategories']
代替$row['catName']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.