我有一个while循环,可以跟踪两个变量,并在条件通过或失败时将其递增。它肯定是递增的,但是它显示了递增的每次迭代。我只想在while循环结束后显示这些值。我知道我需要关闭循环然后显示值,但是我无法发生这种情况,因为我需要HTML为多个用户显示多次。我想知道如何让HTML多次显示,但每个用户只显示两个变量。
$addedItem = $tradedItem = 0;
$sql = "SELECT DISTINCT adminid, log_operation FROM item_log_table WHERE timestamp BETWEEN '$time' and '$time2' ORDER BY adminid ASC";
$result = $db->prepare($sql);
$result->execute();
while ($row = $result->fetch()) {
$username = $functions->getUserInfoSingularFromId('username', $row['adminid']);
$lastLogin = $functions->getUserInfoSingularFromId('previous_visit', $row['adminid']);
$lastLogin = $adminfunctions->displayDate($lastLogin);
if ($row['log_operation'] == "ADDED ITEM") {
$addedItem += 1;
} else {
$tradedItem += 1;
} ?>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="border-radius: 16px; margin-top: 25px;">
<div class="well profile col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
<p style="text-align:center;font-size: smaller;"><strong>Name | Employee: </strong><span class="tags" id="user-status"><?php echo $username; ?> | <?php echo $row['adminid']; ?></span></p>
<p style="text-align:center;font-size: smaller;"><strong>Date Last Logged In: </strong><span class="tags" id="user-status"> <?php echo $lastLogin; ?></span></p>
<div class="col-lg-6 left" style="text-align:center;overflow-wrap: break-word;">
<h4><p style="text-align: center;"><strong id="user-globe-rank"><?php echo $addedItem; ?></strong></p></h4>
<p><small class="label label-success">Items Added</small></p>
</div>
<div class=" col-lg-6 left" style="text-align:center;overflow-wrap: break-word;">
<h4><p style="text-align: center;"><strong id="user-college-rank"><?php echo $tradedItem; ?></strong></p></h4>
<p> <small class="label label-warning">Items Traded</small></p>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
What it looks like in the loop
我只希望它显示每个用户的$ addedItem和$ tradedItem的最后一次迭代。另外,请原谅我只是在制作原型的样式属性。
答案 0 :(得分:0)
由于您使用的是DISTINCT,因此您将仅为adminid
为log_operation
的{{1}}检索一条记录。
例如,如果您的表具有:
ADDED ITEM
您的查询将只检索
| adminid | log_operation |
| 1 | ADDED ITEM |
| 1 | ADDED ITEM |
| 1 | TRANSFER ITEM |
| 2 | ADDED ITEM |
对于特定的adminid,| adminid | log_operation |
| 1 | ADDED ITEM |
| 1 | TRANSFER ITEM |
| 2 | ADDED ITEM |
始终等于$addedItem
。
由于您没有为每个1
重置$addedItem
,因此您的循环将继续为每个adminid
递增。
要解决此问题并总计adminid
的所有log_operations
ADDED ITEM
,请对期望的adminid
值使用聚合函数。
log_operation
这将为每个adminid检索一行,其日志操作总数为SELECT
adminid,
SUM(CASE log_operation WHEN 'ADDED ITEM' THEN 1 ELSE 0 END) AS addedItems,
SUM(CASE log_operation WHEN 'ADDED ITEM' THEN 0 ELSE 1 END) AS tradedItems
FROM item_log_table
WHERE `timestamp` BETWEEN '$time' AND '$time2'
GROUP BY adminid
ORDER BY adminid ASC
,而不是。
ADDED ITEM
然后只需在html中检索这些列即可。
| adminid | addedItems | tradedItems |
| 1 | 2 | 1 |
| 2 | 1 | 0 |