Codeigniter URL: How to display id and article tit

2019-03-11 20:09发布

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条回答
Summer. ? 凉城
2楼-- · 2019-03-11 20:27

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.

查看更多
登录 后发表回答