MySQL如果页面名称然后运行语句

时间:2013-02-10 01:22:33

标签: mysql sql if-statement mysqli

嗨,我只是想知道是否有人可以帮我解决MySQL问题。我正在建立一个博客,并有两个表格文章和类别,我正在加入这些表格,但我想要做的是只显示类别,如果我点击类别链接。我在链接中传递categories_id,但如果页面链接类似于blog.php?= category_id,我无法弄清楚如何仅显示类别。我将在url中有categories_id数字我只是想知道如何只显示该类别,我知道只显示类别的SQL语句但我不知道如果url包含如何运行该语句?= category_id并且不运行我按日期显示所有文章的原始SQL语句。我试图做if if else条件取决于页面名称但不起作用。我希望有意义和帮助将非常感谢,提前感谢,

Mitchell Layzell

继承我的代码 code

        $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
        }
    }
    ?>

code

2 个答案:

答案 0 :(得分: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";
}

答案 1 :(得分: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);