Create a dynamic mysql query using php variables

后端 未结 2 976
执笔经年
执笔经年 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: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);
    

提交回复
热议问题