codeigniter where field =来自表单的数据

时间:2011-12-21 05:17:42

标签: codeigniter activerecord

我试图通过邮政编码搜索匹配供应商:

型号代码:

function get_suppliers(){
    $this->db->from('suppliers');
    $this->db->where('postcode', $data);
    $this->db->select('name,type,site,contact,number');

    $q = $this->db->get();

    if($q->num_rows() > 0) {
        foreach($q->result() as $row) {
            $data[] = $row;
        }
        return $data;
    }
}

控制器代码:

public function index()
{
$this->load->library('form_validation');

    $this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
    $data = array(
        'postcode' => $this->input->post('postcode')
                );
    if($this->form_validation->run() == FALSE)
    {
        ## reload page ##
        $this->load->view('welcome_message');
    }
    else
    {
    $this->load->model('site_model');

    $this->site_model->add_record($data);   

    echo("postcode entered");   

    $data['rows'] = $this->site_model->get_suppliers($data);
    print_r($data);
    }
}

显然忽略了打印机和回声,只是我带来了看看发生了什么我很确定我只需要将模型中的$ data更改为不确定的东西(尝试堆积的东西)

2 个答案:

答案 0 :(得分:0)

在你的模特中:

function get_suppliers($data = ''){

即:您没有将$data作为参数

答案 1 :(得分:0)

<强>型号:

function get_suppliers($postcode = '*') // <-- Capture the postcode
{
    $this->db->from('suppliers');
    $this->db->where('postcode', $postcode); // <-- pass it in here
    $this->db->select('name,type,site,contact,number');

    $q = $this->db->get();

    if($q->num_rows() > 0)
    {
        foreach($q->result() as $row)
        {
            $data[] = $row;
        }
        return $data;
    }
}

<强>控制器:

public function index()
{
    $this->load->library('form_validation');

    $this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');

    $data = array(
        'postcode' => $this->input->post('postcode')
    );

    if($this->form_validation->run() == FALSE)
    {
        ## reload page ##
        $this->load->view('welcome_message');
    }
    else
    {
        $this->load->model('site_model');

        $this->site_model->add_record($data);   

        $data['rows'] = $this->site_model->get_suppliers( $data['postcode'] ); // <-- pass the postcode

        echo("postcode entered: " . $data['postcode'] . "<pre>");
        print_r($data);
    }
}