在 PHP 中构建动态 sql 语句

Building dynamic sql statement in PHP

我有那部分代码,想构建一个动态的 SQL 语句:

//Build IN Clause
$sql_IN="'".implode("','", $keywords)."'";

//Build COUNT Clause
//tbd

//Get Clicks from YOURLS LOG
$sql_get_clicks="
                    SELECT 
                        count(case when shorturl ='u0lg' then 1 end) u0lg, 
                        count(case when shorturl ='3a8h' then 1 end) 3a8h,  
                        count(case when shorturl ='abcd' then 1 end) abcd,  
                        DATE_FORMAT((click_time),'%d.%m.%Y') Datum
                    FROM 
                        `yourls_log` 
                    WHERE  
                         DATE(click_time) BETWEEN '20170102' AND '20170104' AND
                         shorturl IN (".$sql_IN.")
                    Group By Datum";

变量$keywords是一个带有关键字的数组。关键字在 IN 子句中使用,也必须在 "count case part" 中使用。 $keywords 数组中关键字的数量是可变的。有什么技巧可以让我以简单而良好的编程风格构建 count(case.. 吗?

您可以迭代 $keywords 数组并将每个值放入您在 SELECT 之后和 FROM 之前附加的子句等

$keywords = array("foo", "bar", "baz");
$inClause = "'".implode("','", $keywords)."'";
$sql = "SELECT ";
foreach($keywords as $key) {
  $sql.="count(case when shorturl = '".$key."' then 1 end) ".$key.", ";    
}
$sql=rtrim($sql, ", ")." ";
$sql.= "FROM `your_logs` 
  WHERE 
    DATE(click_time) BETWEEN '20170102' AND '20170104' AND
    shorturl IN (".$inClause.")
    Group By Datum";

其中 var_dump($sql); 给出:

string(301) "SELECT count(case when shorturl = 'foo' then 1 end) foo, count(case when shorturl = 'bar' then 1 end) bar, count(case when shorturl = 'baz' then 1 end) baz, FROM your_logs WHERE DATE(click_time) BETWEEN '20170102' AND '20170104' AND shorturl IN ('foo','bar','baz') Group By Datum"

问候编程风格 - 你绝对应该看看 prepared statements