如何计算特定单词出现的行数,并显示包含所有结果的表格。现在只是得到一个空白页面。
$conn = new mysqli($servername, $username, $password, $dbname);
// Set BoatName as variable from the table containing list of boats.
$query = "SELECT BoatName from SpeciesHuntBoats";
$boatname = $conn->query($query);
// Calculate number of rows that boat name appears in another table
$result = mysqli_query($conn, "SELECT * FROM SpeciesHunt WHERE `BoatName` = '$boatname'");
$num_rows = mysqli_num_rows($result);
// Display a table showing all boat names and the number of rows that name appears in
echo "<table><tr><th>Boat Name</th><th>Number of Species</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["BoatName"] . "</a></td><td>" . $row["$num_rows"]. "</td>/tr>";
}
echo "</table>";
$conn->close();
答案 0 :(得分:0)
1:如果您有错误,请始终检查服务器的错误日志。这将告诉你确切的答案。
2:query返回一个mysql_result,你需要进一步处理它。
$boatname = $conn->query($query);
为变量分配一个mysql_result对象
"SELECT * FROM SpeciesHunt WHERE
BoatName = '$boatname'"
会尝试将其转换为字符串,但会在php中抛出错误。可能这是你的问题。
试试$boatname = $conn->query($query)->fetch_object()->BoatName
。
这会将查询结果提取到一个对象数组中,然后选择第0个索引,然后获取元素BoatName。
SELECT
COUNT(SpeciesHunt.id) AS NumberOfSpecies,
SpeciesHuntBoats.BoatName
FROM SpeciesHunt
LEFT JOIN SpeciesHuntBoats
ON SpeciesHuntBoats.BoatName = SpeciesHunt.BoatName
GROUP BY SpeciesHunt.BoatName;
然后打印到表格:
echo "<table><tr><th>Boat Name</th><th>Number of Species</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["BoatName"] . "</a></td><td>" . $row["NumberOfSpecies"]. "</td>/tr>";
}
echo "</table>";