3
votes

I just learned about routing in CodeIgniter and now I am lil bit confuse.

I have an URL like this : http://localhost/norwin/list_group/get_product_by_group/1

Which is:

  1. list_group is controller,

  2. get_product_by_group is method,

  3. and '1' is passing parameter.

I want to minimize the URL with route. So I can have an URL like :

http://localhost/norwin/group/'group_name'

And this is my code on route.php :

$route['group/(:any)'] = 'list_group/get_product_by_group/$1';

this is my controller :

    public function get_product_by_group($group_name)
    {
         
            if($this->uri->segment(3))
            {
                    $this->load->database();
                    $data['product_data'] = $this->group_model->list_product_by_group($group_name);
                    $this->load->view('fend/list_product', $data);

            }
            else
            {
                    redirect('list_group');
            }

    }

And this is my code on view which call the controller :

<?= base_url('group/'. $value->group_name);?>

my problem is : I can not get any result of the route, it always send me to 'list_group'.

Maybe someone here have a good approach to do this.

Thanks for your help.

1
the route configuration is fine. what errors you are facing? - Kamran
@KamranAdil : The result is always redirect me into 'list_group' - TableMan
it is redirecting you because you don't have $this->uri->segment(3) in your URL. You only have two segments 'group' and 'group_name'. change it to $this->uri->segment(2) - Kamran
thanks, I didnt realize it, sorry - TableMan

1 Answers

2
votes

You are being redirected because $this->uri->segment(3) is not returning anything as your URL http://localhost/norwin/group/'group_name' have only 2 segments.

Codeigniter $this->uri->segment(n); works in the following way.

URL: http://localhost/norwin/group/group_name/some_test

it will return

$this->uri->segment(1); // group
$this->uri->segment(2); // group_name
$this->uri->segment(3); // some_test

you have to change $this->uri->segment(3) to $this->uri->segment(2)