2011-07-14 29 views
0

這是怎麼代碼轉換爲笨代碼:如何將此代碼中的錯誤轉換並修復爲CodeIgniter?

search_hotel: - >這是CI_Model

return mysql_query("select * from hotel_submits where name LIKE '".$searchterm."'") 

我嘗試,但有錯誤:

$query = $this->db->order_by("id", "desc")->like('name', '$searchterm')->get('hotel_submits'); 
     return $query->row(); 

錯誤:

A PHP Error was encountered 
Severity: Warning 
Message: mysql_fetch_assoc() expects parameter 1 to be resource, array given 
Filename: admin/tour.php 
Line Number: 15 


A PHP Error was encountered 
Severity: Notice 
Message: Undefined variable: data 
Filename: admin/tour.php 
Line Number: 21 

code: - >這是CI_Controller

$searchterm = $this->input->post('search_hotel'); 
$result = $this->model_tour->search_hotel($searchterm); 
while ($row = mysql_fetch_assoc($result)) { //this is line 15 
//giving names to the fields 
$data = array (
    'name' => $row->name,    
); 
} 
echo json_encode($data); //this is line 21 

回答

3

認爲這裏有各種各樣的東西。在您返回$ query-> row()的模型中,您只會返回一個記錄集行。你應該試試$ query-> result()來代替。我還建議將你的控制器中的代碼移入模型中。所以,你的模型將開始看起來像:

function search_hotel($searchterm) 
{ 

$query = $this->db->order_by("id", "desc")->like('name', $searchterm)->get('hotel_submits'); 

$data = array(); 

foreach ($query->result() as $row) 
{ 
    data[] = $row->name 
} 

return $data 
} 

所以,你的控制器簡單變得像:

function your_controller() { 
//Set your $search_term somehow 

    echo json_encode($this->model('your_model_name')->search_hotel($search_term); 
} 

希望這應該開始指向你在正確的軌道上。有關創建和使用記錄集的完整信息可以在CI文檔中找到 - http://codeigniter.com/user_guide/database/index.html

+1

控制器應該「回顯」數據,而不是「返回」它。 –

+0

好點!相應編輯。 – simnom

+0

'$ this-> model('your_model_name')'無效。它應該是'$ this-> your_model_name'。搜索結果的 –