Jason Wood Jason Wood - 5 months ago 13
SQL Question

Mysqli query using $_get where a value is missing

I have a drop-down box where a user can select a location. Then, there is a text box where they can input a maximum rental price (there will be a few more options but to keep things simple just these in the example). Then this will go to a results.php page and using the $_GET array extract the values and query the database

This works fine if both fields are complete, but if they only wanted to search by location and leave the rent field blank it doesn't work and displays results.php?loc=york&rent= in the URL, which then as I have used the

AND
function displays no results?

I'm very new to PHP and would very much appreciate anyone who can point me in the right direction or what the correct term to search in google for?

<?php
$location = $_GET['loc'];
$rent=$_GET['rent'];

$result = $mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city &&'$rent'>rent_price ORDER BY ID ASC");

?>

Answer

You can either create 2 queries, or just one with some variables.

$rent = $_GET['rent'];
$rent_options = "";
if(isset($rent)) //add condition
 {
      $rent_options .= "&& \'rent\'>rent_price";
 }
$mysqli->query("SELECT * FROM dbc_posts WHERE '$location'=city".$rent_options." ORDER BY ID ASC"); 

This way, assuming they chose a rent option, it will be added to the query. If not, it will simply be blank space and be ignored.

Comments