Jump to content

count how many times the same username is in the database


CBG

Recommended Posts

Hi,

 

I currently have the below code.

 

$query = "select * from db WHERE username LIKE '$username'";
$result = mysql_query($query);
while ($r = mysql_fetch_array($result)) {
$user = $r["username"];
$user_seen = $r["username_seen"];
}

 

Now what I would like to do is count and return the number how many times the same username is in the database, as well as return username

 

How would I do this with the above code?

Use a SELECT COUNT() query when you want to do something like this.

 

$query = "SELECT COUNT(*) AS num FROM db WHERE username = '$username'";
$result = mysql_query($query);

$numberOfUsernames = mysql_result($result, 0, 0);

// or

list($numberOfUsernames) = mysql_fetch_row($result);

 

You alreay have the username in $username

 

Huh? Why would it only return 1 row? There's no limit on the query. It will return all rows that have the username supplied, then mysql_num_rows will give the number of records returned. I've just tried this locally too and it's fine

I would have assumed that since I said "instead" the OP would realise he should keep his original query since trying to get the number twice would be pretty stupid

 

You didn't mention the word 'instead' (not that that would have made your post any clearer) anywhere in your post, nor did you bother to read mine obviously.

Well theres really no need to be pedantic about it. No I didn't re-read my post. That said, it was still pretty obvious that I meant use that instead so I've copied and pasted the two words that define it just in case you need the exact words

"just use"

better?

Use a SELECT COUNT() query when you want to do something like this.

 

$query = "SELECT COUNT(*) AS num FROM db WHERE username = '$username'";
$result = mysql_query($query);

$numberOfUsernames = mysql_result($result, 0, 0);

// or

list($numberOfUsernames) = mysql_fetch_row($result);

 

You alreay have the username in $username

 

 

The while makes me believe he wants to know how many times each username occurs which leads to:

 

SELECT count(*) AS username_count, username
FROM db
GROUP BY username

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.