Codeigniter if URL segment is missing
Having fo开发者_Python百科und out that 3rd URL segments can be passed directly to the a function's parameter I did the following.
URL example:
http://www.mysite.com/profile/user/64
Function in profile
controller:
function user($user_id) //$user_id is 3rd URL segment
{
//get data for user with id = $user_id
}
Using $this->uri->segment(3)
returns FALSE is no segment exists. With the function parameter I get
Missing argument 1
How can I return FALSE and not execute the function if the 3rd URL segment is missing? I'm looking for a simple solution without if statements, if possible.
You get "Missing argument 1" because the function does not get the argument.
Try
function user(){
if($this->uri->segment(3)){
//get data for user with id = $this->uri->segment(3)
}
}
What about default arguments:
function user($user_id = FALSE) //$user_id is 3rd URL segment
{
//get data for user with id = $user_id
}
You could also use this:
public function user($id = null)
{
if(!isset($id))
exit();
// get data for user with id = $id
}
or this
public function user()
{
if( ! $this->uri->segment(3) )
exit();
// get data for user with id = $id
}
if ($this->uri->segment(3)) {
return true
} else {
return false
}
精彩评论