我无法找到这个问题的正确定义,所以我也无法正确地在上搜索
让我们以博客为例。到目前为止,我已经从数据库中按id(自动递增)选择了博客文章。www.example.com/posts/1或/posts/22等
假设帖子的名字是"我最喜欢的花"。我想将链接显示为www.example.com/posts/my-formate-flowers,而不是/posts/56。如果我没有错的话,搜索也更友好。
如果有人能提供一些材料或解释如何做到这一点,我将不胜感激。我不是在问代码,只是引导我走上正轨。
假设URL如下:
www.example.com/posts/my-flowers
或
www.example.com/posts/22
在posts控制器中,只需使用php的is_numeric()函数,并在uri段上使用它来执行以下操作:
function index(){
$query_var = $this->uri->segment(2);
if(is_numeric($query_var)){
$this->your_model->get_post_by_id($query_var);
}
else
{
$this->your_model->get_post_by_link_name($query_var);
}
...whatever the rest of your code is.
}
尝试这个
数据库
CREATE TABLE blog
(
id INT PRIMARY KEY AUTO_INCREMENT,
title TEXT UNIQUE,
body TEXT,
url TEXT UNIQUE,
);
Publish.php
<?php
include('db.php');
function string_limit_words($string, $word_limit)
{
$words = explode(' ', $string);
return implode(' ', array_slice($words, 0, $word_limit));
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$title=mysql_real_escape_string($_POST['title']);
$body=mysql_real_escape_string($_POST['body']);
$title=htmlentities($title);
$body=htmlentities($body);
$date=date("Y/m/d");
$newtitle=string_limit_words($title, 6); // first 6 words
$urltitle=preg_replace('/[^a-z0-9]/i',' ', $newtitle);
$newurltitle=str_replace(" ","-",$newtitle);
$url=$date.'/'.$newurltitle.'.html'; // Final URL
// insert data
mysql_query("insert into blog(title,body,url) values('$title','$body','$url')");
}
?>
//جزء html
<form method="post" action="">
Title:
<input type="text" name="title"/>
Body:
<textarea name="body"></textarea>
<input type="submit" value=" Publish "/>
</form>
Article.php
<?php
include('db.php');
if($_GET['url'])
{
$url=mysql_real_escape_string($_GET['url']);
$url=$url.'.html'; //link
$sql=mysql_query("select title,body from blog where url='$url'");
$count=mysql_num_rows($sql);
$row=mysql_fetch_array($sql);
$title=$row['title'];
$body=$row['body'];
}
else
{
echo '404 Page.';
}
?>
<body>
<?php
if($count)
{
echo "<h1>$title</h1><div class='body'>$body</div>";
}
else
{
echo "<h1>404 Page.</h1>";
}
?>
</body>
.htaccess
RewriteEngine On
RewriteRule ^([a-zA-Z0-9-/]+).html$ article.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+).html/$ article.php?url=$1