Dynamic SQL SELECT Statement with PHP based on user options

后端 未结 2 873
我在风中等你
我在风中等你 2021-01-01 07:07

First of all I want to mention that I\'ve been trying and searching like crazy to find a solution to this but no luck so far. My issue is the following:

I have a MyS

相关标签:
2条回答
  • 2021-01-01 07:26

    try this:

    <?php
    $location= $_GET['location'];
    $language= $_GET['language'];
    $name= $_GET['name'];
    
    if($location!=""){
        $where[] = " `location` = '".mysql_real_escape_string($location)."'";
    }
    if($language!=""){
        $where[] = " `language` = '".mysql_real_escape_string($language)."'";
    }
    if($name!=""){
        $where[] = " `name` = '".mysql_real_escape_string($name)."'";
    }
    $where_clause = implode(' OR ', $where);
    //same code for the other 2 options
    
    $sql_json = "SELECT * FROM myTable WHERE $where_clause ORDER BY id DESC";
    ?>
    
    0 讨论(0)
  • 2021-01-01 07:26

    You could always just iterate through the $_GET and grab keys with values, so:

    foreach ($_GET as $key=>$val) {
       if ($val != "") {
          $where_args[] = "$key='$val'";
      }
    } 
    $where_clause = implode(' OR ', $where_args);
    

    You'd probably want to do better validation than the above example, though, and you could add select/case statement if you needed to perform checks on particular values...

    0 讨论(0)
提交回复
热议问题