如何在Codeigniter中创建动态URL?。
我有下面的表,它存储了基本的文章详细信息:
1. ID
2. Article Title
3. Content
4. Tags
5. Status
6. Create Time
7. Update Time
8. Author ID
9. Status
现在我想知道如何创建动态URL,其中包含Page ID
&CCD_ 2。
例如http://www.domain.com/1/hello-codeigniter
现在在上面的示例URL中,我使用ID
&Article Title
。
- 检索文章内容的ID(当用户点击文章时,从ID中获取内容(
- 安全URL的文章标题
但我不想从URL中显示ID
,并且在用户重定向到详细页面时仍然获得内容。
这是我的代码:
视图:home_page.php
<div id="body">
<?php for($i=0; $i<count($blogPosts); $i++): ?>
<div class="post-preview">
<?php
$postID = $blogPosts[$i]->id; // Get post ID
$postTitle = $blogPosts[$i]->title; // Get post Title
$urlTitle = preg_replace('/'s+/', '-', $postTitle); // Replacing space with dash
echo anchor('content/'.$postID.'/'.$urlTitle, $postTitle, array('title' => $postTitle)); // Get post URL
echo "<br />";
?>
</div>
<hr>
<?php endfor; ?>
</div>
控制器:home.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
public function index() {
$this->load->model("HomeModel"); // Load HomeModel
$data['blogPosts'] = $this->HomeModel->blogPosts(); // Get blog posts data from blogPostsData function
$this->load->view("home_page", $data);
}
}
型号:HomeModel.php
class HomeModel extends CI_Model {
public function blogPosts() {
$this->db->select('*');
$this->db->from('blog_posts');
$query = $this->db->get();
return $query->result();
}
}
编码后当我悬停到锚链接时,我得到了这个URL:
http://localhost/codeIgniter/index.php/content/1/My-First-Blog-Post!
如何隐藏index.php
、content
&来自URL的1
。
还有一件事是,当我点击链接时,我收到了这个错误消息:
An Error Was Encountered
The URI you submitted has disallowed characters.
任何帮助都将不胜感激!!!
您可以将routes
用于此目的
要删除index.php
,请使用带有以下代码的.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
和在config.php
中
$config['uri_protocol'] = 'AUTO';
要从url中删除内容,请从视图中的锚点中删除内容
echo anchor($postID.'/'.$urlTitle, $postTitle, array('title' => $postTitle)); // Get post URL
我认为你不应该从url中删除1
。如果你从url中删除它,那么你如何识别你的帖子。所以把它保存在url中会很好。或者,如果你想删除,那么像一样在帖子标题的末尾附加这个id
http://localhost/codeIgniter/My-First-Blog-Post!-1
并爆炸后 id的最后一个元素
An Error Was Encountered
The URI you submitted has disallowed characters.
您收到此错误是因为您在url中添加了!
。为了使您的应用程序安全,CI防止url中出现特殊字符。因此,最好不要在url中使用除_
和-
之外的特殊字符。
在控制器上
class Content extends CI_Controller {
function index($id, $name)
{
echo $name;// this contain book name
echo $id;// this contain book id
//your code
}
}
现在在您的路线application/config/routes.php
$route['(:num)/(:any)']='content/index/$1/$2';
如果将slug(安全URL的文章标题(存储在数据库中,则根本不需要公开id。不过,这需要在表中添加一列。
您可以使用这里详细介绍的url_title()
在文章创建时自动生成段塞。
<a href="<?php echo base_url()?>index.php/controller_name/method_name/<?php echo $item['name'] ?>/<?php echo $item['id'] ?>" alt="">click here to view</a>
因此,您的URL看起来像Article Title
0
控制器内
function method_name($name, $id)
{
echo $name;// this contain book name
echo $id;// this contain book id
//Simply you can use this to get all data
$result = $this->Model_name->get_book_details($id);//in model $id hold the id of book
}