Create a dynamic mysql query using php variables

后端 未结 2 960
执笔经年
执笔经年 2020-11-28 08:56

I have an html table that loads everything in a mySQL database table. I have dropdowns that relate to columns of that mySQL table - when the user selects one of the dropdow

相关标签:
2条回答
  • 2020-11-28 09:23

    Just check if the variables contain a value and if they do, build the query like so:

    unset($sql);
    
    if ($stationFilter) {
        $sql[] = " STATION_NETWORK = '$stationFilter' ";
    }
    if ($verticalFilter) {
        $sql[] = " VERTICAL = '$verticalFilter' ";
    }
    
    $query = "SELECT * FROM $tableName";
    
    if (!empty($sql)) {
        $query .= ' WHERE ' . implode(' AND ', $sql);
    }
    
    echo $query;
    // mysql_query($query);
    
    0 讨论(0)
  • 2020-11-28 09:24
    $filter = array();
    
    if ($_GET['station'] != '')
    { $filter[] = 'STATION_NETWORK = '.$_GET['station'];}
    if ($_GET['vertical'] != '')
    { $filter[] = 'VERTICAL = '.$_GET['vertical'];}
    if ($_GET['creative'] != '')
    { $filter[] = 'CREATIVE  = '.$_GET['creative'];}
    if ($_GET['week'] != '')
    { $filter[] = 'WK = '.$_GET['week'];}
    
    $query = 'SELECT * FROM $tableName WHERE '.implode(' AND ', $filter);
    $result = mysql_query($query);
    ... 
    

    but better if in GET you pushed name of tables rows; $_GET['STATION_NETWORK'] --- some like this;

    then you make
    foreach ($_GET as $key => $value)
    {
        if ($value != '')
        { $filter[] = $key.' = '.$value;}
    }
    

    or try

    $filter = array('STANTION_NETWORK' => $_GET['station'],
                    'VERTICAL' => $_GET['vertical'],
                     'CREATIVE'  => $_GET['creative'],
                     'WK' => $_GET['week']);
    $query_array = array();
    
     foreach ($filter as $key => $value)
    {
        if ($value != '')
        { $query_array[] = $key.' = '.$value;}
    }
    $query = 'SELECT * FROM $tableName WHERE '.implode(' AND ', $query_array);
    $result = mysql_query($query);
    
    0 讨论(0)
提交回复
热议问题