April 26, 2012
Passing URI segments into Codeigniter functions
Question by luckytaxi
Let’s say I have a view
method that receives a variable via the URI.
ex. http://www.domain.com/item/view/200
Does it make sense to turn the incoming variable into the correct type? In this case, making $item_id
into int
which is what is expected.
For example, in the controller …
function view($item_id) {
if ( $this->item_model->checkItem( (int) $item_id )) {
...
}
}
Answer by Starx
Yeah, casting the variable as integer like you are doing is OK.
And the way to pass the segment into function is like
$segment = $this->uri->segment(2); //get the second segmention
// ^ You can send a default Values as well if itemid is not set
// Like: $this -> uri -> segment(2, '0')
//now pass it to the function you need