Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 492
black_belt Avatar asked Dec 02 '25 05:12

black_belt


1 Answers

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.

like image 79
Robin Castlin Avatar answered Dec 03 '25 23:12

Robin Castlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!