2017-07-24 68 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

相关问题