我有一个包含两个方法的类,用于此问题showone
和view
。后者返回小型数据库的所有项目,也可以执行搜索。另一个是针对像domain.com/showone/firstname-lastname
<?php
class Pages extends CI_Controller {
public function view($page)
{
//this includes a mysql search
}
public function showone($slug)
{
//abbreviated version:
$query = "SELECT * FROM mytable WHERE slug = '" . $slug . "'";
$result = $this->db->query($query);
if ($result->num_rows() == 0)
{
//here is where I'd like to use the same search that I used in showall
}
else
{
//show the one item
}
}
} //class
?>
因此,如果用户决定直接输入一个不会从数据库返回任何内容的URL,我想引导他搜索结果而不是显示404。
那么如何设置function searchdatabase($query)
和showone
同时使用的view
?
答案 0 :(得分:0)
在模型中定义该函数,加载模型,然后调用model-&gt;方法。
<?php
//Your Model would look something like this.
class Search_Model extends CI_Model {
public function __construct(){
parent::__construct();
}
public function showone($slug)
{
//abbreviated version:
//Its best to use active record for building your queries
$this->db->where->('slug', $slug);
$result = $this->db->get('mytable');
if ($result->num_rows() == 0)
{
//here is where I'd like to use the same search that I used in showall
}
else
{
//show the one item
}
}
} //class
然后在你的控制器中你会这样做:
<?php
//Your Controllerwould look something like this.
class Index extends CI_Controller {
public function __construct(){
parent::__construct();
//model will be loaded for each method.
//if you're going to use this model across several controllers
//its best to autoload it, set that in autoload.php under /app/config
$this->load->model('search_model');
}
public function index(){
$searchResults = $this->search_model->showone('slugone');
}
我刚刚意识到如果没有返回结果,你想要显示所有结果。在这种情况下,您也可以在模型中执行该逻辑。
在条件声明中,您将执行以下操作:
if ($result->num_rows() == 0)
{
return $this->showall();
}
else
{
return $this->view($slug);
}
}
您的showall()
和view()
方法return $result->result();
答案 1 :(得分:0)
您可以在控制器内使用控制器功能:
public function view($page)
{
$this->showone($slug);
}