Select 满足条件的数据库 table 的所有结果,将结果限制为 6 - 如果结果小于 6,也会显示 advert/div

Select all results from database table where condition is met, limit results to 6 - and if results less than 6 show advert/div also

我的数据库中有一个名为用户的 table。目前我的 table 用户中有 5 个用户。

我正在尝试使用以下代码从我的 table 中列出最多 6 个用户:

<?php $sql = "SELECT * FROM users WHERE status = 'active' AND usertype = 'advertiser' LIMIT 6";
    $result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
    while($row = mysqli_fetch_assoc($result)){

    echo "<div id='prime'>" .$row['username']. "</div>"; // I just did not use "htmlspecialchars()" function. 

    } ?>

我的查询只获取 5 个结果,因为 table 中只有这些结果,如下所示:

User1.  User2.   User3.   User4.   User5.

如果 table 中没有至少 6 个用户,那么我仍然希望显示 6 个项目,替代方案是一种广告 div - 像这样:

User 1.  User 2.   User 3.   User 4.   User 5.  Advertise Here 6.

我怎样才能amend/improve我的代码来实现上述目标?

使用for循环:

$sql = "SELECT * FROM users WHERE status = 'active' AND usertype = 'advertiser' LIMIT 6";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);

for ($key = 0; $key < 6; $key++) {
    if (isset($result[$key])) {
        echo "<div id='prime'>" .htmlspecialchars($result[$key]['username']). "</div>";
    } else {
        echo "<div id='prime'>Advertise here</div>";
    }
}

或者您也可以使用 while 循环。

$key = 0;
while ($key != 6) {
    if (isset($result[$key])) {
        echo "<div id='prime'>" .htmlspecialchars($result[$key]['username']). "</div>";
    } else {
        echo "<div id='prime'>Advertise here</div>";
    }
    $key++;
}