-5

I am sending multiple values from form via post. If value not chose on the form, POST will be empy value ('$_POST['']'). If is empty then value must show all records. Is there a better way to write this:

$oglas= mysql_query("SELECT id, user_name, tip_ponude, tip_objekta, vrsta_nekretnine, grad, opstina, naselje, cena, kvadrat, broj_soba, tekst, aktivan FROM `oglas` WHERE 1=1 AND

( tip_ponude = '$_POST[tip_ponuda]' ) AND 

( case when '$_POST[objekat]'     is  NULL or '$_POST[objekat]' != '' then  tip_objekta = '$_POST[objekat]' end ) AND 

( case when '$_POST[us_states]'   is  not NULL or '$_POST[us_states]' != '' then 1=1  else grad = '$_POST[us_states]' end ) AND 

(  case when '$_POST[city_names]' is NULL or '$_POST[city_names]' = '' then 1=1 else  opstina = '$_POST[city_names]' end ) AND 

( case when '$_POST[naselje]'     is NULL or '$_POST[naselje]' = '' then 1=1 else naselje = '$_POST[naselje]' end ) AND

( case when '$_POST[cena]'  is NULL or '$_POST[cena]' = '0' or '$_POST[cena]' = '' then 1=1 else cena <= '$_POST[cena]' end ) AND 

( case when '$_POST[kvadratura]'  is NULL or '$_POST[kvadratura]' = '0' or '$_POST[kvadratura]' = '' then 1=1 else kvadrat <= '$_POST[kvadratura]' end ) AND 

( case when '$_POST[broj_soba]'    is NULL or '$_POST[broj_soba]' = '' then 1=1 else broj_soba = '$_POST[broj_soba]' end ) ") or  die(mysql_error());

Thanks

Nirnae
  • 1,315
  • 11
  • 23
  • 9
    CAPS is considered as shouting. Please remove them from your title, grazie! We can read quite fine ;-) – Funk Forty Niner Feb 03 '16 at 14:27
  • 2
    Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Feb 03 '16 at 14:30

1 Answers1

0

I would first validate the post using php and using implode insert it to the query.

For example

$whereArry = array();    
if(!empty($_POST['objekat']){
   $whereArry[] = " objekat = " . $_POST['objekat'];
}

After all variables have been set.

$where = implode(" AND ", $array);
$sql = "SELECT ...... FROM .... WHERE {$where} ";
Roninio
  • 1,761
  • 1
  • 17
  • 24