CodeIgniter Forums
url segment - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: url segment (/showthread.php?tid=23679)



url segment - El Forum - 10-19-2009

[eluser]georgerobbo[/eluser]
I'm trying to query my database based on the second segment in my url, however I'm struggling with the controller side.

My Model, named Post is as follows.
Code:
<?php

class Post extends Model {

    function Post()
    {
        parent::Model();
    }
    
    function get_random_single()
    {
        $this->db->select('*');
        $this->db->orderby('ID', 'random');
        $this->db->limit(1);
        
        $query = $this->db->get('post');
        return $query->result_array();
    }
    
    function get_posts_by_category()
    {
        $category = $this->uri->segment(2);
        
        $this->db->select('*');
        $this->db->where('category', $category);
        
        $query = $this->db->get('post');
        return $query->result_array();
    }
    
}

An my controller category
Code:
<?php

class Category extends Controller {

    function Category()
    {
        parent::Controller();    
    }
    
    function index()
    {
        $data['title'] = "Category";
        
        $data['item'] = $this->Post->get_posts_by_category();
        
        $this->load->view('meta', $data);
        $this->load->view('header', $data);
    }
}



url segment - El Forum - 10-19-2009

[eluser]umefarooq[/eluser]
hi first keep your model clean only for database functions. get you all url segments in controller and pass to you model functions.

controller
Code:
<?php

class Category extends Controller {

    function Category()
    {
        parent::Controller();    
    }
    
    function index()
    {
        $data['title'] = "Category";
        $category = $this->uri->segment(2);
        $data['item'] = $this->Post->get_posts_by_category($category);
        
        $this->load->view('meta', $data);
        $this->load->view('header', $data);
    }
}

model
Code:
function get_posts_by_category($category)
    {
        $this->db->select('*');
        $this->db->where('category', $category);
        
        $query = $this->db->get('post');
        return $query->result_array();
    }

also debug it with echo $category in controller that you are getting proper value in you uri segment or not.


url segment - El Forum - 10-19-2009

[eluser]georgerobbo[/eluser]
The reason It wasn't working is because it was looking for the function instead of the ID. A little bit of URL routing and everything is working.

=)