MySQLi:在列中选择 5 个最常见的数据并按顺序返回以供显示
MySQLi: Selecting 5 most common data in column & returning in order for display
我正在尝试从名为 users
的 table 中 select 名为 favorite
的栏中的 5 个最常见的单词。我只需要前 5 个,但希望它们按 1 到 5 的顺序 return 进行显示。这些是名称,例如:
user1 Bob Marley
user2 Stan Smiley
user3 Bob Marley
user4 Joe Schmoe
等...
我有以下内容作为开始:
$db_fav_query = mysqli_prepare($con, "SELECT favorite, COUNT(*) AS favCOUNT FROM users GROUP BY favorite ORDER BY favCOUNT DESC LIMIT 5");
$db_fav_query->execute();
$db_fav_result = $db_fav_query->get_result();
$row = $db_fav_result->fetch_assoc();
$fav1 = $row['favorite'];
我正在尝试输出如下:
<tr>
<td><?php echo htmlentities($fav1); ?></td>
<td><?php echo htmlentities($fav2); ?></td>
<td><?php echo htmlentities($fav3); ?></td>
<td><?php echo htmlentities($fav4); ?></td>
<td><?php echo htmlentities($fav5); ?></td>
</tr>
我知道 $fav2
、$fav3
等.. 尚未声明,但我不确定如何从 dB 中获取它们以便可以这样分配它们。我没有收到任何错误,但现在 $fav1
return 什么都没有。
您需要一个 while 循环来遍历所有行
while($row = $db_fav_result->fetch_assoc()) {
$fav = $row['favorite'];
echo $fav;
}
把它们放到 table:
<tr>
<?php
while($row = $db_fav_result->fetch_assoc()) {
$fav = $row['favorite'];
echo "<td>$fav</td>";
}
?>
</tr>
我正在尝试从名为 users
的 table 中 select 名为 favorite
的栏中的 5 个最常见的单词。我只需要前 5 个,但希望它们按 1 到 5 的顺序 return 进行显示。这些是名称,例如:
user1 Bob Marley
user2 Stan Smiley
user3 Bob Marley
user4 Joe Schmoe
等...
我有以下内容作为开始:
$db_fav_query = mysqli_prepare($con, "SELECT favorite, COUNT(*) AS favCOUNT FROM users GROUP BY favorite ORDER BY favCOUNT DESC LIMIT 5");
$db_fav_query->execute();
$db_fav_result = $db_fav_query->get_result();
$row = $db_fav_result->fetch_assoc();
$fav1 = $row['favorite'];
我正在尝试输出如下:
<tr>
<td><?php echo htmlentities($fav1); ?></td>
<td><?php echo htmlentities($fav2); ?></td>
<td><?php echo htmlentities($fav3); ?></td>
<td><?php echo htmlentities($fav4); ?></td>
<td><?php echo htmlentities($fav5); ?></td>
</tr>
我知道 $fav2
、$fav3
等.. 尚未声明,但我不确定如何从 dB 中获取它们以便可以这样分配它们。我没有收到任何错误,但现在 $fav1
return 什么都没有。
您需要一个 while 循环来遍历所有行
while($row = $db_fav_result->fetch_assoc()) {
$fav = $row['favorite'];
echo $fav;
}
把它们放到 table:
<tr>
<?php
while($row = $db_fav_result->fetch_assoc()) {
$fav = $row['favorite'];
echo "<td>$fav</td>";
}
?>
</tr>