【问题标题】:Echo all While outputs into a single variable [duplicate]将所有While输出回显到单个变量中[重复]
【发布时间】:2020-08-17 21:18:54
【问题描述】:

这是我的代码:

$sql = "SELECT * FROM notifications";
if($result = mysqli_query($link, $sql)) {
    if(mysqli_num_rows($result) > 0) {  
        while($row = mysqli_fetch_array($result)) {
            $notification = "
<a class='d-flex align-items-center dropdown-item' href=".$row["link"].">
<div class='dropdown-list-image mr-3'><i class='fas fa-bell'></i>
<div class='bg-success status-indicator'></div>
</div>
<div class='font-weight-bold'>
<div class='text-truncate'><span>".$row["omschrijving"].".</span></div>
<p class='small text-gray-500 mb-0'>".$row["klant"]." - ".$row["createdat"]."</p>
</div>
</a>    
";
        }
    }
}

在我的页面中还有:

echo "<h6 class='dropdown-header'>Notificaties</h6>
$notification"

出于不同的原因,我真的希望将输出作为单个变量。

现在它只从数据库输出第一个通知。

是否可以这样做:为表中的每一行回显 $notification?

【问题讨论】:

  • $notification .=使用串联

标签: php if-statement variables mysqli while-loop


【解决方案1】:

连接通知可能会做到这一点

$notification = '';
while($row = mysqli_fetch_array($result))
    $notification .="
        <a class='d-flex align-items-center dropdown-item' href=".$row["link"].">
        <div class='dropdown-list-image mr-3'><i class='fas fa-bell'></i>
        <div class='bg-success status-indicator'></div>
        </div>
        <div class='font-weight-bold'>
        <div class='text-truncate'><span>".$row["omschrijving"].".</span></div>
        <p class='small text-gray-500 mb-0'>".$row["klant"]." - ".$row["createdat"]."</p>
        </div>
        </a>   ";

【讨论】:

  • 它现在显示得更多了,我收到了 6 条通知。奇怪的是我的数据库中有 2 个通知。并且还得到:注意:未定义的变量:第 83 行 C:\xampp\htdocs\parameters.php 中的通知
  • while之前需要定义变量$notification = '';
  • @TimNijland 你需要在使用它之前初始化变量(在截图中添加了必要的行)
  • “如何在循环中连接字符串”可能是 Stack Overflow @Berto 上的重复项,请关闭而不是回答。
  • 非常感谢@Berto99!
【解决方案2】:

看起来您在 while 循环中的每个实例上都写了 $notification 变量。您应该查看concatenating 那个变量。此外,您需要注意 PHP 变量中的 HTML 可能并不总是很好。我还建议使用heredoc 语法。它看起来像这样:

$notification .= <<<EOD
HTML goes here
EOD;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2012-05-28
    • 2019-09-29
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    相关资源
    最近更新 更多