Codeigniter URL: How to display id and article title in the URL

故事扮演 提交于 2019-12-03 08:51:33

问题


Please see the following link structure

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

In the above link the 10672712 is the question id I guess, because if you check the following link you will get to the same location as above:

 http://stackoverflow.com/questions/10672712

Now if you use the above link then you will notice that in the browser's address bar the link automatically adds the question title (as slug) after the question id and it appears just like the first link above.

I am trying to create an article based website using Codeigniter. To display a particular article I have a controller which looks like following:

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);
     }

My Model:

  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;}

    }  

If you hit this-> localhost/my_base_url/my_controller/my_funtion/article_id then my article shows up. Now what I am trying to achieve is if someone hits localhost/my_base_url/my_controller/my_funtion/article_id I want to automatically add the article title as slug right after the article_id.(Just like the example I have given above)

Could you please tell me how to do that?

Thanks:)

P.S In my DB table I have a column called article_slug, in which I store my article title as slug(example: voting-system-like-stackoverflow ).


回答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

    }

}

There is no point to have a slug column in your database since you don't identify anything based on your slug, nor is it unique.



来源:https://stackoverflow.com/questions/10683820/codeigniter-url-how-to-display-id-and-article-title-in-the-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!