从Codeigniter中的数据库路由段或URL

时间:2018-09-04 08:05:32

标签: php codeigniter codeigniter-2

我有一些控制者:帖子,页面,作者。在每个控制器上,我想从数据库中设置单个URL。数据库页面的结构:数据库中将有成千上万的记录。

enter image description here 如何实现这一点,还应指出每个URL将基于slug从数据库加载。我从最近两天开始一直坚持下去

当前网址结构为-

  

http://127.0.0.1/hmvc/post/post_details?id=1

我想要这样的网址

  

http://127.0.0.1/hmvc/blog-post-1

2 个答案:

答案 0 :(得分:1)

由于您的数据库中已经有子弹,所以我假设您已经完成了该表的CRUD并且只想与它进行交互。

首先是您的控制器和方法:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Post extends CI_Controller {

    public function post_details($slug)
    {
        $this->load->model('article_model', 'article');
        $this->data['article'] = $this->article->get_by_slug($slug);
    }

}

/* End of file post.php */
/* Location: ./application/controllers/post.php */

然后建立您的模型:

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Article_model extends CI_Model
{

    public function get_by_slug($slug = null)
    {
        if (is_null($slug)) {
            return array();
        }
        return $this->db->where('slug', $slug)
            ->get('posts')
            ->row();
    }

}

/* End of file article_model.php */
/* Location: ./application/models/article_model.php */

最后,您的路线应如下所示:

$route['default_controller'] = 'dashboard';
$route['404_override'] = '';
$route['translate_uri_dashes'] = false;
$route['(:any)'] = 'post/post_details/$1';

答案 1 :(得分:0)

请通过将以下代码放在config / routes.php文件的底部来检查代码。

它的作用是,检查uri(不在querystring中)是否存在'blog-post-'。如果存在,则将其爆炸并检查第二部分是否为有效的正整数。如果是,则将uri的路由规则设置为“ post / post_details / {NUMBER}”。

通过尝试将其匹配重定向到“发布”控制器,不会破坏其他控制器(页面,作者)的路由规则。

$uri = $_SERVER['REQUEST_URI'];
$check_part = 'blog-post-';

if (strpos($uri, $check_part) !== FALSE) {
    $uri_parts = explode('blog-post-', $uri);
    if (count($uri_parts) == 2) {
        $id = intval($uri_parts[1]);
        if ($id > 0) $route[ltrim($uri, '/')] = 'post/post_details/'.$id;
    }
}
相关问题