11

我有一个 html 表,可以加载 mySQL 数据库表中的所有内容。我有与该 mySQL 表的列相关的下拉列表 - 当用户选择其中一个下拉列表时,它使用 AJAX 查询数据库。

我需要弄清楚如何动态构建查询,因为有时下拉列表会是空的(即他们不想按该列进行过滤)。

做这个的最好方式是什么?

目前我有这样的事情:

    $stationFilter = $_GET['station'];
    $verticalFilter = $_GET['vertical'];
    $creativeFilter = $_GET['creative'];
    $weekFilter = $_GET['week'];    
    
    $result = mysql_query("SELECT * FROM tableName WHERE STATION_NETWORK = '$stationFilter' AND VERTICAL = '$verticalFilter' AND CREATIVE = '$creativeFilter'  AND WK = '$weekFilter'");   
    $data = array();
    while ($row = mysql_fetch_row($result) )
        {
        $data[] = $row;
        }   
    $finalarray['rowdata'] = $data;

您可以想象这不起作用,因为如果这些字段中的任何一个为空 - 查询将失败(或不返回任何内容)。

显然,如果某些变量为空,那么创建这样的“静态”查询确实会变得很困难。

动态创建该查询的最佳方法是什么,以便它只输入那些非空的并添加到查询中,以便它可以成功完成并显示适当的数据?

4

2 回答 2

34

只需检查变量是否包含值,如果包含,请像这样构建查询:

$sql = [];
$parameters = [];
    
if ($stationFilter) {
    $sql[] = " STATION_NETWORK = ?";
    $parameters[] = $stationFilter;
}
if ($verticalFilter) {
    $sql[] = " VERTICAL = ?";
    $parameters[] = $verticalFilter;
}

$query = "SELECT * FROM tableName";

if ($sql) {
    $query .= ' WHERE ' . implode(' AND ', $sql);
}
$stmt = $mysqli->prepare($query);

if ($parameters) {
    $stmt->bind_param(str_repeat('s', count($array), ...$parameters);
}
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
于 2013-04-03T17:39:04.607 回答
0
$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);
... 

但如果在 GET 中推送表行的名称会更好;$_GET['STATION_NETWORK'] --- 有些像这样;

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

或尝试

$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);
于 2013-04-03T17:54:54.860 回答