2013-07-06 66 views
0

我開始學習codeigniters活動記錄,並且使用從控制器傳遞給模型的參數來查詢我的數據庫。codeigniter如何知道如何將參數從控制器傳遞到模型

首先,我將控制器的id傳遞給模型,並且工作正常。

控制器

function bret($id){ 
$this->load->model('school_model'); 
$data = $this->school_model->get_city_and_population($id); 
foreach ($data as $row) 
{ 
echo "<b>Name Of The City</b>...........". $row['Name']; 
echo "<br/>"; 
echo "<b>Total Population</b>...........".$row['Population']; 
} 
} 

型號

function get_city_and_population($id){ 
$this->db->select('Name,Population'); 
$query = $this->db->get_where('city', array('ID'=>$id)); 
return $query->result_array(); 
} 

我繼續放在多個參數期待失敗,但這個工程,但我不敢肯定,爲什麼它的工作或什麼工作。

控制器

public function parameters($id,$name,$district){ 
    $this->load->model('school_model'); 
    $data = $this->school_model->multiple_parameters($id,$name,$district); 
    foreach ($data as $row) 
    { 
    echo "<b>Total Population</b>...........".$row['Population']; 
    } 
    } 

型號

function multiple_parameters($id,$name,$district){ 
$this->db->select('Population'); 
$query = $this->db->get_where('city', array('ID'=>$id,'Name'=>$name,'District'=>$district)); 
return $query->result_array(); 
} 

在我的多個參數例如,我訪問了http://example.com/env/at/index.php/frontpage/parameters/7/Haag/Zuid-Holland/

在這裏,我知道這個名字Haag是ID 7和區是Zuid-Holland

這裏是我的問題。codeigniter如何知道如何將參數從url傳遞到模型,其次,如果我像7/Haag/Zuid-Hollandes/那樣稍微錯誤,我將如何向用戶顯示該URL是錯誤的並且回退到默認值值而不是在參數錯誤時顯示空白?

回答

4
//In codeiginter URI contains more then two segments they will be passed to your function as parameters. 
//if Url: http://example.com/env/at/index.php/frontpage/parameters/7/Haag/Zuid-Holland/ 

//Controller: forntpage 
public function parameters($id,$name,$district){ 
    echo $id.'-'$name.'-'.$district; 
} 

//and if you are manually getting url from segment & want to set default value instead of blank then use following: 



public function parameters(
$this->load->helper("helper"); 
$variable=$this->uri->segment(segment_no,default value); 
//$id=$this->uri->segment(3,0); 
} 

//or 
//Controller: forntpage 
public function parameters($id='defaultvalue',$name='defaultvalue',$district='defaultvalue'){ 
    echo $id.'-'$name.'-'.$district; 
} 
+0

'...傳遞給你的函數作爲參數'是非常有用的。多謝了。 –

1

這只是在CI中的簡單URI映射,或者如果您願意,可以使用uri param綁定。
當你有這樣的方法:

public function something($param1, $param2) { 
    // get from: controller/something/first-param/second-param 
} 

這意味着你的URI段被作爲參數傳遞給您的控制器方法傳遞。

public function something() { 
    $param1 = $this->uri->segment(3); 
    $param2 = $this->uri->segment(4); 
    // segment 1 is the controller, segment 2 is the action/method. 
} 

你要明白,你必須手動檢查URI段,你想他們是什麼,因爲CI沒有做任何事情:作爲

上述方法可以寫成比這個映射。

接下來,如果你想有一些默認值,下面的語句是正確的:

public function something($param1 = 'some default value', $param2 = 'other value') { 
// get from: controller/something/first-param/second-param 
} 

也就是說,如果像網址:/controller/something被傳承下去,你仍然會得到您的默認值返回。當傳遞controller/something/test時,您的第一個參數將被url(測試)中的參數覆蓋。

就是這樣。

相關問題