// How to make this request as safe and simple as possible using PDO

$var=""; $var1=0; if(isset($_GET['priceFrom'])){ $var = " `pris` > ". $_GET['priceFrom']; $var1=1; } if(isset($_GET['priceUpTo'])){ if($var1==1){ $var1 = $var1 . " AND `pris` < " . $_GET['priceUpTo']; }else{ $var = " `pris` > ". $_GET['priceUpTo']; } mysql_query("SELECT * FROM object WHERE $var "); 
  • Functions mysql_* date !!! In php 7, they are no longer there. If you use them, and even SO !!! as in your question, with your base any student can do anything. - Visman
  • Well, I myself still a schoolboy) And what do you suggest? - There are no stupid questions.
  • Prepared expressions and PDO phpfaq.ru/pdo#prepared IMPORTANT: Prepared expressions are the main reason to use PDO, since this is the only safe way to execute SQL queries involving variables. - Visman
  • Thanks, it is useful to change the question now. - There are no stupid questions
  • Given what Visman said, build your query in chunks, just like you wrote it. adding to the variable part of the request, only in the form поле=? and putting the required values ​​into the array of arguments. And yes, in the end, just substitute the collected piece of conditions in the request. Only between the conditions, the gaps would not prevent - Mike

3 answers 3

PDO :: prepare - Prepares a request for execution and returns the object associated with this request.

http://php.net/manual/ru/pdo.prepare.php

    // connected to the database using $ pdo

     $var=''; $var1=0; if(isset($_GET['priceFrom'])){ $var = " pris > ". $_GET['priceFrom']; $var1=1; } if(isset($_GET['priceUpTo'])){ if($var1==1){ $var1 = $var1 . " AND pris < " . $_GET['priceUpTo']; }else{ $var = " pris > ". $_GET['priceUpTo']; } } $priceFrom = ($_GET['priceFrom']); $priceUpTo = ($_GET['priceUpTo']); $sql = $pdo->prepare("SELECT * FROM object WHERE " . $var); $sql->execute(array($priceFrom, $priceUpTo)); var_dump($sql->fetch()); 

      You need to use PDO and bind parameters, like so

       $st = $pdo->prepare('SELECT * FROM `object` WHERE pris > :pris'); $st->bindParam(':pris', $_GET['priceUpTo']); $st->execute(); 

      If a digital parameter is expected, it can be done before the request $_GET['priceUpTo'] = intval($_GET['priceUpTo']);

      • And if there are no parameters for example $ _GET ['priceUpTo', but only $ _GET ['priceFrom']; will work? - No stupid questions
      • Then only type those parameters - gomazafaka
      • You can show in your decision, I do not understand - No stupid questions