简体   繁体   中英

Use jQuery/Ajax to filter PHP SELECT query with dropdowns

i'm trying to create a filter using jQuery / Ajax and PHP/MySQL.

I have 4 dropdown select in my HTML, i want to achieve something like this:

When Ajax success post data, my PHP file check to see if value is empty or not, so each dropdown will add 'AND' statement to the SELECT query, something like:

SELECT * from properties WHERE property_id = '$property_id' AND dropdown_value = '$dropdown_value' AND dropdown_value2 = '$dropdown_value2'

So i could set all the variables and just check if the posted value is empty or not, so if it is empty, the query statement is not added at all.

Is this possible?

Thanks.

EDIT

Current code:

$statements = array();
if (isset($_POST['segmento'])) {
   $segmento_query = $_POST['segmento'];
   $statements[] = " AND property_details.segmento = '$segmento_query' "; //condition for each property
}
if (isset($_POST['cidade'])) {
   $cidade_query = $_POST['cidade'];
   $statements[] = " AND property_details.cidade = '$cidade_query' ";
}

$filtraSegmento = "SELECT * FROM properties, property_complements, property_details WHERE property_complements.imovel_id = properties.property_id AND property_details.imovel_id = properties.property_id $statements";

Have you tried:

$statements = array();
if (isset($POST['param1']) {
   $param1 = $POST['param1'];
   $statements[] = " property1 = '$param1' "; //condition for each property
}
if (isset($POST['param2']) {
   $param2 = $POST['param2'];
   $statements[] = " property2 = '$param2' ";
}

//.....more.....
$sql = "SELECT * FROM tbl WHERE ". implode('AND', $statements);
//do something here

Edited : use $statements as a string

$statements = '';
if (isset($_POST['segmento'])) {
   $segmento_query = $_POST['segmento'];
   $statements .= " AND property_details.segmento = '$segmento_query' "; //condition for each property
}
if (isset($_POST['cidade'])) {
   $cidade_query = $_POST['cidade'];
   $statements .= " AND property_details.cidade = '$cidade_query' ";
}

$filtraSegmento = "SELECT * FROM properties, property_complements, property_details WHERE property_complements.imovel_id = properties.property_id AND property_details.imovel_id = properties.property_id $statements";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM