在PHP中构建动态sql语句

时间:2017-01-04 14:34:54

标签: php mysql yourls

我拥有该部分代码,并希望构建一个动态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子句中使用,也必须在“计数案例部分”中使用。 $ keywords数组中的关键字数量是可变的。有关如何以简单优秀的编程风格构建count(case..的任何提示吗?

1 个答案:

答案 0 :(得分:1)

您可以迭代$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);给出的地方:

  

字符串(301)" SELECT计数(shorturl =' foo'然后1结束时的情况)foo,count(shorturl =' bar'然后1结束时的情况) bar,count(shorturl =' baz'然后1结束时的情况)baz,FROM your_logs     哪里       DATE(click_time)BETWEEN' 20170102' AND' 20170104'和       短暂的IN(' foo',' bar',' baz')       Group By Datum"

关于编程风格 - 你最应该关注prepared statements