php列出html表中列和行中的mysql数据

时间:2016-05-02 19:25:06

标签: php mysql html-table

我的数据库,播放器和分数表中有2个表。我在这些表中有数据,并希望将我的分数表中的数据列出到HTML表。我希望玩家名称是列,玩家的分数是行。我已经看到了如何使用预定义列添加行的示例,但是没有看到如何添加将数据设置为列的示例。由于玩家名称在播放器表中,我将不得不使用join函数来显示播放器名称,不知道如何使用php执行此操作。我是php的新手,所以一直坚持这一点。

  

数据库

玩家表:

playerid
name
lastname

得分表:

scoreid
score
playerid (foreign key with player.playerid)

我的分数数据包含ex:

scoreid: 1, score: 53, playerid: 1
scoreid: 2, score: 23, playerid: 1 
scoreid: 3, score: 12, playerid: 2 
scoreid: 4, score: 67, playerid: 3 
scoreid: 5, score: 31, playerid: 2  
  

PHP:   这是我现在工作的,但它只显示名称。

$result = mysqli_query($conn,"SELECT * FROM player");

echo "<table>
<tr>
<th>Name</th>
<th>Last Name</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "</tr>";
}
echo "</table>";
  

通缉结果

| Jonny  |  Mike  |  Bill  |
|   23   |   10   |   12   |
|   12   |   31   |   23   |

...等

如您所见,播放器名称是列,分数是与播放器对应的行中的数据。

想想它:

玩家表格有:

id: 1. name: Jonny
id: 2. name: Mike
id: 3. name: Bill

得分表有:

scoreid: 1, score: 23, playerid: 1 (Jonny)
scoreid: 2, score: 12, playerid: 1 (Jonny)
scoreid: 3, score: 10, playerid: 2 (Mike)
scoreid: 4, score: 31, playerid: 2 (Mike)
scoreid: 5, score: 12, playerid: 3 (Bill)
scoreid: 6, score: 23, playerid: 3 (Bill) 

希望你现在能更好地理解

  

输出

这就是它之前的样子

enter image description here

现在结果如下:

enter image description here

2 个答案:

答案 0 :(得分:2)

您必须使用JOIN,方法如下:

$result = mysqli_query($conn,"SELECT player.*, score.* FROM player LEFT JOIN score ON score.playerid = player.playerid ");

echo "<table>
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Score</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['score'] . "</td>";
echo "</tr>";
}
echo "</table>";

答案 1 :(得分:1)

最好的方法是让你的表格在列中显示&#34;行数据&#34;是在表中使用表,因为必须逐行构建HTML表。

然后,要获得玩家的所有分数,您可以通过单独请求为每个玩家请求数据,也可以使用GROUP_CONCAT。

$result = mysqli_query($conn,"SELECT p.*, (SELECT GROUP_CONCAT(s.score) FROM score s WHERE s.playerid = p.playerid) AS scorearray FROM player p");

现在,您的结果将包含您的播放器表的所有列和一个列&#34; scorearray&#34;,其中包含以逗号分隔的播放器所有分数列表。 See GROUP_CONCAT example

要生成第一行,您可以重复使用给定的代码:

$result = mysqli_query($conn, "SELECT p.*, (SELECT GROUP_CONCAT(s.score) FROM score s WHERE s.playerid = p.playerid) AS scorearray FROM player p");


$playercols = array(); 
$scores = array(); 

while($row = mysqli_fetch_array($result)) 
{ 
    $playercols[] =  "<th>" . $row['name'] . "</th>"; 
    $currentscore = explode(",", $row['scorearray']); 
    // Only doing a line break, you can build a one-columned table out of this data aswell 
    $scores[] = "<td valign=top>" . implode("<br />", $currentscore) . "</td>"; 
} 
echo "<table>"; 
echo "<tr>"; 
echo implode("", $playercols); 
echo "</tr>"; 
echo "<tr>"; 
echo implode("", $scores); 
echo "</tr>"; 
echo "</table>"; 

在此处查看结果:Result

完整来源:Source