[英]Displaying SQL Query in HTML table (php)
試圖從 2 個不同的表中獲取計數到一個簡單的 HTML 表中。
這是我的代碼:
$sql = "SELECT COUNT(*) FROM tasks";
$result = $conn->query($sql);
$rowcount=mysqli_num_rows($result);
if ($result->num_rows > 0) { ?>
<table style="width:100%">
<tr>
<th>Total</th>
</tr>
<?php while($row = $result->fetch_assoc()) { ?>
<tr>
<td><?=$rowcount;?></td>
</tr>
<?php } ?>
</table>
<?php } else { echo "0 results"; } ?>
當我運行代碼時,它顯示了表中的行數,但它也創建了其中包含數字的行數(即 281 行)。
桌子 |
---|
281 |
281 |
281 |
281等 |
我的想法是復制並粘貼上面的內容以顯示第二組結果表(如果正確的話),但是有更好的方法嗎? 我一直在研究如何將SELECT (select COUNT(*) from tasks), (select count(*) from quotes)
顯示為以下格式(HTML):
桌子 | 數數 |
---|---|
任務 | 281 |
引號 | 42000 |
首先,您的查詢確實只為表生成一行,而不是 281。第二個 - 我省略了使用占位符准備好的 SQL 語句,只要適用,應始終在實際項目中使用。
$rows = [];
foreach(['Tasks', 'Quotes'] as $table ){
$result = $conn->query("SELECT '$table' as 'table', count(*) as 'count' FROM $table");
if( $result )
$rows[] = $result->fetch_assoc();
}
if( empty( $rows ) )
print "0 results";
else {?>
<table style="width:100%">
<tr><th>Table</th><th>Count</th></tr>
<?=implode(
"\n",
array_map(function($row){
return "<tr><td>${row['table']}</td><td>${row['count']}</td></tr>";
}, $rows)
)?>
</table>
<?php }
我一直在研究如何將 SELECT(從任務中選擇 COUNT( ))、(從引號中選擇 count( ))顯示為以下格式 (HTML)
您可以只運行 queries 查詢,並使用第一個的結果創建表的第一行,然后使用第二個的結果創建第二行。 由於在沒有 GROUP BY 時 COUNT 查詢總是只返回 1 行,所以做起來非常簡單:
$sql1 = "SELECT COUNT(*) FROM tasks";
$result1 = $conn->query($sql1);
if ($row = $result1->fetch_array()) $taskCount = $row[0];
else $taskCount = "error";
$sql2 = "SELECT COUNT(*) FROM quotes";
$result2 = $conn->query($sql2);
if ($row = $result2->fetch_array()) $quoteCount = $row[0];
else $quoteCount = "error";
?>
<table style="width:100%">
<tr>
<th>Table</th>
<th>Count</th>
</tr>
<tr>
<td>Tasks</td>
<td><?php echo $taskCount; ?></td>
</tr>
<tr>
<td>Quotes</td>
<td><?php echo $quoteCount; ?></td>
</tr>
</table>
另一種方法,如果您希望 HTML 結構重復性較低/依賴於表查詢,則將SELECT
UNION
到單個查詢中:
$sql = "SELECT 'Tasks' AS 'table', COUNT(*) as 'count' FROM tasks";
$sql .= " UNION ";
$sql .= "SELECT 'Quotes' AS 'table', COUNT(*) as 'count' FROM quotes";
$result = $conn->query($sql);
?>
<table style="width:100%">
<tr>
<th>Table</th>
<th>Count</th>
</tr>
<?php
while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo $row["table"]; ?></td>
<td><?php echo $row["count"]; ?></td>
</tr>
<?php
}
?>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.