我再次陷入MySQL查询,我想要一些帮助。
我正在努力找到最好的方法来做到这一点。我想要做的是检查$ var ='x'并根据它运行不同的查询。
部分代码:
if ($var1 == '0' AND $var2 != '0' AND $var3 != '0' AND $var4 != '0') {
echo $query = "SELECT * FROM table WHERE var1 = ''";
}elseif ($var1 == '1' AND $var2 != '0' AND $var3 != '0' AND $var4 != '0') {
echo $query = "SELECT * FROM table WHERE var1 = '1'";
}elseif ($var1 != '0' AND $var2 == '0' AND $var3 != '0' AND $var4 != '0') {
echo $query = "SELECT * FROM table WHERE var2 = ''";
}elseif ($var1 == '0' AND $var2 == '0' AND $var3 != '0' AND $var4 != '0') {
echo $query = "SELECT * FROM table WHERE var1 = '' AND var2 = ''";
} etc..
连接很多。有一个更好的方法吗?几乎每个变量(共7个)都有3种不同的选择。我不能把var = $var
放在WHERE子句下面,因为有时$var = '0'
我的意思是所有的结果所以我甚至没有把它放在那里..
这是一个过滤脚本/代码..
这对你有意义吗? 谢谢!
答案 0 :(得分:2)
我认为这可以通过单个查询和不同的WHERE条件来完成。您需要首先定义何时将var1 = ''
放入WHERE子句中。当您在查询中逐一需要varX = ''
时,您应该找出案例。
$conds = array();
if ($var1 == '0' || $var2 == '0') {
$conds[] = "var1 = ''"; // this should be the only point where var1 is included in your query, so you need to have every possible condition in this if part
}
if ($var3 == '0' && $var4 != '0') {
$conds[] = "var3 = ''";
}
// ..etc..
$query = "SELECT * FROM TABLE WHERE " . implode(' AND ', $conds);
答案 1 :(得分:0)
怎么样:
$where_parts = array();
if (isset($var1)) {
if ($var1 == 0) { $var1 = ''; }
$where_parts [] = "var1 = '" . $var1 . "'";
}
if (isset($var2)) {
if ($var2 == 0) { $var2 = ''; }
$where_parts [] = "var2 = '" . $var2 . "'";
}
if (isset($var3)) {
if ($var3 == 0) { $var3 = ''; }
$where_parts [] = "var3 = '" . $var3 . "'";
}
if (isset($var4)) {
if ($var4 == 0) { $var4 = ''; }
$where_parts [] = "var4 = '" . $var4 . "'";
}
$query = "SELECT * FROM table WHERE " . implode(' AND ', $where_parts );
答案 2 :(得分:0)
您是否有可能只专注于与查询相关的变量?例如:
$str = "";
# When will "var1" be in the query
switch($var1) {
case '0' : $str .= " AND $var1=''"; break;
case '1' : $str .= " AND $var1='1'"; break;
}
# When will "var2" be in the query
switch($var2) {
case '0' : $str .= " AND $var2=''"; break;
case '1' : $str .= " AND $var2='1'"; break;
}
...
# If not empty then remove the first " AND "
if(!empty($str)) {
$str = substr($str,4);
}
# Final query is a lot of concatenated strings
$query = "SELECT * FROM table WHERE $str";
它可能不是代码最优化的,但很容易理解。