CodeIgniter Forums
How to add page title in url? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: How to add page title in url? (/showthread.php?tid=71609)



How to add page title in url? - Huskie - 09-04-2018

I'm learn Codeignite on someone else's source. How to add $title for url in this controller?
As: website/mainitems/$id/$title
Code:
class mainitems extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
    }
    
    //single movie page
    public function index($param = null)
    {
        $this->load->helper("form");
        $this->load->helper('url');

        $uri_string = $this->uri->segment(2);
        $movie = explode("-", $uri_string);
        $movieID = $this->db->escape(abs(intval(end($movie))));
        
        //get movie data
        $itemsRs = $this->db->get_where("items", array("id" => $movieID));
        $movieData = $itemsRs->result();
        
        $title = $movieData[0]->title;
        
        //data - result
        $data['movie_info'] = $movieData;
        
        $this->load->view('items', $data);
    }



RE: How to add page title in url? - Wouter60 - 09-04-2018

Why do you need the id as well as the title in the url? The id is unique, so you can always use that to find the proper database record. If you prefer user friendly URL's, don't include the id, just the title. But be careful: the title may contain characters that are not allowed in URL's. It's better to use a "slug", basically a string that's converted to a format that is allowed in URL's.
CodeIgniter has a function for that, in the url helper: url_title().

See documentation: https://www.codeigniter.com/userguide3/helpers/url_helper.html?highlight=url_title#url_title

Obviously, you must take care that each slug is unique. Of you've got that set up, you can find the database record like this:
PHP Code:
$record $this->db->where('slug'$title)->get('posts')->row(); 


The CodeIgniter tutorial also covers the use of slugs:
https://www.codeigniter.com/userguide3/tutorial/news_section.html