【问题标题】:fetching article from mysql db with slug url使用 slug url 从 mysql db 获取文章
【发布时间】:2016-03-06 10:45:15
【问题描述】:

我正在开发自己的 PHP Mysql 站点。

我曾经像这样通过 id 获取数据:mysite.com/articles.php?id=12

现在我想用 slug 更改网址:

mysite.com/articles/google-search

mysite.com/articles.php?article=google-search

我不想使用 id 和数字。

我的桌子:

+----+---------------+---------+------------------------------------+
| id | title         | article |   urlslug                          |
+----+---------------+---------+------------------------------------+
| 12 | google search | xxxxxxx |   google-search                    |
| 13 | bing yahoo    | xxxxxxx |   bing-yahoo                       |
| 14 | friendly seo  | xxxxxxx |   friendly-seo                     |
+-------------------------------------------------------------------+

我使用下面的代码通过 id 获取数据:

$id = $_GET['id'];
$id = mysqli_real_escape_string($conn,$id);
$query = "SELECT * FROM `table` WHERE `id`='" . $id . "'";
$result = mysqli_query($conn,$query);

while($row = mysqli_fetch_array($result)) {
echo ($row['title']);
echo ($row['article']);    }

我通过替换 urlslug 尝试了上面的代码,上面写着Invalid ID specified. 我用谷歌搜索,甚至搜索堆栈问题,但没有得到任何帮助。请帮助我。提前致谢。

【问题讨论】:

  • 你能回显echo $_GET['id'];

标签: php mysql .htaccess slug


【解决方案1】:

如果网址是这样的mysite.com/articles.php?article=google-search 然后从 url 获取 article 而不是 id 并将条件更改为 urlslug 而不是 id。

$slug = $_GET['article'];
$slug = mysqli_real_escape_string($conn,$slug);
$query = "SELECT * FROM `table` WHERE `urlslug`='" . $slug. "'";
$result = mysqli_query($conn,$query);

 //Since  slug is unique you will get only 1 result so no need to loop

 $row = mysqli_fetch_array($result);
 echo $row['title'];
 echo $row['article'];    

【讨论】:

  • slug 必须是唯一的。所以你不需要担心文章的数量。
  • 天哪,我对此完全陌生。我按照你建议的方式尝试了,但它说指定的 id 无效
  • @dan 这意味着您在应用程序的某个位置检查了id。 php 没有提供这样的消息invalid id specified 所以在你的代码中找到它.. 你的问题中没有提到。我认为这是一个非常小的问题。
  • invalid id specified你有没有在你的代码的任何部分给出这样的信息......???请检查。
【解决方案2】:

您可以在 Root/.htaccess 中使用以下规则

RewriteEngine On


RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^articles/([^/]+)/?$ /articles.php?id=$1 [NC,L] 

这将重写

example.com/articles/123

example.com/articles.php?id=123

【讨论】:

    猜你喜欢
    • 2011-01-25
    • 2016-02-29
    • 2023-03-09
    • 2015-04-04
    • 2021-10-08
    • 2017-05-30
    • 2014-08-16
    • 1970-01-01
    • 2011-10-06
    相关资源
    最近更新 更多