Mysqli查询使用$ _get,其中缺少值[重复]

This question already has an answer here:

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");

?>
</div>

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.

try this

   <?php

      // you can check for sql injection
      $location = $_GET['loc'];
      $rent=$_GET['rent'];

      // check if $_GET['rent'] is provided and has a value
      if( isset( $_GET['rent'] ) && $_GET['rent'] ) {

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

       // do remaining stuff

      } else { 

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

       // do other stuff

      }



    ?>

If the $rent is empty the you have to check it first before querying to database.

if(!empty($rent))
{
     $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' and rent_price<'$rent' ORDER BY ID ASC");
} else {
     $result = $mysqli->query("SELECT * FROM dbc_posts WHERE city='$location' ORDER BY ID ASC");
}