How to set restriction on mysql_array?

//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 code above works fine if only one member is connected to the network. The problem is really aesthetic.

If several users are online, the request displays:

Administrator, system,

I was wondering how I would do it like this on the last result (last member online by while () {} clause) Could I remove the comma? Is there a way to limit the while statement to $ numrows-1 or something in that direction? Then repeat the last user without a comma and a space after their name?

+3
source share
3 answers

One elegant way is to use an array of 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);
+5

implode - , , :

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

, implode, - - .

+1
<?php

$i = 0;
while{

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

$i++;
}
0
source

Source: https://habr.com/ru/post/1759858/


All Articles