Codeigniter-使用查询字符串进行路由

时间:2018-09-26 09:38:41

标签: php mysql codeigniter

我是Codeigniter的新手。我已经开发了一个简单的搜索表单,单击它就会显示结果。

我在表单中使用了get方法,因此在搜索时,URL类似于domain / Search / search_func?keyword = test&submit = Search。我想将URL更改为域/搜索/测试之类的内容。 这里Search是我的控制器,search_func是我的方法,而test是get参数。 我尝试使用 `$ route ['Search / search_func?(:any)'] ='Search / search_func';' 但没有运气 有人可以帮忙吗?

HTML

<form name="search_form" action="/Search/search_func">
Search: <input type="text" placeholder="Enter keywords, city, country, etc." name="keyword">
<input type="submit" name="submit" value="Search">

CONTROLLER

    <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search extends CI_Controller {
    public function index()
    {
        $this->load->view('search');
    }
    public function search_func()
    {
        $this->load->model('Search_model');
        $result['rows'] = $this->Search_model->search_result();
        $this->load->view('search_results',$result);
    }
}
?>

模型

 <?php

class Search_model extends CI_Model
{
    public function search_result(){
        $this->load->database();
        $keyword  = $this->input->get('keyword'); 
        //$query = $this->db->get("employee");
        $query = $this->db->query("select * from employee where city like '%".$keyword."%' or state like'%".$keyword."%' or country like '%".$keyword."%'");
        $results = $query->result();
        return $results;
    }
}   
?>

2 个答案:

答案 0 :(得分:0)

<form name="search_form" action="/search/">
Search: <input type="text" placeholder="Enter keywords, city, country, etc." name="keyword">
<input type="submit" name="submit" value="Search">

$route['Search/(:any)'] = 'Search/search_func/$1';

此处搜索是您的控制器(:any)将映射到您的get参数,并将由搜索控制器的search_func处理。

答案 1 :(得分:0)

您的路线已经设置

$route['search/(:any)'] = 'search/search_func/$1';

您的控制器必须具有一个参数。 所以你的控制器功能

public function search_func($keyword)
{
$this->load->model('Search_model');
        $result['rows'] = $this->Search_model->search_result($keyword);
        $this->load->view('search_results',$result);
}

关于模型功能

public function search_result($keyword){
        $this->load->database();
        $query = $this->db->query("select * from employee where city like '%".$keyword."%' or state like'%".$keyword."%' or country like '%".$keyword."%'");
        $results = $query->result();
        return $results;
    }