Forum Moderators: coopster
$where = array();
//do this for each form field
if ($_POST['field1']!= "")
$where[] = "databaseColumn = '$_POST[field1]'";
...
if ($_POST['fieldN']!= "")
$where[] = "databaseColumn = '$_POST[fieldN]'";
$where_size = count($where);
for ($i = 0;$i < $where_size; $i++)
$q_where .= "$where[$i] OR ";
$q_where = substr($q_where,0,-4); // remove the last " OR ";
$sql = "SELECT [columns] FROM [table] WHERE $q_where ORDER BY [columnName] LIMIT [number]";
the query is quite ok if people only select one category, but they are allowed to search multiple. If they specify an operator and a language and one category, only rows containing the specified language and operator will be returned. If they specify more then one category, they query fails. Well it doesnt fail, but it returns rows with languages other then the ones specified. I can see why it fails, but I cant figure out a way to sort it properly.
So, all variables except the catgory_id one are limited to one value, while the category_id may be an array
My code:
$device_id = mysql_real_escape_string($_GET['device_id']);
$operator_id = mysql_real_escape_string($_GET['operator_id']);
$country_id = mysql_real_escape_string($_GET['country_id']);
$language_id = mysql_real_escape_string($_GET['language_id']);
$category_id = $_GET['category_id'];
//$cats_arr_asigned = split(",", $row['categories']);
$nr_categories_get = count($_GET['category_id']);
if (!empty($device_id)){
if (!empty($operator_id)){
$query_part2 = " AND files.operator = '$operator_id'";
}
if (!empty($country_id)){
$query_part3 = " AND files.country = '$country_id'";
}
if (!empty($language_id)){
$query_part4 = " AND files.language = '$language_id'";
}
if (!empty($category_id)){
for($i=0; $i<$nr_categories_get; $i++){
$category_id_new = mysql_real_escape_string($category_id[$i]);
if ($i==0){$start = ' AND';}else{$start = ' OR';}
$query_part_tmp .= $start;
$query_part_tmp .= " FIND_IN_SET('$category_id_new', files.categories)";
}
$query_part5 = $query_part_tmp;
}
@mysql_select_db('db');
$query = 'SELECT * FROM files'.
" WHERE device_id = '$device_id' $query_part2 $query_part3 $query_part4 $query_part5 ORDER BY files.filename";
I know the error lies here:
if ($i==0){$start = ' AND';}else{$start = ' OR';}
but I dont know how to fix it, so any help would be appreciated