通过名称链接从数据库中选择文章/项目,而不是使用codeigniter

时间:2013-08-26 20:12:58

标签: php codeigniter

我无法找出问题的正确定义,所以我也无法正确地进行谷歌搜索

让我们以博客为例。 到目前为止,我已经从数据库中选择了id(自动递增)的博客文章。 www.example.com/posts/1或/ posts / 22等

让我们说帖子的名字是“我最喜欢的花朵”。我想链接出现www.example.com/posts/my-favorite-flowers而不是/ posts / 56。如果我没有错,它也更友好。

如果某人感冒提供一些材料或解释如何做到这一点,我将不胜感激。我不是在问代码,只是引导我走上正轨。

2 个答案:

答案 0 :(得分:0)

试试这个

数据库

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  

答案 1 :(得分:0)

假设网址如下:

www.example.com/posts/my-favorite-flowers

www.example.com/posts/22

在你的帖子控制器中,只需使用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.
}