0

我正在建立一个博客并有两个表格文章和类别,并且我正在加入这些表格,但是如果我单击类别链接,我想要做的是只显示类别。我在链接中传递了 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
    }
}
?>
4

2 回答 2

0

cat_id在查询字符串中使用,例如:

blog.php?cart_id=1

您可以从中提取它$_GET[]$_REQUEST[]

if (isset($_GET['cat_id']))
    $category_id = intval($_GET['cat_id']);
else
    $category_id = 0;

if($category_id > 0) { //Non-Zero +ve value
    $sql = "SELECT article_id, title, body, date, categories.category, author
            FROM articles LEFT JOIN categories ON articles.category = categories.category_id
            WHERE category_id = $category_id";
} else { //Zero
    $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";
}
于 2013-02-10T07:03:12.073 回答
0

正如您在评论中被告知的那样,您必须只使用参数,而不是整个请求。

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);
于 2013-02-10T07:05:50.930 回答