2017-07-24 32 views
0

如果設置了變量,那麼基於變量顯示結果的正確/有效方法是什麼?如果未設置變量,則不應使用AND運算符。僅當設置了變量時才使用SELECT運算符'AND'

我很抱歉,如果這是重複,我點擊建議的鏈接,他們沒有意義。

代碼的結尾附近是我的筆記,標記爲^^^^^。

例如:

$whatever = 123; 

SELECT 
DISTINCT terms.name as product_type_name, 
tax.term_id as termidouter 

FROM  $wpdb->posts AS p 

INNER JOIN wp_term_relationships r 
ON p.ID = r.object_id 

INNER JOIN wp_term_taxonomy tax 
ON r.term_taxonomy_id = tax.term_taxonomy_id 

INNER JOIN wp_terms terms 
ON tax.term_id = terms.term_id 

WHERE 
tax.taxonomy = 'product_type' 

AND   p.post_status = 'publish' 
AND   p.post_type = 'product' 
AND   '$whatever ' = terms.term_id 
^^^^ If $whatever is empty, I want to return results as if this line did not exist. 

ORDER BY product_type_name 
"); 

我打算做一個IF/ELSE但我想這是偷懶的方法。

$whatever = 123; 

if (empty($whatever)) { 
    // SELECT without the AND 
} else { 
    // SELECT with the AND 
} 
+1

AND($ whatever = terms.term_id或$ whatever IS NULL) –

回答

1

你可以做這樣的事情:

AND CASE WHEN '$whatever ' IS NOT NULL THEN '$whatever ' ELSE terms.term_id END = terms.term_id 
+0

謝謝。我理解這部分:CASE當'$ whatever'不是NULL然後'$ whatever'但我不明白ELSE。只需要有terms.term_id = terms.term_id就沒有什麼事情發生。 – LITguy

+1

@LITguy是的,如果'$ whatever沒有被填充,那麼filter子句將變成terms.term_id = terms.term_id,它基本上是一個冗餘過濾器,因爲它永遠是真的。您的查詢將返回結果,如果此行不存在:) – VDK

+0

標記爲答案。工作得很好,我很欣賞解釋! – LITguy

1

所以......通常你想使用準備好的語句,但是如果我們走這條路,我會收集所有的可選

$myTerms=array(); 
if(!empty($whatever)) { 
    $myTerms[]="terms.term_id='" . $whatever . "'"; 
} 
... 

然後你就可以輕鬆地構建您的查詢,像這樣:

在數組作爲字符串搜索標準

請注意這是一個基本的例子;你也應該檢查你傳遞給你的查詢的任何值以進行攻擊等。

+0

這也是一個很好的答案。 – LITguy

相關問題