忽略空条件,如果空
问题描述:
$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
为空,它会给出sql错误。忽略空条件,如果空
答
你好你可以简单地做到这一点。使用$sql
的concatnation
。如果$name
和$address
存在
$name=Yii::$app->request->post('name');
$address=Yii::$app->request->post('address');
$sql = "SELECT * FROM studentrecords where 1 = 1 ";
if($name)
{
$sql.=" AND name='$name'" ;
}
if($address) {
$sql.= " AND address= '$address'";
}
$display=Yii::$app->db->createCommand($sql)->queryAll();
答
检查这个......
$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;
+1
如果没有名称和地址,则查询将失败;)。做一些像$ where =''; if(count($ conditions)){$ where = ...}我已经做了一些编辑 – Eduardo
答
如果你有ActiveRecord的,你可以,你andFilterWhere
$query = StudentRecors::find()
->andFilterWhere(['=', 'name', $name])
->andFilterWhere(['=', 'address', $address])->all();
andFilterWhere管理凡在道路条件是其中添加到查询的部分只有当相关值not null
+0
这是提供信息。但由于某些原因,我需要数组中的值。 – micky
您在if语句中使用OR,然后在查询中使用AND应该会给您一个提示。从逻辑上讲,用同一个操作员做这些事情是有道理的,不是?请注意,php将'False,null和0'视为假 – ArtisticPhoenix