Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put a limit on a while mysql_array?

Tags:

arrays

php

mysql

//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?

like image 293
Callum Johnson Avatar asked Mar 01 '26 15:03

Callum Johnson


1 Answers

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);
like image 132
Pekka Avatar answered Mar 04 '26 06:03

Pekka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!