mysql查询中的php循环
我有一个像这样的大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将上面的查询放入循环中吗?
另外,我尝试添加一个下拉菜单,选择后,相应的月份将在查询中更新。
问候,
钱德鲁。
I have a big mysql query like this:
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
Is there any way that i can put above query in loop using php.
Also i am try to add one drop down menu and on selecting, the respective month will update in query.
Regards,
Chandru.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不介意查询具有不同的输出格式,您可以像这样重写它:
这将首先返回按
userid
分组的数据,然后按activitydate
分组。它还会运行得快得多。
最后,在 php 中获取每个用户每个日期的结果会更容易。
当您更改月份时,您不必更改列数。
以下是如何在 php 中使用循环来循环它:
我从这个答案复制了代码: 如何在 PHP 中通过 PDO 循环执行 MySQL 查询?
关于
htmlspecialchars()
您需要转义用户可以输入并输出到屏幕的所有字符串字段。
在这种情况下,我转义了
userid
和activitydate
因为我只有 95% 确定这些是整数和日期字段,如果我 100% 确定,我会跳过转义,但是如果我不是,我就必须逃跑。链接:
如何转义 PHP 中的输出
如何循环执行 MySQL 查询通过 PHP 中的 PDO?
If you don't mind the query having a different output format you can rewrite it like so:
This will return your data grouped by
userid
first and then byactivitydate
.It will also run a lot faster.
Finally it will be easier to get the results per user per date in php.
And when you change months you don't have to change the number of columns.
Here's how to loop through it in php using a loop:
I've copied the code from this answer: How do I loop through a MySQL query via PDO in PHP?
About
htmlspecialchars()
You need to escape all string fields that can be entered by a user and that you output to screen.
In this case I escaped
userid
andactivitydate
because I'm only 95% sure these are integer and date fields, I'd skip escaping if I was 100% sure, but if I'm not I have to escape.Links:
How to escape output in PHP
How do I loop through a MySQL query via PDO in PHP?