如何使用不同的文章管理网站的URL?

时间:2017-06-09 03:47:30

标签: php database match blogs

我已经制作了一些包含一些文章的示例网站。我希望URL的方式如下:

  

www.example.com/news/first-article

但是,就目前而言,我刚刚首先创建目录:home/news/,将所需的 first-article.html 文件放在目录中。

需要注意的是,我确实拥有保存在数据库中的文章的所有内容(如标题,正文,日期等),所以我觉得可能有更好的方法,比如 URI匹配器存在于Android中,而不是仅在每个目录中创建文件。

这里的动机是识别文章的类别(这里是'新闻')和文章的名称(这里是'第一篇')然后从数据库中检索详细信息并动态生成所需的页面。这可能在PHP吗?

[示例代码段可以提供帮助]

1 个答案:

答案 0 :(得分:1)

我建议使用单个PHP页面从数据库中读取数据,并根据$_GET参数显示内容:

include('database_connection.php'); // Saved as $mysqli

if (isset($_GET['id'])) {
    $news_id = $_GET['id'];

    // Grab the news information given the ID (in MySQLi)
    $stmt = $mysqli->prepare("SELECT id, news, date FROM news WHERE id = ?");
    $stmt->bind_param('i', $news_id);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id, $news, $date);
    $stmt->fetch();

    // Output results
    echo "<h1>" . $date . "</h1>";
    echo "<p"> . $news . "</p>";

    $stmt->close();
}

这只需要一个PHP页面(news.php),它会加载包含news.php?id=1news.php?id=2等各种文章。

然后你可以使用.htaccess来变形&#39;新闻页面进入“漂亮”的网页具有以下内容的页面:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) news.php?id=$1&$2

使用以下内容进行链接时

$article_title = 'First Article';
echo '<a href="' . str_replace(" ", "-", $article_title).'">Read More</a>';

哪个会“美化”。您的页面网址,基于脚本文件名。

希望这有帮助! :)

相关问题