Sethen
Sethen

Reputation: 11348

Passing parameters in CodeIgniter

I have been banging my head against this problem for about an hour now. I have looked high and low but nothing is working for me. This should be simple and I am sure it is.

I am trying to pass some parameters in CodeIgniter to a URL and nothing seems to be working. Here is my controller:

class Form_controller extends CI_Controller {
    public function change($key = NULL) {
        if (is_null($key)) {
            redirect("reset");
        } else {
            echo "Hello world!";
        }
    }
}

Here is my route:

$route['change/(:any)'] = "form_controller/change/$1";

Every time I visit /index.php/change/hello I get the string "Hello world!" but when I visit /index.php/change I got a 404 not found.

What I am trying to do is pass a parameter to my controller for the purposes of checking the DB for a specific key and then acting upon it. If the key does not exist in the DB then I need to redirect them somewhere else.

Any thoughts on this?

Upvotes: 1

Views: 6687

Answers (2)

Chitowns24
Chitowns24

Reputation: 960

This might help you out

public function change() {
 $key = $this->uri->segment(3);

http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html

This allows you to grab the segment easily using the CI url helper

index.php/change/(3RD Segment) this part will go into that variable $key.

This may not be what you are looking for but it is very useful if you are trying to pass two variables or more because you can just grab the segment from the url and store it into the variable

Upvotes: 1

Sethen
Sethen

Reputation: 11348

Never mind, I figured it out. I ended up making two different routes to handle them, like so:

$route['change'] = "form_controller/change";
$route['change/(:any)'] = "form_controller/change/$1";

And the function in the controller looks like this now:

public function change($key = NULL) {
    if (is_null($key)) {
        redirect("reset");
    } else if ($this->form_model->checkKey($key)) {
        $this->load->view("templates/gateway_header");
        $this->load->view("forms/change");
        $this->load->view("templates/gateway_footer");
    } else {
         redirect("reset");           
    }
}

If anyone has a better solution, I am all ears. This worked for me though.

Upvotes: 2

Related Questions