PHP在php中动态生成一个mysql where子句

时间:2014-02-06 11:24:58

标签: php mysql

使用php动态生成mysql where子句我已经这样做了

$_GET['cat_2'] = '11';

$catid_1 = isset($_GET['cat_1']) && $_GET['cat_1'] <> '' ? $_GET['cat_1'] : '%';
$catid_2 = isset($_GET['cat_2']) && $_GET['cat_2'] <> '' ? $_GET['cat_2'] : '%';
$catid_3 = isset($_GET['cat_3']) && $_GET['cat_3'] <> '' ? $_GET['cat_3'] : '%';
$catid_4 = isset($_GET['cat_4']) && $_GET['cat_4'] <> '' ? $_GET['cat_4'] : '%';

// array for where clause
$search['catid_1'] = $catid_1;
$search['catid_2'] = $catid_2;
$search['catid_3'] = $catid_3;
$search['catid_4'] = $catid_4;

$where = array();
if (!empty($search) && is_array($search)) {
foreach ($search as $key => $value) {

        $operator = $value == '%' ? ' LIKE ' : ' = ';
        $where[] = $key . $operator . "'" . $value . "'";
        }
    }

if (!empty($where)) {
$whr = sprintf('WHERE %s', implode(' AND ', $where));
}

此代码生成此

WHERE catid_1 LIKE '%' AND catid_2 = '11' AND catid_3 LIKE '%' AND catid_4 LIKE '%'

现在我想尝试为catid_2和catid_3添加不同的“AND”子句,如果它们是&lt;&gt; %但遗憾的是我不能这样做

我想得到这个

WHERE catid_1 LIKE '%' AND (catid_2 = '11' OR type = '0') AND catid_3 LIKE '%' AND catid_4 LIKE '%'

可能的事情要做吗?如何修改我的代码呢? 谢谢

1 个答案:

答案 0 :(得分:1)

首先,似乎没有必要为catid_ *添加条件,例如'%',也可以将其关闭,只有在你有值时才添加。

所以你可以为每个参数添加你想要的where子句(如果存在),类似下面的(未经测试的)样本

$where = array();
$cat1 = $_GET['cat_1']; // should sanitize these to prevent sql injection
$cat2 = $_GET['cat_2']; // 

if( isset($cat_1) && $cat_1 <> '' ) { 
   $where[] = "catid_1 = '" . $cat_1 . "'";
}
if( isset($cat_2) && $cat_2 <> '' ) {  
  $where[] = "(catid_2 = '" . $cat_2 . "' OR type = '0')"
}

if (!empty($where)) {
  $whr = sprintf('WHERE %s', implode(' AND ', $where));
}