Common approach is to create an array that will contain different query parts and just add elements to them, depending on what you need to filter. For example:
<?php
$sql_parts = array(
'select' => array(),
'from' => array(),
'where' => array()
);
if ($filter_by_name != ''){
$sql_parts['select'][] = 'u.*';
$sql_parts['from'][] = 'users AS u';
$sql_parts['where'][] = "u.name = '".mysql_real_escape_string($filter_by_name)."'";
}
if ($filter_by_surname != ''){
$sql_parts['select'][] = 'u.*';
$sql_parts['from'][] = 'users AS u';
$sql_parts['where'][] = "u.surname = '".mysql_real_escape_string($filter_by_surname)."'";
}
//filter by data from another table
if ($filter_by_city_name != ''){
$sql_parts['select'][] = 'u.*, c.*';
$sql_parts['from'][] = 'cities AS c';
$sql_parts['from'][] = 'users AS u';
$sql_parts['where'][] = "c.cityname = '".mysql_real_escape_string($filter_by_city_name)."'";
$sql_parts['where'][] = "c.id = u.cityid";
}
$sql_parts['select'] = array_unique($sql_parts['select']);
$sql_parts['from'] = array_unique($sql_parts['from']);
$sql_parts['where'] = array_unique($sql_parts['where']);
$sql_query = "SELECT ".implode(", ", $sql_parts['select']).
"FROM ".implode(", ", $sql_parts['from']).
"WHERE ".implode(" AND ", $sql_parts['where']);
?>