0

我有一个数据库,每次有人下载文件时都会存储信息。每次下载文件(根据客户要求)时,它都会捕获名称电子邮件和日期戳。

我希望能够连接到数据库并添加所有重复的条目。因此,如果电子邮件 a@a.com 有 10 个结果,它将打印“a@a.com;10 次下载”。

这是我到目前为止所尝试的。但是它在页面上超时:

function userFile($id) // $id = File ID
 {
    $order = "SELECT * FROM downloads WHERE dl_id='$id'";
    $result = mysql_query($order);
    while($row=mysql_fetch_array($result)){     
        $email = $row['email'];
        $order = "SELECT * FROM downloads WHERE email='$email'";
        $result = mysql_query($order);
        $num_rows = mysql_num_rows($result);
        print $row['email'] . ' ' . $num_rows;
    }
 }

必须有一种更简单或更好的方法来做到这一点。任何帮助表示赞赏!

4

3 回答 3

2
function userFile ($id) // $id = File ID
{
    $order = "SELECT COUNT(*) AS `count`, email FROM downloads WHERE dl_id='$id' GROUP BY email"
    $result = mysql_query($order);
    while($row = mysql_fetch_array($result)) {
        print "{$row['email']}; {$row['count']} downloads.\n"
}
于 2013-04-18T15:09:25.963 回答
1

让 MySQL 为您完成这项工作。如果我正确理解您的要求,您需要这样的查询:

SELECT email, COUNT(*) AS num_rows
FROM downloads
WHERE dl_id='$id'
GROUP BY email

然后您的 PHP 代码将如下所示:

function userFile($id) // $id = File ID
 {
    $order = "SELECT email, COUNT(*) AS `num_rows` FROM downloads WHERE dl_id='$id' GROUP BY email";
    $result = mysql_query($order);
    while($row=mysql_fetch_array($result)){     
        $email = $row['email'];
        $num_rows = $row['num_rows'];
        print $email . ' ' . $num_rows;
    }
 }

我今天没有可用的 PHP,所以请注意这是未经测试的。

于 2013-04-18T15:10:11.337 回答
0

您应GROUP BYCOUNT.

SELECT *,COUNT(1) FROM downloads WHERE `email`='$email' GROUP BY `email`
于 2013-04-18T15:08:24.423 回答