Advertisement
AlexWebDevelop

Untitled

Sep 4th, 2019
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.42 KB | None | 0 0
  1. <?php
  2.  
  3. /* PDO database connection here */
  4. //$pdo = ...
  5.  
  6. $query = 'SELECT * FROM table';
  7. $params = array();
  8. $paramsCount = 0;
  9.  
  10. if (isset($_GET['location']))
  11. {
  12.     /*  Important: you must also check whether $_GET['location'] is valid before using it.
  13.         For example, check its length, its chars, etc. */
  14.    
  15.     if ($paramsCount == 0)
  16.     {
  17.         $query .= ' WHERE';
  18.     }
  19.     else
  20.     {
  21.         $query .= ' AND';
  22.     }
  23.    
  24.     $paramsCount++;
  25.     $query .= 'location = :location';
  26.     $params[':location'] = $_GET['location'];
  27. }
  28.  
  29. if (isset($_GET['category']))
  30. {
  31.     /*  Important: you must also check whether $_GET['category'] is valid before using it.
  32.         For example, check its length, its chars, etc. */
  33.    
  34.     if ($paramsCount == 0)
  35.     {
  36.         $query .= ' WHERE';
  37.     }
  38.     else
  39.     {
  40.         $query .= ' AND';
  41.     }
  42.    
  43.     $paramsCount++;
  44.     $query .= 'category = :category';
  45.     $params[':category'] = $_GET['category'];
  46. }
  47.  
  48. if (isset($_GET['subcategory']))
  49. {
  50.     /*  Important: you must also check whether $_GET['subcategory'] is valid before using it.
  51.         For example, check its length, its chars, etc. */
  52.    
  53.     if ($paramsCount == 0)
  54.     {
  55.         $query .= ' WHERE';
  56.     }
  57.     else
  58.     {
  59.         $query .= ' AND';
  60.     }
  61.    
  62.     $paramsCount++;
  63.     $query .= 'subcategory = :subcategory';
  64.     $params[':subcategory'] = $_GET['subcategory'];
  65. }
  66.  
  67. /* Now execute the query. */
  68. try
  69. {
  70.     $res = $pdo->prepare($query);
  71.     $res->execute($params);
  72. }
  73. catch (PDOException $e)
  74. {
  75.     echo 'Query error: ' . $e->getMessage();
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement