如果为null,则忽略where条件

时间:2016-07-30 04:19:55

标签: php yii yii2

$name=Yii::$app->request->post('name');
$address=Yii::$app->request->post('address');

if($name || $address)
{
    $sql="SELECT * FROM studentrecords WHERE name=$name AND address=$address" ;
    $display=Yii::$app->db->createCommand($sql)->queryAll();
}

我需要的是,如果我在地址字段中输入地址,请忽略WHERE address=$address。目前,如果$address为null,则会出现sql错误。

3 个答案:

答案 0 :(得分:3)

如果你有activeRecord,你可以andFilterWhere

         $query = StudentRecors::find()
                ->andFilterWhere(['=', 'name', $name])
                ->andFilterWhere(['=', 'address', $address])->all();

andFilterWhere管理where条件,只有在相关值不为null时才将where的一部分添加到查询中

答案 1 :(得分:1)

您好,您可以这样做。使用List<MyDTO> myDTOList的{​​{1}}。如果存在concatnation$sql

$name

答案 2 :(得分:0)

检查......

 $name=Yii::$app->request->post('name');
    $address=Yii::$app->request->post('address');
    $conditions = array();
    $where = '';

    if ($name) {
      $conditions[] = 'name= "'.$name.'"';
    }
    if ($address) {
      $conditions[] = 'address= "'.$address.'"';
    }

    if(count($conditions)) {
      $where = 'WHERE '.implode(' AND ', $conditions);
    }

    $sqlStatement = 'SELECT * FROM studentrecords '.$where;