title: PHP dynamically generate a mysql where clause in php
body: <p>To generate dynamically a mysql where clause using php I have done it this way</p>
  
  <pre><code>$_GET['cat_2'] = '11';
  
  $catid_1 = isset($_GET['cat_1']) &amp;&amp; $_GET['cat_1'] &lt;&gt; '' ? $_GET['cat_1'] : '%';
  $catid_2 = isset($_GET['cat_2']) &amp;&amp; $_GET['cat_2'] &lt;&gt; '' ? $_GET['cat_2'] : '%';
  $catid_3 = isset($_GET['cat_3']) &amp;&amp; $_GET['cat_3'] &lt;&gt; '' ? $_GET['cat_3'] : '%';
  $catid_4 = isset($_GET['cat_4']) &amp;&amp; $_GET['cat_4'] &lt;&gt; '' ? $_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) &amp;&amp; is_array($search)) {
  foreach ($search as $key =&gt; $value) {
  
          $operator = $value == '%' ? ' LIKE ' : ' = ';
          $where[] = $key . $operator . "'" . $value . "'";
          }
      }
  
  if (!empty($where)) {
  $whr = sprintf('WHERE %s', implode(' AND ', $where));
  }
  </code></pre>
  
  <p>this code produces this</p>
  
  <pre><code>WHERE catid_1 LIKE '%' AND catid_2 = '11' AND catid_3 LIKE '%' AND catid_4 LIKE '%'
  </code></pre>
  
  <p>Now i'd like to try to add a different "AND" clause for catid_2 and catid_3 if those are &lt;> % but unfortunately I can not do it</p>
  
  <p>I would like to get this</p>
  
  <pre><code>WHERE catid_1 LIKE '%' AND (catid_2 = '11' OR type = '0') AND catid_3 LIKE '%' AND catid_4 LIKE '%'
  </code></pre>
  
  <p>Is a possible thing to do? how can I modify my code to do it?
  Thank you</p>