首先,您必须确保无法进行SQL注入.为此,我们使用PDO.
接下来,要解决您的实际问题,您只需创建两个带条件的列表.一个具有您希望WHERE
在查询部分中具有的条件,一个具有需要HAVING
在查询部分中进行的条件.
$pdo = new PDO(/* See http://php.net/manual/en/pdo.construct.php */); $whereConditions = []; $havingConditions = []; $parameters = []; if (!empty($last_visit)) { $whereConditions[] = "behaviour.TIMESTAMP >= DATE_SUB( CURDATE( ) , INTERVAL :last_visit DAY) AND behaviour.TIMESTAMP < DATE_ADD( CURDATE( ) , INTERVAL 1 DAY ) "; $parameters['last_visit'] = $last_visit; } if (!empty($from_country)) { $whereConditions[] = "audience.country = :from_country"; $parameters['from_country'] = $from_country; } if (!empty($more_than)) { $havingConditions[] = "COUNT( * ) >= :more_than"; $parameters['more_than'] = $more_than; } if (!empty($time_spent)) { $havingConditions[] = "timeSpent >= :time_spent"; $parameters['time_spent'] = $time_spent; } if (!empty($lead_scoring)) { $havingConditions[] = "new_table.percentile_rank >= :lead_scoring"; $parameters['lead_scoring'] = $lead_scoring; } if (count($vals)) { $escapedUrlList = implode(', ', array_map(function ($url) use ($pdo) { return $pdo->quote($url); }, $vals)); $whereConditions[] = "url IN($escapedUrlList)"; } $whereClause = count($whereConditions) ? ' AND ' . implode(' AND ', $whereConditions) : ''; $havingClause = count($havingConditions) ? ' HAVING ' . implode(' AND ', $havingConditions) : ''; $statement = $pdo->prepare(" SELECT behaviour.hash, Sum(behaviour.timespent) AS timeSpent, new_table.percentile_rank, Count(*) AS total FROM behaviour, audience, new_table WHERE behaviour.hash = audience.hash AND behaviour.hash = new_table.hash {$whereClause} GROUP BY behaviour.hash {$havingClause} "); $result = $statement->execute($parameters);