I’m building a blog and have two tables articles and categories and I’m joining these tables, but what I want to do is display just the categories if I click a categories link. I’m passing the categories_id in the link but I can’t figure out how to display just the categories if the page link is like blog.php?=category_id. I’ll have the categories_id number in the URL I just can’t figure out how to display just that category, I know the SQL statement to just display the categories but what I can’t figure out is how to run that statement if the URL contains the the?=category_id and not run my original SQL statement that was displaying all the articles by date. I tried to do if and else conditions depending on the page name but wasn’t working.
<?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
}
}
?>
Advertisement
Answer
As you’ve been told in the comments, you have to use only parameter, not the whole request.
connect_to_db();
$where = '';
if (isset($_GET['cat_id'])) {
$where = "WHERE category_id = ".intval($_GET['cat_id']);
}
$sql = "SELECT article_id, title, body, date, categories.category, author
FROM articles LEFT JOIN categories
ON articles.category = categories.category_id
$where ORDER BY article_id DESC LIMIT 4";
$result = query($sql);