【问题标题】:Codeigniter URL: How to display id and article title in the URLCodeigniter URL:如何在 URL 中显示 id 和文章标题
【发布时间】:2012-05-21 10:47:36
【问题描述】:

请看以下链接结构

http://stackoverflow.com/questions/10672712/voting-system-like-stackoverflow

在上面的链接中,10672712 是我猜的问题 ID,因为如果您检查以下链接,您将到达与上面相同的位置:

 http://stackoverflow.com/questions/10672712

现在,如果您使用上面的链接,那么您会注意到在浏览器的地址栏中,该链接会在问题 ID 之后自动添加问题标题(作为 slug),并且它看起来就像上面的第一个链接。

我正在尝试使用 Codeigniter 创建一个基于文章的网站。为了显示特定文章,我有一个如下所示的控制器:

function articles(){


    $id=$this->uri->segment(3);

    $this->load->model('mod_articles');
    $data['records']=$this->mod_articles->list_articles($id);
    $this->load->view('view_article',$data);
     }

我的模特:

  function list_articles($id)

       $this->db->select('*');
        $this->db->from('cx_article');
        $this->db->join('cx_author', 'cx_author.author_id = cx_article.author_id');
        $this->db->where('article_id', $id); 
        $query = $this->db->get();

       if ($query->num_rows() > 0)
        { return $query->row_array();
        }
        else {return NULL;}

    }  

如果你点击这个-> localhost/my_base_url/my_controller/my_funtion/article_id 那么我的文章就会出现。现在我想要实现的是,如果有人点击localhost/my_base_url/my_controller/my_funtion/article_id,我想在article_id之后自动添加文章标题作为slug。(就像我上面给出的例子)

你能告诉我怎么做吗?

谢谢:)

P.S 在我的数据库表中,我有一个名为 article_slug 的列,其中我将文章标题存储为 slug(例如:voting-system-like-stackoverflow)。

【问题讨论】:

    标签: codeigniter codeigniter-2 codeigniter-routing


    【解决方案1】:

    controllers/my_controller.php

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class My_controller extends CI_Controller {
    
        function my_function($int_id = NULL, $str_slug = '') {
    
            $row = $this->db->get_where('cx_article', array('article_id' => $int_id))->row();
    
            if ($row and ! $str_slug) {
    
                $this->load->helper('url');
    
                $str_slug = url_title($row->title, 'dash', TRUE);
                redirect("my_controller/my_function/{$int_id}/{$str_slug}");
    
            }
    
            // Run the rest of the code here
    
        }
    
    }
    

    在您的数据库中有一个 slug 列是没有意义的,因为您没有根据您的 slug 识别任何内容,也不是唯一的。

    【讨论】:

    • 好的,我将删除 slug 列。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2011-12-13
    相关资源
    最近更新 更多