php - 使用数组填充表格
问题描述
我正在尝试计算提交给摄影比赛的图像数量。我正在使用一个数组(称为 $frequencies)来存储我的查询生成的值。我可以创建一个包含比赛名称和条目数的表格,但看不到如何包含与每个比赛相关的 id。简而言之,我想要 id、比赛名称和计数 - 我可以得到所有这三个,但不能让 id 可以用于将用户引导到特定比赛的链接中)。
我明白了(一切正常,但没有 id):
...但是想要这个(我想不出如何将 id 放入表中):
请参阅下面的查询和数组。
<?php
$con = mysqli_connect( DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE );
if ( mysqli_connect_errno() ) {
echo "Failed to connect to MySQL: " . mysqli_connect_error( $con );
}
$frequencies = array();
$cnt_result = "SELECT entered_images.id AS compID,
competitions.name AS compName,
COUNT(entered_images.id) AS Freq
FROM entered_images
INNER JOIN competitions
ON competitions.id = entered_images.id
GROUP BY competitions.name";
$cnt_Recordset1 = mysqli_query( $con, $cnt_result )or die( mysqli_error( $con ) );
$row_Recordset1 = mysqli_num_rows( $cnt_Recordset1 );
if ( $cnt_Recordset1 === false ) {
trigger_error( mysqli_error( $GLOBALS[ 'con' ] ) );
}
while ( $row = mysqli_fetch_row( $cnt_Recordset1 ) ) {
$frequencies[$row[1]] = $row[2];
}
?>
这按要求工作。这是我将值放入表中的方法:
<table width="95%" border="1" align="center">
<tbody>
<tr>
<td align="center" bgcolor="#F8F2C3"><strong>Competition Name</strong></td>
<td align="center" bgcolor="#F8F2C3"><strong>Count</strong></td>
</tr>
<?php foreach ($frequencies as $name => $count) {?>
<tr>
<td><?php echo $name?></td>
<td align="center"><?php echo $count; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
解决方案
应该就像简单地将 ID 添加到表中一样简单,不是吗?我建议直接在结果上使用 foreach 循环以避免双重循环。
$sQuery = "SELECT entered_images.id AS compID,
competitions.name AS compName,
COUNT(entered_images.id) AS Freq
FROM entered_images
INNER JOIN competitions
ON competitions.id = entered_images.id
GROUP BY competitions.name";
$result = mysqli_query( $con, $cnt_result )or die( mysqli_error( $con ) );
<table width="95%" border="1" align="center">
<thead>
<tr>
<th align="center" bgcolor="#F8F2C3"><strong>ID</strong></th>
<th align="center" bgcolor="#F8F2C3"><strong>Competition Name</strong></th>
<th align="center" bgcolor="#F8F2C3"><strong>Count</strong></th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) {?>
<tr>
<td><?php echo $row['compID'] ?></td>
<td><?php echo $row['compName']?></td>
<td align="center"><?php echo $row['Freq']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
推荐阅读
- python - 用 Python 重命名一个带有文件名的目录
- database - SQLite - 如何获取字符串中所有字符的出现
- javascript - VUEX,$store.state 为空时怎么办
- angular8 - 同步融合中连接器的重叠
- mysql - 如何在 SQL 中多次关联表?
- python - Sympy solveset 将结果存储为浮点数、整数等
- excel - VBA 中的行数和列数显示不正确
- amazon-web-services - AWS Api Gateway 与 S3 作为 AWS 服务集成的 SAM 模板
- python - Python函数处理不存在的参数
- iframe - 包含带有 Web 扩展的 iframe 是否被视为远程代码?