Codeigniter URL:如何在URL中显示id和文章标题

时间:2012-05-21 10:47:36

标签: codeigniter codeigniter-2 codeigniter-routing

请参阅以下链接结构

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)。

1 个答案:

答案 0 :(得分:9)

<强>控制器/ 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识别任何东西,也不是唯一的。

相关问题