2015-12-02 131 views
0

我开发自己的PHP Mysql站点。从嗅嗅网址获取文章从MySQL数据库

我使用的ID这样来获取数据:mysite.com/articles.php?id=12

现在我想用塞更改URL:

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. 我一派,甚至搜查在堆栈问题我没有得到任何帮助。请帮助我。提前致谢。

+0

你可以重复'回声$ _GET [ 'id'];' – uno

回答

1

如果URL是这样mysite.com/articles.php?article=google-search 然后代替id得到的URL article和更改条件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'];  
+0

我有500篇文章如何能ic那样的话。 – dan

+0

slu must必须是唯一的。所以你不需要打扰文章的数量。 –

+0

在基督兄弟,即时通讯全新的这一点。我尝试了你的建议,但它说无效的ID指定 – dan

0

您可以使用以下规则根/的.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