tags:

views:

42

answers:

3
//check which faction members are online
$sql = mysql_query("SELECT * FROM ".TBL_ACTIVE_USERS." 
WHERE faction=$userfaction_id ORDER BY timestamp DESC,username");
//no '' around var as it is an integer, so php doesn't expeect it to be string
$numrows = mysql_numrows($sql);//gets number of members online
if($numrows == 1){ echo 'You are the only faction member online'; }
else{
while($online = mysql_fetch_array($sql)){
echo '<a href="#" class="light_grey">'.$online['username'].'</a>';
echo ',&nbsp;';
}//loops round all online users
//echoing their usernames
}

The above code works fine if only one member is online. The problem is really aesthetic reasons.

If more than one member is online, the query displays:

Administrator, System,

I was wondering how I would make it so on the last result (last member online by the while(){} clause) I could remove the comma? Is there a way of limiting the while statement to $numrows-1 or something along those lines? Then echoing the last user without the comma and space after their name?

+5  A: 

One elegant way is to use an array and implode().

$elements = array();

while($online = mysql_fetch_array($sql)){
  array_push ($elements, '<a href="#" class="light_grey">'.
                         $online['username'].'</a>');
}

echo implode(",&nbsp;", $elements);
Pekka
this way works perfectly, but would you say this method is more efficient than reko_t's?
Callum Johnson
@Callum unless you are processing 100000 lines this way, efficiency is really totally negligeable and a question of a few milliseconds. The same applies to high-traffic sites: You are likely to have much bigger bottlenecks than this loop. You can freely choose which method best suits your coding style.
Pekka
oh aha! I don't think it will ever process that many lines ^^Thanks for the reply!
Callum Johnson
A: 
<?php

$i = 0;
while{

    if($i > $numrows)
    {
        echo ',&nbsp;';
    }

$i++;
}
fabrik
+1  A: 

implode is one way to do it, as Pekka showed, one other way is to do it like this:

$first = true;
while($online = mysql_fetch_array($sql)){
  if (!$first) {
      echo ', ';
      $first = false;
  }
  echo '<a href="#" class="light_grey">',$online['username'],'</a>';
}

Should be a bit more efficient than the implode way if there's a lot of online members, due to not having to construct a temporary array.

reko_t
First off, I've chose this way to try as you've stated its the most efficient way, there might be hundreds of users online (probably not, but I always look to improve efficiency).I've tried this way, and the output is: AdministratorSystem .I've just C+P your code into mine, so what could be the issue here?
Callum Johnson
I chose Pekka's way as it seemed simpler. But, thanks for the help though!
Callum Johnson