[英]SQL select multiple arrays and populate one table
我正在嘗試使用來自同一個表的 2 個 select 查詢的結果填充 1 個表。 它不起作用,一個填充另一個只顯示一個結果.. 是否可以在一個 select 中執行此操作,因為我認為問題在於使用兩個 fetch assoc。
問題:如何獲得我創建的表中顯示的這兩個查詢的結果?
<table align="left" style="width: auto; min-width: 700px; margin-bottom:20px;" class="deftable">
<thead><tr>
<th colspan="4">Top 10 users</th>
</tr>
</thead>
<thead><tr>
<th colspan="2">Top 10 Richest users</th>
<th colspan="2">Top 10 Bananaslappers</th>
</tr>
</thead>
<thead>
<tr><th>Name</th>
<th>Bananas</th>
<th>Name</th>
<th>Total slapped</th>
</tr></thead><tbody>
<?php
$stmt88 = $mysqli->prepare("SELECT naam,geld FROM `gebruikers` ORDER BY geld DESC LIMIT 10 ");
$stmt88->execute();
$result = $stmt88->get_result(); //only works when nd_mysli is set on the server!
$stmt88->close();
while ($rowrich = $result->fetch_assoc()) {
$stmt89 = $mysqli->prepare("SELECT naam,user_amountslapped FROM `gebruikers` ORDER BY user_amountslapped DESC LIMIT 10 ");
$stmt89->execute();
$result2 = $stmt89->get_result(); //only works when nd_mysli is set on the server!
$stmt89->close();
while ($rowrich2 = $result2->fetch_assoc()) {
?>
<tr><td >
<a class="online" href="profile.php?username=<?= htmlspecialchars($rowrich['naam']) ?>"><b><?= htmlspecialchars($rowrich['naam']) ?></b></a></td>
<td>🍌<?= htmlspecialchars(number_format($rowrich['geld'],0,",",".")) ?></td>
<td >
<a class="online" href="profile.php?username=<?= htmlspecialchars($rowrich2['naam']) ?>"><b><?= htmlspecialchars($rowrich2['naam']) ?></b></a></td>
<td>🍌<?= htmlspecialchars(number_format($rowrich2['user_amountslapped'],0,",",".")) ?></td>
</tr>
</tbody>
<? } }?></table><br>
你不應該有嵌套循環,這是在兩個結果之間創建一個叉積,而不是並行處理它們。
您應該有一個從每個查詢中獲取一行的循環。
<?php
$stmt88 = $mysqli->prepare("SELECT naam,geld FROM `gebruikers` ORDER BY geld DESC LIMIT 10 ");
$stmt88->execute();
$result = $stmt88->get_result(); //only works when nd_mysli is set on the server!
$stmt88->close();
$stmt89 = $mysqli->prepare("SELECT naam,user_amountslapped FROM `gebruikers` ORDER BY user_amountslapped DESC LIMIT 10 ");
$stmt89->execute();
$result2 = $stmt89->get_result(); //only works when nd_mysli is set on the server!
$stmt89->close();
while (($rowrich = $result->fetch_assoc()) && ($rowrich2 = $result2->fetch_assoc())) {
?>
<tr><td >
<a class="online" href="profile.php?username=<?= htmlspecialchars($rowrich['naam']) ?>"><b><?= htmlspecialchars($rowrich['naam']) ?></b></a></td>
<td>🍌<?= htmlspecialchars(number_format($rowrich['geld'],0,",",".")) ?></td>
<td >
<a class="online" href="profile.php?username=<?= htmlspecialchars($rowrich2['naam']) ?>"><b><?= htmlspecialchars($rowrich2['naam']) ?></b></a></td>
<td>🍌<?= htmlspecialchars(number_format($rowrich2['user_amountslapped'],0,",",".")) ?></td>
</tr>
</tbody>
<? } ?></table><br>
請注意,如果任一查詢返回的行數少於 10 行,則表將在較短的長度處停止。 如果您想要更長的長度,請使用||
在while
條件下,然后在輸出這些列之前檢查$rowrich
或$rowrich2
是否為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.