2

基本上,此代码通过提取用户在表单中输入的数据来发挥作用,并连接到模型,该模型根据输入的信息执行查询搜索。

此代码有效,但仅当我同时输入 $no 和 $first 字段时才有效。但我需要它工作,这样用户才能输入 $no 并将其他变量留空。

我以为我可以使用某种 OR 语句,但我不确定如何实现它。任何帮助将不胜感激,如果它不够清楚,我对codeigniter还很陌生,我深表歉意。

控制器

    public function query()

{

    $no = $this->input->post('no');
    $first = $this->input->post('first');
    $this->load->model("test");
         $data['query']=$this->test->query($no,$first);
        $this->load->view('query',$data);

}

模型

function query($no, $first)
{

 return $query = $this->db->get_where('table', array('no' => $no,
 'first' => $first ))->result();

}

看法

<?php foreach($query as $row): ?>
<tr> 
    <td><?php echo $row->no; ?></td>
    <td><?php echo $row->date; ?></td>
    <td><?php echo $row->first; ?></td>


    </tr>
    <?php endforeach; ?>
4

3 回答 3

2

跳过任何未提供的参数怎么样?

function query($no, $first)
{
  $where = array();

  if ($no != '') $where['no'] = $no;
  if ($first != '') $where['first'] = $first;

  if (empty($where))
  {
    return array(); // ... or NULL
  }
  else
  {
    return $query = $this->db->get_where('table', $where);
  }
}
于 2012-12-02T21:56:51.863 回答
0

例如

if(strlen($no)>0 && strlen($first)>0){
   $data['query']=$this->test->query($no,$first);
}else{
   $data['query']=$this->test->query($no);//or $first
}
于 2012-12-02T21:57:47.910 回答
0

您也可以使用默认参数概念。可以检查用户是否传递了两个参数,因此您可以调用模型并可以发送参数。

考虑到您的示例,我正在编写代码:

控制器

public function query()
{

$no = $this->input->post('no');
if($this->input->post('first'))
  $first = $this->input->post('first');
$this->load->model("test");
if($first != '')
  $data['query']=$this->test->query($no,$first);
else
  $data['query']=$this->test->query($no);
$this->load->view('query',$data);
}

模型

function query($no, $first = null)
{

 return $query = $this->db->get_where('table', array('no' => $no,
 'first' => $first ))->result();

}

看法

<?php foreach($query as $row): ?>
<tr> <td><?php echo $row->no; ?></td>
    <td><?php echo $row->date; ?></td>
    <td><?php echo $row->first; ?></td>
</tr>
<?php endforeach; ?>

使用这个概念,您可以在不同的地方使用相同的功能。例如。您使用两个差异创建了搜索功能。用于搜索的参数,但使用默认参数概念,您可以使用相同的函数来搜索带有一个或两个参数的数据库。

我希望我对你有帮助!:)

于 2014-07-07T07:30:19.103 回答