2016-12-27 19 views
0

如果變量$ whereEmail或變量$ whereNotEmail或兩者均爲空,則以下查詢不會選擇任何行。

$whereEmail = "'[email protected]','[email protected]'"; 
$whereNotEmail = "'[email protected]','[email protected]'"; 
$result = $mSearch->dao->query(sprintf(' 
SELECT * FROM table 
WHERE email IN (%s) 
AND email NOT IN (%s) 
', $whereEmail, $whereNotEmail)); 

變量$ whereEmail和$ whereNotEmail中的電子郵件地址是使用php函數存儲的,在某些情況下,它們留空或爲空。

我希望如果變量$ whereEmail和$ whereNotEmail都爲空,查詢應該從表中選擇所有行。

同樣,我期望如果變量$ whereEmail爲空,查詢應該選擇表中的所有行,除了那些電子郵件地址在變量$ whereNotEmail中的行。

同樣,我期望如果變量$ whereNotEmail爲空,查詢應該選擇電子郵件地址在變量$ whereEmail中的所有行。

回答

0

//你要設置的條件,其中whereEmail不是空的,whereNotEmail希望這個作品

$whereEmail = "'[email protected]','[email protected]'"; 
$whereNotEmail = "'[email protected]','[email protected]'"; 
if($whereEmail != ''){ 
$result = $mSearch->dao->query(sprintf(' 
SELECT * FROM table 
WHERE email IN (%s) 
', $whereEmail)); 
}else{ 
$result = $mSearch->dao->query(sprintf(' 
SELECT * FROM table 
WHERE email NOT IN (%s) 
', $whereNotEmail)); 
} 
0

我預計如果兩個變量$ whereEmail和$ whereNotEmail是 空的查詢應該選擇的所有行桌子。

不,查詢瞭解SQL語言結構,而不是PHP,因此您必須檢查並做相應的處理。如果我是你,那麼就會驗證這兩個列表是否都是空的。如果爲空,則彈出驗證消息,否則可能會將其傳遞給查詢。 (OR)如果任何列表爲空,那麼您可以從查詢中免除該條件。

+0

什麼http://stackoverflow.com/questions/19357990/sql-select-all-if-parameter-is-null-else-return-specfic-item它會對你有幫助嗎? – Syed

+0

@Syed,不會因爲它檢查SQLParameter而不是PHP變量。你瞭解差異嗎? – Rahul

+0

不,可以將PHP變量轉換爲SQL參數嗎? – Syed

0

如果我理解正確的話,你可以試試下面的辦法:開始構建選擇所有行的查詢,並添加條件,如果這些電子郵件數組不是空

$whereEmail = array('[email protected]','[email protected]'); 
    $whereNotEmail = array('[email protected]','[email protected]'); 

    $query = 'SELECT * FROM `table` WHERE 1'; 
    if(!empty($whereEmail)) { 
      $validEmailsString = implode('","', $whereEmail); 
      $query .= ' AND email IN ("'.$validEmailsString.'")'; 
    } 

    if (!empty($whereNotEmail)) { 
      $invalidEmailsString = implode('","', $whereNotEmail); 
      $query .= ' AND email NOT IN ("'.$invalidEmailsString.'")'; 
    } 

    print $query; 

    $result = $mSearch->dao->query($query); 
相關問題