mysql查询中的php循环

时间:2011-07-14 06:33:50

标签: php mysql html

我有一个像这样的大型mysql查询:

SELECT u.userid AS `User`
  , SUM(CASE WHEN activitydate='2011-07-01' THEN round(time/60) ELSE 0 END) AS `2011-07-01`
  , SUM(CASE WHEN activitydate='2011-07-02' THEN round(time/60) ELSE 0 END) AS `2011-07-02`
.......
  , SUM(CASE WHEN activitydate='2011-07-30' THEN round(time/60) ELSE 0 END) AS `2011-07-30`
FROM hoursbase h
  JOIN person u
    ON h.userid = u.id
WHERE h.activitydate BETWEEN '2011-07-01' AND '2011-07-30'
GROUP BY h.userid
ORDER BY h.userid

有什么方法可以使用php在循环中放置查询。

此外,我尝试添加一个下拉菜单,在选择时,相应的月份将在查询中更新。

的问候,
Chandru。

1 个答案:

答案 0 :(得分:3)

如果您不介意查询具有不同的输出格式,您可以像这样重写它:

SELECT u.userid AS `User`
   ,activitydate
   ,sum(round(ifnull(time,0)/60)) as timetaken
FROM hoursbase h
JOIN person u ON h.userid = u.id 
WHERE h.activitydate BETWEEN :startdate AND :enddate  /*note the : params*/ 
GROUP BY h.userid, h.activitydate 
ORDER BY h.userid, h.activitydate

这将首先返回按userid分组的数据,然后按activitydate分组 它还会更快地运行批次 最后,在php中获取每个用户每个日期的结果会更容易 当你改变月份时,你不必改变列数。

以下是如何使用循环在php中循环它:
我已经复制了这个答案中的代码:How do I loop through a MySQL query via PDO in PHP?

// $attrs is optional, this demonstrates using persistent connections, 
// the equivalent of mysql_pconnect 
$attrs = array(PDO::ATTR_PERSISTENT => true);  

// connect to PDO 
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "password", $attrs);
// the following tells PDO we want it to throw Exceptions for every error. 
// this is far more useful than the default mode of throwing php errors 
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
// prepare the statement. the place holders allow PDO to handle substituting 
// the values, which also prevents SQL injection 
$stmt = $pdo->prepare("SELECT u.userid AS `User`.....  ");  
// bind the parameters 
$stmt->bindValue(":startdate", "2011-07-01"); 
$stmt->bindValue(":enddate", "2011-07-31");  
// initialise an array for the results  
$products = array(); 
if ($stmt->execute()) {   
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {      
    //do more useful stuff here
    //escape all fields that can be entered by users using htmlspecialchars
    //to prevent XSS exploits.
    echo htmlspecialchars($row['User']);
    echo htmlspecialchars($row['activitydate']);
    echo $row['timetaken'];
  } 
}  
// set PDO to null in order to close the connection 
$pdo = null; 

关于htmlspecialchars()
您需要转义用户可以输入并输出到屏幕的所有字符串字段 在这种情况下,我转发useridactivitydate,因为我只有95%确定这些是整数和日期字段,如果我100%肯定,我会跳过逃避,但如果我不是我必须逃脱。

<强>链接:
How to escape output in PHP
How do I loop through a MySQL query via PDO in PHP?