Jump to content

Recommended Posts

hi, i have a database that stores views to a user's profile. Is there a script i could use to sort the views and tell what number the user ranks in page views?

 

example:

user 1 (200 views)

user 2 (400 views)

user 3 (20 views)

user 4 (1000 views)

 

How can I tell where user 2 ranks with php? In this case it would be second..

 

Thanks for any help.

 

oh i see, individually. i dont know of a query that would do this alone, but you could try this:

 

// select all records' usernames
$result = mysql_query("SELECT `username` FROM `profiles` ORDER BY `page_views` DESC;");

// store in an assoc array (named array)
$array = mysql_fetch_array($result, MYSQL_ASSOC);

// set starting rank
$i=1;

// loop through each row and find a username that matches, since its ordered from the query we can just increment the rank by 1 each time.
foreach($array As $row){
      if($row['username'] == $username){ // if username matches return $i ($i = rank)
          return $i;
      }
      $i++; // increment the rank
}

 

 

this is the best i can come up with, hope this helps,

try this, has worked for me in the past

<?php
$user = USERNAME; //enter the username or however you want to do it
$rank = 0;
$result = mysql_query("SELECT * FROM users ORDER BY page_views DESC");
while($row = mysql_fetch_array($result)) {
  $rank++;
  if ($row['user'] == "$user"){
    echo "$user you are ranked: $rank";
    break;
  }
}
?>

 

don't know if you understand the code or not but i'll explain a little anyway.

 

$user is the user it is looking for this could be anything.. $_SESSION['username'] if you wanted.

then it goes and sets the $rank. 0 first.

does the mysql query listing the rows in page_views order. so it would go in the order.. user4, user2, user1, user3.

it proceedes to go through the mysql rows until it makes a match to whatever was stated in $user adding 1 to the $rank each time it starts again. once it matches the $row['user'] to $user it will output the echo statement

 

$user you are ranked: $rank

 

and then break.

hope this helps

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.