我在 Mysql 中只得到一个值

I only get one value in Mysql

我正在制作一个小型浏览器游戏,我有一个存储用户高分的数据库。 here an image of the database (name is the username and M1_CPM the score)

使用以下代码,我试图获取前 10 个值,以便稍后在排行榜上显示它们:

$sql = "SELECT * FROM leaderboard ORDER BY M1_CPM DESC LIMIT 10";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
    exit();
}
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
echo implode(",", mysqli_fetch_assoc($resultData));

问题是总是只回显最高分而不回显前十名。为什么?

mysql_fetch_assoc()函数returns只从记录集中提取一行作为关联数组。要检索所有行,请使用 while 循环:

while($row = mysqli_fetch_assoc($resultData))
{
   echo implode(",", $row);
}

Note: After the data is retrieved, this function moves to the next row in the recordset. Each subsequent call to mysql_fetch_assoc() returns the next row in the recordset.

每次访问mysqli_fetch_assoc($result)时,指针移动到下一条记录。最后当没有找到记录时,它 returns null 打破了 while 条件。
所以你需要先用 while 获取数据,然后使用 implode,像这样

$rows = [];
while ($row = mysqli_fetch_assoc($resultData)) {
    $rows[] = $row;
}

然后就可以使用implode,这样你的代码就会变成这样

$sql = "SELECT * FROM leaderboard ORDER BY M1_CPM DESC LIMIT 10";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
    exit();
}
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);

$rows = [];
while ($row = mysqli_fetch_assoc($resultData)) {
    $rows[] = $row;
}

echo implode(",", $rows);