如何将此代码转换为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
代码: - >这是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
答案 0 :(得分: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