我有数据库记录了访问我网站的用户的IP地址和会话ID。我想显示前10个IP地址的HTML表以及与每个IP地址关联的不同会话数。
所以我从这个查询开始:
$sql="SELECT ip, country, city, COUNT(*) as count FROM Hits GROUP BY ip ORDER BY count DESC LIMIT 10";
然后,对于每个产生的10行,我使用while循环查询同一个数据库,以提取与每个地址相关的不同会话ID的数量:
$sql="SELECT DISTINCT Session FROM Hits WHERE ip='$ipaddress'"
我的挑战是在我通过while循环时构建一个数组(与MySQLi查询结果具有相同的结构),然后我可以使用foreach循环输出HTML表。这是我的完整代码:
$con = mysqli_connect("localhost","user","password","dbase");
$sql="SELECT ip, country, city, COUNT(*) as count FROM Hits GROUP BY ip ORDER BY count DESC LIMIT 10";
$result = mysqli_query($con,$sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$ipaddress = $row["ip"];
$sql="SELECT DISTINCT Session FROM Hits WHERE ip='$ipaddress'";
$res = mysqli_query($con,$sql);
$distinctsessions = mysqli_num_rows($res);
$data[] =$ipaddress.",".$distinctsessions;
};
$colNames = array_keys(reset($data));
foreach($data as $row) {
echo "<tr>";
foreach($colNames as $colName) {
echo "<td>".$row[$colName]."</td>";
}
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
mysqli_free_result($res);
mysqli_close($con);
我意识到我的错误在于:
$data[] =$ipaddress.",".$distinctsessions;
并且这可能不是正确的结构,但我无法解决问题。感谢你的建议。
答案 0 :(得分:0)
无需使用foreach
使用以下代码
$con = mysqli_connect("localhost","user","password","dbase");
$sql="SELECT ip, country, city, COUNT(*) as count FROM Hits GROUP BY ip ORDER BY count DESC LIMIT 10";
$result = mysqli_query($con,$sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$ipaddress = $row["ip"];
$sql="SELECT DISTINCT Session FROM Hits WHERE ip='$ipaddress'";
$res = mysqli_query($con,$sql);
$distinctsessions = mysqli_num_rows($res);
?>
<tr>
<td><?php echo $ipaddress; ?></td>
<td><?php echo $distinctsessions; ?></td>
</tr>
<?php }
echo "</table>";
mysqli_free_result($result);
mysqli_free_result($res);
mysqli_close($con);
?>