我正在建立一个博客并有两个表格文章和类别,并且我正在加入这些表格,但是如果我单击类别链接,我想要做的是只显示类别。我在链接中传递了 category_id,但如果页面链接类似于 blog.php?=category_id,我不知道如何只显示类别。我将在 URL 中有 category_id 编号我只是不知道如何仅显示该类别,我知道 SQL 语句仅显示类别但我不知道如何运行该语句,如果URL 包含 the?=category_id 并且不运行按日期显示所有文章的原始 SQL 语句。我尝试根据页面名称执行 if 和 else 条件,但没有工作。
<?php
connect_to_db();
$url = $_SERVER['SCRIPT_NAME'];
$pos = strrpos($url,"/");
$pagename = substr($url,$pos+1);
if($pagename == ("blog.php")) {
$sql = "SELECT article_id, title, body, date, categories.category, author FROM articles
LEFT JOIN categories ON articles.category = categories.category_id ORDER BY article_id DESC LIMIT 4";
}
elseif($pagename == ("blog.php?=1")) {
$sql = "SELECT article_id, title, body, date, categories.category, author FROM articles
LEFT JOIN categories ON articles.category = categories.category_id WHERE category_id = 1";
}
$result = query($sql);
if($result===false) {
echo "query failed";
}
else {
while( $data = mysqli_fetch_array($result))
{
?>
<article>
<h3 class="title-medium"><?php echo $data['title']; ?></h3>
<p class="caption-medium"><?php echo $data['author']; ?> <?php echo $data['date']; ?> <?php echo $data['category']; ?></p>
<img src="img/blog-post-1.jpg" alt="">
<p><?php echo substr($data['body'],0,450)." ..." ?></p>
<a href="blog-post.php?id=<?php echo $data['article_id']; ?>"><p class="caption-medium highlight">Read More</p></a>
<hr>
</article>
<?php
}
}
?>