2015-12-02 128 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