Kim
Kim

Reputation: 1156

While inside a while

I'm trying to count how many times a hashtag is mentioned in the database. So first while is getting all the hashtags, and the second is inside the other while to count how many times the hashtag is mentioned. But the problem is that the numbers isn't getting along correct, it is just showing 1,2,3,4,5.. etc, and when there is a hashtag mentioned two times it's showing i.e. 3+4.

How can I solve this?

$i = 0;
$popular_hashtags_query = mysql_query("SELECT * FROM " . $dbPrefix . "hashtags WHERE status=1");

while ($popular_hashtags = mysql_fetch_array($popular_hashtags_query)) {
    echo "<div class='hashtag_label'><a data-hover='";
    $count_hashtags_query = mysql_query("SELECT * FROM " . $dbPrefix . "hashtags WHERE status=1 AND hashtag='" . $popular_hashtags['hashtag'] . "'");
    while ($count_hashtags = mysql_fetch_array($count_hashtags_query)) {
        $i++;
        echo $i;
    }
    echo "'><span>#".$popular_hashtags['hashtag'] . "</span></a></div>"; 
}

Upvotes: 1

Views: 89

Answers (3)

Vahid Hallaji
Vahid Hallaji

Reputation: 7447

I suggest to use mysqli or PDO. in this case group by hashtag in the query is better way and not need to extra query and loop so.

$popular_hashtags_query = mysql_query("
    SELECT 
        `hashtag`, count(*) AS `count` 
    FROM `" . $dbPrefix . "hashtags` WHERE `status` = 1 GROUP BY `hashtag`
");

while ($popular_hashtags = mysql_fetch_array($popular_hashtags_query)) {
    echo "<div class='hashtag_label'><a data-hover='";
        echo $popular_hashtags['count'];
    echo "'><span>#" . $popular_hashtags['hashtag'] . "</span></a></div>";
}

Upvotes: 1

rc_luke
rc_luke

Reputation: 111

There's no need to loop over all records in a table to do the same thing again. What you want is to use an aggregate function in you SQL query.

Something like the following:

SELECT hashtag, COUNT(hashtag)
FROM hashtags
GROUP BY hashtag

Upvotes: 0

DiMono
DiMono

Reputation: 3368

There are a bunch of problems with your code. First, the mysql_ functions are deprecated and will eventually be removed from php entirely, so you should move over to mysqli_ functions or a PDO.

Second, your actions on $i are in the wrong place. You should be resetting $i = 0 as the first action inside the first loop, or else it's just going to count up the total number of times ANY hashtag is used.

Third, you're echoing $i inside the second while loop, which means every time the loop runs, you're going to be forever echoing increasing numbers. The echo should be outside the inner loop, after you've counted up the instances of the hashtag.

And finally, you can actually accomplish all of this with one loop by executing "SELECT hashtag, count(*) FROM " . $dbPrefix . "hashtags WHERE status=1 group by hashtag"

Upvotes: 0

Related Questions