【发布时间】:2015-08-02 06:53:57
【问题描述】:
如何在 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 和 Article Title。
例如http://www.domain.com/1/hello-codeigniter
现在在示例 URL 上方,我正在生成带有 ID 和 Article Title 的 URL。
- 检索文章内容的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!
如何在 URL 中隐藏 index.php、content 和 1。
还有一件事是,当我单击链接时,我收到了以下错误消息:
An Error Was Encountered
The URI you submitted has disallowed characters.
任何帮助将不胜感激!!!
【问题讨论】:
-
我从来没有使用过 CI,但我会大胆猜测
site_url()?
标签: php codeigniter codeigniter-2 codeigniter-routing