Reputation: 991
I'm trying to list data from my database, and I need to use variables inside of my array, but when echoing it I want it to remove the last comma but it doesn't seem to work.
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = '1'");
while($forum_usersonline_fetch = $forum_usersonline->fetch_array()) {
$usersonlineuname = $forum_usersonline_fetch["user_name"];
$onlinelist = array($usersonlineuname, ' ');
echo implode($onlinelist, ',');
}
It always returns with user1, user2,
so how should I do it?
Upvotes: 1
Views: 2331
Reputation: 12132
The problem is you're doing the implode
inside the while
loop, it should be done outside after building your final array. This is what I would do:
$forum_usersonline = $kunaiDB->query("SELECT * FROM users WHERE user_loggedin = 1");
while ($row = $forum_usersonline->fetch_array()) {
$onlinelist[] = $row["user_name"];
}
echo implode($onlinelist, ",");
However, this should not be the case as you should be using CONCAT
when doing your database query.
Upvotes: 0
Reputation: 16772
You could use chop();
which removes characters from the right end of a string.
An example:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo chop($str,",");
?>
Or you could use rtrim();
like:
<?php
$str = "Random String Ending With,";
echo $str . "<br>";
echo rtrim($str,',');
?>
Or you could also use substr
like:
<?php
$str = "Random String Ending With,";
echo substr($str,0,-1)."<br>";
?>
Upvotes: 1
Reputation: 907
Your can do this job easily in sql. If your database is mysql try following
SELECT GROUP_CONCAT(user_name) as user_name FROM users WHERE user_loggedin = '1'
or if your database is postgres try following
SELECT string_agg(user_name, ',') as user_name FROM users WHERE user_loggedin = '1'
above query result return comma separated user_name.
Upvotes: 1
Reputation: 2525
use rtrim(string,',')
For reference goto http://www.w3schools.com/php/func_string_rtrim.asp
Upvotes: 0