PHP group_concat插入分隔符或按结果排序没有数据

时间:2018-03-09 23:12:57

标签: php mysql

我有一个没有分隔符的代码,也没有按此处的代码订购

[1, 1]
[1, 2]
[1, 3]
[1, 4]

导致

__ ANGEL_ 980,979,981,982,983 但如果我更改此代码

[1, 1]
[1, 2]
[1, 3]
[1, 4]
[2, 1]
[2, 2]
[2, 3]
[2, 4]
[3, 1]
[3, 2]
[3, 3]
[3, 4]
[4, 1]
[4, 2]
[4, 3]
[4, 4]

$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query('SELECT PlayerName, GROUP_CONCAT(BallotNumber)
FROM BallotNumbers
GROUP BY PlayerName') as $row) {

echo "<tr>";
echo "<td>" . $row['PlayerName'] . "</td>";
echo "<td>" . $row['GROUP_CONCAT(BallotNumber)'] . "</td>";
echo "</tr>"; 
}
?>
</tbody></table>

我得到表格中没有数据,如果我在页面上添加订单,根本不会访问任何帮助将非常感谢

1 个答案:

答案 0 :(得分:1)

只需使用别名即可获得正确的结果:

$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$result = $dbh->query("SELECT PlayerName, GROUP_CONCAT(BallotNumber SEPARATOR ', ') as bn FROM BallotNumbers GROUP BY PlayerName");
foreach($result as $row) {
    echo "<tr>";
    echo "<td>" . $row['PlayerName'] . "</td>";
    echo "<td>" . $row['bn'] . "</td>";
    echo "</tr>"; 
}
?>
</tbody></table>
来自@apokryfos的

UPD 评论