如何在codeigniter查询中添加动态where子句

时间:2014-08-23 12:46:12

标签: php mysql sql codeigniter

我正在使用codeigniter并尝试进行动态查询, 现在我的查询看起来像

$query = $this->db->select('name')->get('user');
$result_array = $query->result_array();

我的问题是,如何根据变量值添加动态where子句? 所以代码看起来像

$query = $this->db->select('name')->get('user');
if(isset($name))
{
  //add where clause here, to select specific name
}
$result_array = $query->result_array();

2 个答案:

答案 0 :(得分:2)

在致电 where() 之前,只需在if语句中拨打 get()

$this->db->select('name');

if(isset($name))
{
    //add where clause here, to select specific name
    $this->db->where('name', $name);
}

$query = $this->db->get('user');    
$result_array = $query->result_array();


文档:

https://www.codeigniter.com/user-guide/database/active_record.html

答案 1 :(得分:0)

$this->db->select('name');
$name = $this->input->post('name');
if(isset($name) &&  $name  != '' && !empty($name))
{

    $this->db->where('name',$name );
}

$query = $this->db->get('user');    
$result_array = $query->result_array();

在codeigniter中查看onece活动记录

https://www.codeigniter.com/user-guide/database/active_record.html