0

I am trying to do something that I thought would be very simple but it's driving me crazy.

I have the following data:

ID     ---    Name
1      ---    Joe
2      ---    Bob 
3      ---    Jim
4      ---    Mike

I want to be able to show the results of this from MYSQL as:

"Joe", "Bob", "Jim", "Mike"

I tried CONCATENATE tutorials, but they all seem to be for merging like ID's.

$sql = "SELECT names, CONCAT_WS('', 'names') as namelist FROM peoplenames";

$result = $conn->query($sql);

echo $row["namelist"];

if ($result->num_rows > 0) {

    // output data of each row
    while($row = $result->fetch_assoc()) {

        $names = $row["nameslist"];
        echo $names;
    }
} 

If I echo outside the loop I only get the most recent result.

Any ideas?

Gary
  • 13,303
  • 18
  • 49
  • 71
Ryan Webb
  • 5
  • 3

2 Answers2

0

Change your query to SELECT names FROM peoplenames and use PHP concat for a string:

$names = "";

while($row = $result->fetch_assoc()) {
  $names .= '"' . $row["names"] . '",';
}

echo $names;
Rob
  • 1,840
  • 2
  • 12
  • 19
  • I am trying to take this result and put it into an array. When I use PHP to add the separator I only get one name to show. IE it shows "Joe", and not "Joe", "Bob", "Jim", "Mike" – Ryan Webb Jul 21 '15 at 20:39
  • Did you try the solution I provided? Note that the loop concats the names and then the names are echoed OUTSIDE of the loop. – Rob Jul 21 '15 at 20:41
  • Sorry Rob, your solution looks like it should work. This was my fault, it looked like something I had been working on earlier, but your code is more solid. Only problem I have now is getting the quotes to show correctly. IE it shows Joe, Bob instead of "Joe", "Bob" – Ryan Webb Jul 21 '15 at 20:48
  • Updated my answer. You need to manually concat the string with the quotes. – Rob Jul 21 '15 at 20:56
0

The problem is that you are overwriting the contents of $names each time round the loop.

Change your code like this

$sql = "SELECT names FROM peoplenames";

$result = $conn->query($sql);

$names = NULL;

if ($result->num_rows > 0) {

    while($row = $result->fetch_assoc()) {
        $names .= sprintf('"%s",',$row['names']);
    }
    // output amalgamated date
    rtrim($names, ',');
    echo $names;
} 
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149