2012-05-21 21 views
2

請看下面的鏈接結構笨網址:如何在URL中顯示的ID和文章的標題

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

在上面的鏈接10672712是問題的id我想,因爲如果你查看以下鏈接你將獲得相同的位置上面:

http://stackoverflow.com/questions/10672712 

現在,如果你的問題的id和之後使用上面的鏈接,那麼你會發現,在瀏覽器的地址欄中的鏈接會自動添加問題的標題(如蛞蝓)就像上面的第一個鏈接一樣。

我想創建一個基於文章的網站使用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列,其中我存儲我的文章標題作爲蛞蝓(例如:投票系統樣計算器)。

回答

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 

    } 

} 

沒有點在你的數據庫,因爲你不認同基礎上的塞任何東西塞列,也不是唯一的。

+0

謝謝:)輝煌 –

+0

好吧,我會刪除slug列。謝謝 :) –

相關問題