2016-07-30 104 views
1
$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錯誤。忽略空條件,如果空

+0

您在if語句中使用OR,然後在查詢中使用AND應該會給您一個提示。從邏輯上講,用同一個操作員做這些事情是有道理的,不是?請注意,php將'False,null和0'視爲假 – ArtisticPhoenix

回答

1

你好你可以簡單地做到這一點。使用$sqlconcatnation。如果$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(); 
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; 
+1

如果沒有名稱和地址,則查詢將失敗;)。做一些像$ where =''; if(count($ conditions)){$ where = ...}我已經做了一些編輯 – Eduardo

3

如果你有ActiveRecord的,你可以,你andFilterWhere

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

andFilterWhere管理凡在道路條件是其中添加到查詢的部分只有當相關值not null

+0

這是提供信息。但由於某些原因,我需要數組中的值。 – micky