CodeIgniter: adding parameters to URL
Asked Answered
F

4

5

Started my first CI project and am just wondering how I handle URL parameters? I have a controller named 'city', and I've modified my mod_rewrite so localhost/codeigniter uses rewrite to localhost/codeigniter/city. What I want to do is add a city name onto the end of the URL and use get segment to query a table.

So my example would be localhost/codeigniter/edinburgh. I would grab the last segment and then create the sql query. However I think when I put edinburgh into the URL CI thinks I'm looking for a controller called 'edinburgh'.

Do I have to add routing in or something similar?

Foliate answered 10/1, 2011 at 13:1 Comment(0)
M
9

You can indeed use routing to do this.

$route[':any'] = "controller/method";

This will redirect EVERYTHING after your base url to the specified controller and method inside that controller. To get the url segments you can use the URI helper.

$this->load->helper('url'); // load the helper first

$city = $this->uri->segment(1);

When accessing http://localhost/codeigniter/edinburgh the $city variable in above example would be edinburgh.

Hope that helps!

PS. You don't need mod_rewrite to specify a default controller. You can set it in your config.php under Routes. Specify city as your default controller and you can get rid of the mod_rewrite.

Mach answered 10/1, 2011 at 13:17 Comment(2)
Thanks, now my post_insert method I just being treated the same. Do i have to specify methods to ignore?Foliate
If you need more specific routing just add them as a route above the $route[':any'].Mach
L
3

Yes you can use a route:

$route[':any/'] = "myclass/by_city_method";

But why don't you use a module called (for instance) city to get the classical uri scheme?

class city extends Controller { 
   public void index($city=false) {
       if ($city) { } else { }
   }
}

Edit: you can even choose city to be the default controller, in the global config file.

Latchkey answered 10/1, 2011 at 13:9 Comment(0)
H
2

Another method:

route.php:

$route['city/(:any)'] = "city/city_lookup/$1";

city.php

<?php 
class City extends Controller {

    function City()
    {
        parent::Controller();
    }

    function city_lookup($id)
    {
        echo "$id";
    }
}
Hendiadys answered 10/1, 2011 at 13:31 Comment(0)
E
0
$path = "/codeignter/city/viewcity/Edinburg";

This will cause that City controller is called, method viewcity is executed with parameter that has value 'Edinburg' is passed!

Here is code for your controller...

class city extends Controller { 
   public viewcity($city='') {
       echo ($city === '') ? "The city you want to view is {$city}!" : "not defined!";
   }
}

Amen :)

Ethics answered 10/1, 2011 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.