Reputation: 478
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";
Upvotes: 0
Views: 1220
Reputation: 701
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";
Upvotes: 1