0

I have a database that stores information everytime someone downloads a file. It captures name email and the date stamp everytime they download the file (as requested by client).

I want to be able connect to the database and add up all duplicate entries. So if there are 10 results with the email [email protected] it will print "[email protected]; 10 downloads."

This is what i have tried so far. However it times out on the page:

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;
    }
 }

There has to be an easier or better way of doing this. Any help is appreciated!

1

3 Answers 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"
}
Sign up to request clarification or add additional context in comments.

Comments

1

Have MySQL do the work for you. If I understand your requirements correctly you need a query like this:

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

Then your PHP code would look something like this:

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;
    }
 }

I don't have PHP available here today, so be warned this is untested.

3 Comments

This is exactly what i was looking for! Thank you for the fast reply! Im still fairly new to mysql and havent really learned all there is to it yet! Thanks again!
@EdGibbs I don't know any method to upvote an edit :P But you could upvote my answer (as it is nearly the same as yours, there's no difference, but I'd have then +10 reputation^^)
@bwoebi - done! Thanks again for the assist, and it looks like your edit came through somehow so that's all set too.
0

You shall use GROUP BY within COUNT.

SELECT *,COUNT(1) FROM downloads WHERE `email`='$email' GROUP BY `email`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.