1

To generate dynamically a mysql where clause using php I have done it this way

$_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));
}

this code produces this

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

Now i'd like to try to add a different "AND" clause for catid_2 and catid_3 if those are <> % but unfortunately I can not do it

I would like to get this

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

Is a possible thing to do? how can I modify my code to do it? Thank you

1 Answer 1

1

First off, there seems to be no point in adding a condition for where catid_* like '%', may as well just leave it off and only add if you have a value.

So you could just add the where clause you want for each param if it is present, something like the following (untested) sample

$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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you but I do not understand how I can apply your solution to my code in foreach function...
it was an alternative to using your foreach function - it simplifies things a little I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.