我有个博客。我希望当用户点击“所有的帖子”时,它应该显示来自博客的所有帖子。当有人点击一个类别,如“饮食”,它应该显示来自“饮食”类别的帖子。
以下是我迄今为止所做的
<div class="blog-nav">
<ul class="nav">
<li><a>All Posts</a></li>
<?php
$SelectBlogcats = mysqli_query($con, "SELECT * FROM blog GROUP BY cat_blog");
while($row = mysqli_fetch_assoc($SelectBlogcats)){
$Cat_query = mysqli_query($con,"SELECT * FROM cat_blog WHERE
id=".$row['cat_blog']);
$main_cat = mysqli_fetch_assoc($Cat_query);
?>
<li><a><?php echo $main_cat['bcat_name'];?></a></li>
<?php } ?>
</ul>
</div>发布于 2022-01-15 20:35:58
测试和工作答案
<?php
$cat_id=0;
$condition="";
if(isset($_GET['cat'])){
$cat_id=$_GET['cat'];
$condition="where cat_blog=$cat_id";
}
$SelectBlogcats = mysqli_query($con, "SELECT * FROM blog GROUP BY cat_blog");
while($row = mysqli_fetch_assoc($SelectBlogcats)){
$Cat_query = mysqli_query($con,"SELECT * FROM cat_blog WHERE
id=".$row['cat_blog']);
$main_cat = mysqli_fetch_assoc($Cat_query);
?>
<li>
<h2><a href="blog.php?cat=<?php echo $main_cat['id']; ?>"><?php echo $main_cat['bcat_name'];?></a></h2>
</li>
<?php } ?>发布于 2022-01-02 09:58:08
一些半伪代码,可能会帮助你完成你的目标-不过,完全未经测试。
您所拥有的嵌套sql查询效率不高,而且很可能表之间的简单join正是您真正需要的。
用于选择要显示的新的/不同的category的每个超链接都需要设置(在本例中)一个querystring参数,该参数可用于筛选整个记录集的记录。
<?php
/*
Hopefully a single query should suffice
joining the two tables rather than querying
separately.
Store the result of the query and use that to build
the nav menu and also display the content late
*/
$cat=!empty( $_GET['category'] ) ? $_GET['category'] : 'all';
# without seeing the schema this is a guess!
$sql='SELECT * FROM `blog` b
JOIN `cat_blog` cb on cb.`id`=b.`cat_blog`
GROUP BY b.`cat_blog`';
$res=$con->query( $sql );
$rs=$res->fetch_all( MYSQLI_ASSOC );
?>使用存储在关联数组中的数据,您可以继续生成超链接菜单,其中每个链接都有一个querystring变量集;即:?category=X。
<div class="blog-nav">
<ul class="nav">
<li><a href='?category=all'>All Posts</a></li>
<?php
foreach( $rs as $row ){
$active = $cat==$row['bcat_name'] ? ' class="active"' : '';
printf( '
<li%2$s>
<a href="?category=%1$s">%1$s</a>
</li>
',
$row['bcat_name'],
$active
);
}
?>
</ul>
</div>然后,可以再次处理记录集,以输出实际的博客内容,注意变量$cat,以规定要显示哪些记录。
<!-- blog display - ALL records or the filtered subset -->
<div class="blog-content">
<?php
if( !empty( $rs )){
foreach( $rs as $row ){
// display only the filtered category or ALL records
if( $cat==$row['cat_name'] or $cat=='all' ){
/* output your blog content ..... */
}
}
}else{
echo 'There was an error fetching database records.';
}
$res->close();
?>
</div>https://stackoverflow.com/questions/70552628
复制相似问题