希望有人能在这里提供帮助。
我正在创建一个网站,该网站将列出赛马技巧,这些技巧是使用 PHP 脚本从 MySQL 数据库中提取的。我已经成功创建了数据库,该数据库有五列(ID、RaceDate、Location、RaceTime 和 Horse),并且我创建了一些查询 RaceDate 列的脚本,并且仅显示与当前日期匹配的行。见下文:
<?php
$db_host = 'xxxxx'; // Server Name
$db_user = 'xxxxx'; // Username
$db_pass = 'xxxxx'; // Password
$db_name = 'xxxxx'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT * FROM Horses WHERE Date(RaceDate) = Date(NOW())';
$result = $conn->query($sql);
?>
然后,我在页面下方还有另一段 php,它回显要屏幕的数据,并以漂亮的表格进行格式化。
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<tr>
<td>'.$row['Location'].'</td>
<td>'.$row['RaceTime'].'</td>
<td>'.$row['Horse'].'</td>
</tr>';
}
} else {
echo '0 results';
}
$conn->close();
?>
这一切都很好,但在一个大列表中吐出所有内容。我真正想做的是根据比赛地点分割结果。
例如,在location1可能有5场比赛,在location2有5场比赛,在location3有5场比赛。我不想将 15 场比赛逐一列出,而是将其分为 3 个组/表。有没有办法搜索我的查询数据的位置列并确定列出了哪些赛马场,然后将数据回显到屏幕?
e.g IF Location = Wolverhampton
THEN echo to table 1
ELSE IF Location = Ayr
THEN echo to table 2
ELSE IF Location = Llos Fas
THEN echo to table 3
(etc, if more Locations exist)
最佳答案
我的评论只是让事情变得复杂,这是更简单的方法。
while($row = $result->fetch_assoc()) {
if($row['Location'] === 'location1')
{
echo '<tr>
<td>'.$row['Location'].'</td>
<td>'.$row['RaceTime'].'</td>
<td>'.$row['Horse'].'</td>
</tr>';
}else if($row['Location'] === 'location2')
{
echo '<tr>
<td>'.$row['Location'].'</td>
<td>'.$row['RaceTime'].'</td>
<td>'.$row['Horse'].'</td>
</tr>';
}else if($row['Location'] === 'location3')
{
echo '<tr>
<td>'.$row['Location'].'</td>
<td>'.$row['RaceTime'].'</td>
<td>'.$row['Horse'].'</td>
</tr>';
}
// And so on....
}
关于PHP MYSQL - 搜索和排序查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45772343/