【问题标题】:fetching article from mysql using slug使用 slug 从 mysql 获取文章
【发布时间】:2011-01-25 22:39:48
【问题描述】:

我正在我的网站上编写自己的新闻文章部分,并将每篇文章存储在 mysql 数据库中。每篇文章都有一个唯一的 id、一个标题、正文,并且感谢 jquery 插件,它是自己的 url-friendly slug。

但是,我不确定在链接到 slug 时我到底是如何获取文章的。

我如何获得:

www.site.com/news/nice-looking-title/

像这样工作:

www.site.com/news/index.php?id=1

这样我就可以使用 SQL 从 MySQL 表中获取记录,例如:

tbl_news:
news_id
news_title
news_slug
news_body
news_date

.htacccess 是否参与其中?

一如既往,我们非常感谢所有帮助! :)

保罗

【问题讨论】:

    标签: php mysql .htaccess url-rewriting


    【解决方案1】:

    您需要将 SQL 查询更改为按 news_slug 而不是 news_id 进行选择。一个简单的应用程序可能如下:

    .htaccess

    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/news #only do this for URLs beginning /news
    RewriteRule (.*) /news/index.php [L] #redirect control to index.php
    

    PHP

    $slug = explode('/', $)SERVER['REQUEST_URI']); // turn the path into an array
    $slug = $slug[2]; // get the 2nd part of the array (nice-looking-title)
    $query = sprintf ("SELECT * FROM tbl_news WHERE news_slug = '%s'", $slug); // new SQL query
    

    注意:这还没有经过测试,所以可能有错误!

    【讨论】:

    • 它几乎可以工作了! :) 使用 thise rewrite 导致无限循环,因此将其更改为: RewriteRule /news/(.*) /news/index.php 实现您建议的 PHP 给我一个 404 错误,但浏览器中的 url 显示为我想要它,所以我比以前更近了几步!
    【解决方案2】:

    好的,这是我必须做的来解决这个问题。有点hacky,但它有效。

    使用 RewriteRule (.*) /news/index.php 会导致网站出现无限循环,就像在 news 目录中拥有 php 页面一样。所以我不得不将链接发送到不同的目录名称,并将它们重写到实际目录。

    .htaccess

    RewriteCond %{REQUEST_URI} /guild-news
    RewriteRule guild-news/(.*)/ news/news-item.php?slug=$1
    RewriteRule guild-news/(.*) news/news-item.php?slug=$1
    

    PHP

    $slug=$_GET['slug'];
    $newsSQL = "SELECT *, DATE_FORMAT(news_date, '%W, %D %M, %Y') news_date_f FROM tbl_news WHERE news_slug = '".$slug."' AND news_visible=1";
    $result = mysql_query($newsSQL, $conn) or die(mysql_error());
    

    所以可能不是有史以来最好的代码,但它确实可以很好地满足我的需求:)

    【讨论】:

      猜你喜欢
      • 2016-03-06
      • 2023-03-09
      • 1970-01-01
      • 2011-10-06
      • 2019-07-10
      • 1970-01-01
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多