Jump to content

Recommended Posts

I want to display member's names, each separated by a comma, but have no comma after the last one. I'm using mysql to store them. This is an example of what I have:

 

<?php

$query = "SELECT * FROM members";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo $row["username"] . ", ";
}

?>

 

What I want the above script to output is..."james, bob, dave, elisha, and maureen", but it only outputs, "james, bob, dave, elisha, maureen, "

There's an extra comma and space after the last name with using the above script, so...how do I get that "and" in there and make sure there's no comma after the last name to be displayed? I've tried everything I can think of, but to no avail. Anyone?

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/
Share on other sites

It's much easier to do as Pikachu suggested:

<?php
$tmp = array();
$query = "SELECT username FROM members";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $tmp[] = $row["username"];
}
echo implode(', ',$tmp);
?>

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226226
Share on other sites

It's much easier to do as Pikachu suggested:

<?php
$tmp = array();
$query = "SELECT username FROM members";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $tmp[] = $row["username"];
}
echo implode(', ',$tmp);
?>

 

Ken

 

Will try this thanks!

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226234
Share on other sites

You should have tested it; it won't work.

 

Okay, what you suggested works, but can you explain what's going on here? I'm not too familiar with implode and have no idea what the code does. I noticed the array $tmp gets carried outside of the while loop and the while loop constructs the array, but how is the comma getting excluded from the last name and how could i place an "and" in there?

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226235
Share on other sites

Here's the code right now. Sorry if it seems a it complicated to read.

 

<?php
		$find_members_online_q = "SELECT * FROM fans WHERE status = 'Online'";
		$find_members_online_r = mysql_query($find_members_online_q);
		$find_members_online_c = mysql_num_rows($find_members_online_r);
		echo "<strong>" . $find_members_online_c . " members</strong> are online<br><br>";
		while ($find_members_online_ro = mysql_fetch_array($find_members_online_r)) {
			$tmp[] = $find_members_online_ro["username"];
		}
		echo "<a href='../profile.php?action=view&username=" . implode (", ", $tmp) . "' ";
		if ($find_members_online_ro["forum_rank"] == "Site Owner") {
			echo "style='color: #FF0000'";
		}
		echo ">" . implode (", ", $tmp) . "</a>";
		?>

 

One thing about this script is it makes all of the names one big link, but I want each name to be its own link.

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226236
Share on other sites

You should have tested it; it won't work.

 

Okay, what you suggested works, but can you explain what's going on here? I'm not too familiar with implode and have no idea what the code does. I noticed the array $tmp gets carried outside of the while loop and the while loop constructs the array, but how is the comma getting excluded from the last name and how could i place an "and" in there?

 

implode(); takes an array, iterates through each array item and applies the separator in between each array item, once it detects the last array item, it doesn't apply another separator because it's the end of the array.

 

http://php.net/implode

 

Basically does something like this, but you can call the implode() function instead of needing to do this:

$a=array("a","b","c","d","e");
for($i=0; $i<=count($a); $i++{
if($i!=$count){
echo $i.",";
}
else{
echo $i;
}
}

 

 

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226242
Share on other sites

Also, since you want to make a comma separated list of links, you would need to form each link inside the while(){} loop when you store each value into the $tmp[] array.

 

The implode() after the end of the while(){} loop would just be the original code that puts the comma between the elements that are in the array.

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226243
Share on other sites

If you want individual links for each username, you need to re-work your code a little to build the link in the while loop & then echo all the links:

<?php
$find_members_online_q = "SELECT username, forum_rank FROM fans WHERE status = 'Online'";
$find_members_online_r = mysql_query($find_members_online_q);
$find_members_online_c = mysql_num_rows($find_members_online_r);
echo "<span style='font-weight:bold'>" . $find_members_online_c . " members</span> are online<br><br>";
$tmp = array();
while ($find_members_online_ro = mysql_fetch_array($find_members_online_r)) {
    $usr = ($find_members_online_ro["forum_rank"] == "Site Owner")?"<span style='color:#FF0000'>{$find_members_online_ro["username"]}</span>":$find_members_online_ro["username"];
    $tmp[] = "<a href='../profile.php?action=view&username={$find_members_online_ro["username"]}'>$usr</a>";
}
echo implode(', ',$tmp);
?>

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226244
Share on other sites

Okay, what you suggested works, but can you explain what's going on here? I'm not too familiar with implode and have no idea what the code does. I noticed the array $tmp gets carried outside of the while loop and the while loop constructs the array, but how is the comma getting excluded from the last name and how could i place an "and" in there?

 

You know there is a manual for php, right? Having us explain a function to you which has clear documentation with examples and user comments is a useless activity. Now, if you were to have read the manual and still have questions, then by allmeans ask.

 

http://us2.php.net/manual/en/function.implode.php

 

 

Try this code

<?php
    //Create and run query
    $query  = "SELECT * FROM fans WHERE status = 'Online'";
   $result = mysql_query($find_members_online_q);

   //Process results
   $memberAry = array();
   $baseURL = "../profile.php?action=view&username=";
   $memberCount = mysql_num_rows($result);
   while ($row = mysql_fetch_array($result))
    {
        $style = ($row['forum_rank'] == 'Site Owner') ? " style='color: #FF0000'" :'' ;
        $urlUname = urlencode($row['username']);
       $memberAry[] = "<a href='{$baseURL}{$urlUname}'{$style}>{$row['username']}</a>";
    }

    //Output results
   echo "<strong>{$memberCount} members</strong> are online<br><br>\n";
    echo implode (", ", $memberAry);
?>

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226246
Share on other sites

Okay, what you suggested works, but can you explain what's going on here? I'm not too familiar with implode and have no idea what the code does. I noticed the array $tmp gets carried outside of the while loop and the while loop constructs the array, but how is the comma getting excluded from the last name and how could i place an "and" in there?

 

You know there is a manual for php, right? Having us explain a function to you which has clear documentation with examples and user comments is a useless activity. Now, if you were to have read the manual and still have questions, then by allmeans ask.

 

http://us2.php.net/manual/en/function.implode.php

 

 

Try this code

<?php
    //Create and run query
    $query  = "SELECT * FROM fans WHERE status = 'Online'";
   $result = mysql_query($find_members_online_q);

   //Process results
   $memberAry = array();
   $baseURL = "../profile.php?action=view&username=";
   $memberCount = mysql_num_rows($result);
   while ($row = mysql_fetch_array($result))
    {
        $style = ($row['forum_rank'] == 'Site Owner') ? " style='color: #FF0000'" :'' ;
        $urlUname = urlencode($row['username']);
       $memberAry[] = "<a href='{$baseURL}{$urlUname}'{$style}>{$row['username']}</a>";
    }

    //Output results
   echo "<strong>{$memberCount} members</strong> are online<br><br>\n";
    echo implode (", ", $memberAry);
?>

 

I was incidentally reading about both explode and implode before I came across this problem today, actually, and I'm posting about it, because I didn't know you could use implode for this type of thing. I was fully aware what implode did before coming to this forum and posting about this, but the way in which it is used here confused me, hence why I asked.

 

Still have a problem though if anyone can help. I want to put an "and" before the last name and after the last comma. how do i do that?

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226250
Share on other sites

I want to put an "and"...

 

^^^ You cannot sneak up on programming because computers only do exactly what their code and data tells them to do. To the best of your ability, you must know and list everything you want to accomplish before you write any code. Otherwise you will be spend a fortune in time going back and redoing code to match the changing requirements.

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226253
Share on other sites

Using the code I posted previously, I would change the following section as shown

    //Output results
    echo "<strong>{$memberCount} members</strong> are online<br><br>\n";
    $lastRecord = array_pop($memberAry);
    echo implode (", ", $memberAry) . "and {$lastRecord}";

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226256
Share on other sites

Using the code I posted previously, I would change the following section as shown

    //Output results
    echo "<strong>{$memberCount} members</strong> are online<br><br>\n";
    $lastRecord = array_pop($memberAry);
    echo implode (", ", $memberAry) . "and {$lastRecord}";

 

I managed to combine everyones script with mine to form this:

<?php
		$find_members_online_q = "SELECT username, forum_rank FROM fans WHERE status = 'Online'";
		$find_members_online_r = mysql_query($find_members_online_q);
		$find_members_online_c = mysql_num_rows($find_members_online_r);
		echo "<span style='font-weight:bold'>" . $find_members_online_c . " members</span> are online<br><br>";
		$tmp = array();
		while ($find_members_online_ro = mysql_fetch_array($find_members_online_r)) {
			$user = ($find_members_online_ro["forum_rank"] == "Site Owner")?"<span style='color:#FF0000'>{$find_members_online_ro["username"]}</span>":$find_members_online_ro["username"];
			$tmp[] = "<a href='../profile.php?action=view&username=" . $find_members_online_ro["username"] . "'>$user</a>";
		}
		$last_element = array_pop ($tmp);
		echo implode(', ', $tmp);
		echo ", and " . $last_element;			
?>

 

This does PRECISELY what I need. Thanks for all the effort everyone, much appreciated =)

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226261
Share on other sites

I have one last question, though, because this is bugging the hell out of me and I won't rest in peace tonight if I don't ask. What's this line?

 

 

<?php

$user = ($find_members_online_ro["forum_rank"] == "Site Owner")?"<span style='color:#FF0000'>{$find_members_online_ro["username"]}</span>":$find_members_online_ro["username"];

?>

 

I've never seen a variable declared like this. $ = ()?:

 

Is this a fancy, alternative way of declaring a variable?

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226262
Share on other sites

That's called ternary syntax, it's essentially a shorthand for an if/else structure.

 

This

$variable = !empty($_POST['field']) ? $_POST['field'] : 'Empty';

 

Does the same as this

if( !empty($_POST['field']) ) {
     $variable = $_POST['field'];
} else {
     $variable = 'Empty';
}

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226267
Share on other sites

That's called ternary syntax, it's essentially a shorthand for an if/else structure.

 

This

$variable = !empty($_POST['field']) ? $_POST['field'] : 'Empty';

 

Does the same as this

if( !empty($_POST['field']) ) {
     $variable = $_POST['field'];
} else {
     $variable = 'Empty';
}

 

Which would you recommend I use? I personally would prefer doing it the classic if/else way...is there a difference?

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226269
Share on other sites

It depends what I'm doing. I prefer the ternary if I'm in the middle of a display block and need to check if a value is present before echoing it, mainly because it allows everything to stay formatted properly and on one line. There are a few other places I use it, but that's the main one.

 

<input type="text" name="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>" id="email">

Link to comment
https://forums.phpfreaks.com/topic/238611-commas/#findComment-1226271
Share on other sites

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.