 <p><strong>SQL INJECTION</strong></p> <p>^ Please Google that! Your code is <em><strong>seriously vulnerable!</strong></em> Your data can be stolen or deleted...</p> <p><strong>You have to sanitize your inputs at least with <a href="https://dev.mysql.com/doc/apis-php/en/apis-php-mysqli.real-escape-string.html" rel="nofollow"><code>mysqli_real_escape_string()</code></a></strong></p> <p>Even better would be to <a href="http://stackoverflow.com/a/60496/1667004">take proper countermeasures to SQL injection</a> and use prepared statements and parametrized queries! (as shown in the code below)</p> <hr> <p>I think the best approach would be to handle the logic by altering the query based on the values of the variables:</p> <pre><code>$sql = "SELECT p.price, p.type, p.area, p.floor, p.construction, p.id as propertyID, CONCAT(u.name, ' ',u.family) as bname, p.type as ptype, n.name as neighborhoodName, CONCAT(o.name,' ',o.surname,' ',o.family) as fullName FROM `property` p LEFT JOIN `neighbour` n ON p.neighbour = n.id RIGHT JOIN `owners` o ON p.owner = o.id LEFT JOIN users u ON p.broker = u.id WHERE `neighbour`= :current "; //note: ending white space is recommended //lower boundary clause -- if variable null - no restriction if(!is_null($priceFrom){ sql = sql . " AND `price` &gt;= :priceFrom "; // note: whitespace at end and beginning recommended } //upper boundary -- better than to set it to an arbitrary "high" value if(!is_null($priceTo)){ sql = sql . " AND `price` &lt;= :priceTo "; // note: whitespace at end and beginning recommended } </code></pre> <p>This approach allows for any upper value: if there is a serious inflation, a different currency, or suddenly the code will be used to sell housese and there will be products with prices > 200000, you don't need to go out and change a lot of code to make it show...</p> <p>The parameters need to be bound when executing the query of course:</p> <pre><code>$stmt = $dbConnection-&gt;prepare(sql); $stmt-&gt;bind_param('current', $current); if(!is_null($priceFrom)){ $stmt-&gt;bind_param('priceFrom', $priceFrom); } if(!is_null($priceTo)){ $stmt-&gt;bind_param('priceTo', $priceTo); } //execute and process in same way $stmt-&gt;execute(); </code></pre> <p><strong>Also note:</strong> from your code it seems you are issuing queries in a loop. That is <strong>bad practice</strong>. If the data on which you loop comes </p> <ul> <li>from the DB --> use a <code>JOIN</code></li> <li>from an array or other place of the code --> better use an <code>IN</code> clause for the elements</li> </ul> <p>to fetch all data with one query. This helps a lot both in organizing and maintaining the code and results generally in better performance for the most cases.</p>