Welcome Guest, Not a member yet? Register   Sign In
url segment
#1

[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);
    }
}
#2

[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.
#3

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

=)




Theme © iAndrew 2016 - Forum software by © MyBB