我意识到这个线程很旧,但我是 CodeIgniter 的新手,并且一直在处理类似的挑战。我的挑战是创建一个搜索表单,在特定邮政编码中查找种植者。这是我的解决方案。它比我预期的要简单,并且可能对其他人有所帮助。
此代码假定您已连接到数据库并拥有标准的 MVC CI 应用程序等。
我在模型和视图中处理大部分任务,但我的控制器中确实有这个方法:
public function result()
{
$zipcode = $this->input->post('zip_code');
$query = $this->db->get_where('growers', array('zip LIKE' => $zipcode));
return $query->result_array();
}
在我的模型中,我使用了以下方法:
public function result()
{
$zipcode = $this->input->post('zip_code');
$query = $this->db->get_where('growers', array('zip LIKE' => $zipcode));
return $query->result_array();
}
我有三个视图——一个页面(位于views/pages/search.php)和两个小部件——一个用于搜索表单,一个用于搜索结果(位于views/widgets/result)。
我在结果显示的同一页面上有搜索结果表单。但是,每个部分都包含在其自己的视图文件中,我已将其放置在视图/小部件中。该部分在页面视图中的代码是:
<div class="search" style="margin-top:0px;">
<?php
$this->load->view('widgets/search');
?>
</div>
</div>
<div id="results">
<div id="grower-info">
<?php
$this->load->view('widgets/result');
?>
</div>
</div>
搜索表单小部件是:
<form action="search-results" method="post">
<input type="text" maxlength="10" name="zip_code" value="zip code" size="10">
<input type="submit" name="submit" value="SEARCH">
</form>
搜索结果小部件是:
<?php
$results = $this->pages_model->result();
foreach ($results as $result)
{
echo '<h4>'.$result['company'].'</h4>';
echo $result['address_1'] . ' ' . $result['address_2'].'<br>';
echo $result['city'].', ' . $result['state'] . ' ' . $result['zip'].'<br>';
echo 'Phone: ' . $result['office_phone'].'<br>';
echo 'Fax: ' . $result['office_fax'].'<br>';
echo 'Website: <a href="'.$result['website'].'" target="_blank">' . $result['website'].'</a><br>';
echo '<br>';
echo '<hr>';
}
if (count($results) < 1) {
echo 'No results found. Please try your search again, or try <a href="another-search">another search</a>.';
}
?>
希望对大家有所帮助!