使用MYSQL从一列连接所有行[重复]

This question already has an answer here:

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?

</div>

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;
} 

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;