I currently have the following query:
SELECT group_concat(DISTINCT usrFirst, usrLast) as receiver_name //etc
When using PHP, it outputs my list of names as follows:
<?php
echo $row['receiver_name'];
//Outputs: JohnDoe,BillSmith,DaveJones
//Desired output: John Doe, Bill Smith, and Dave Jones
I need help figuring out three things:
-
How can I put a space between the first and last name?
-
How can insert a space after each comma?
-
How can I add an ‘and’ right before the last name displayed?
I’m not sure you should bully MySQL into doing exactly what you want there. I’d suggest using the following:
Then loop through this resultset in PHP and handle the case of ‘ and ‘ there.
If performance is a concern (you’ll be doing this query often). You would benefit from not using DISTINCT on the calculated value of CONCAT(first, ‘ ‘, last) as that would require the use of a temporary table.
To tweak it, add the following index:
And change your query as follows:
You’ll be able to get your values directly from the index without resorting to a temporary table or filesort.
As far as the loop goes, something like the following would work:
Note This code assumes you would always have at least 2 rows returned. I’m sure you can figure out how to handle the case of only a single name returned. 🙂