PHP while 循环外的 echo 变量返回最后一个值

PHP echo variable outside of while loop returning last value

希望大家新年快乐

我正在尝试从循环中回显一个值,但它只是 returns for 循环的 last

while ($row = $stmt->fetch_assoc()) {
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td><button type=\"button\" class=\"btn btn-info btn-sm\" data-toggle=\"modal\" data-target=\"#modal-username\">Username</button></td>";
    echo "<td>" . $row['password'] . "</td>"; // Don't worry the password is hashed
    echo "<td>" . $row['email'] . "</td>";
    echo "<td>" . $row['admin'] . "</td>";
    echo "</tr>";

    // Assign variables to use out of loop
    $id = $row['id'];
    $username = $row['username'];
    $password = $row['password'];
    $email = $row['email'];
    $admin = $row['admin'];
}

在我的模态主体上是

<div class="modal-body">
    <p><?php echo $username; ?></p>
</div>

我试过使用 .= 而不是 = 但这只是将所有用户名连接在一起

我知道这可能是一个简单的修复方法,并尝试循环遍历变量分配部分,但它只是 returns 0

提前致谢

$username是一个变量,它只能保持
如果你想保留所有用户名,那么应该使用 Arrays

像这样的东西:

$id=$username=$password=$email=$admin=Array(); 

while ($row = $stmt->fetch_assoc()) {
    // Assign variables to use out of loop
    $id[] = $row['id'];
    $username[] = $row['username'];
    $password[] = $row['password'];
    $email[] = $row['email'];
    $admin[] = $row['admin'];
}

echo $username[0];// first username
echo $email[1];// second email

更新

您可以 limit 查询结果,例如:

$result = mysqli_query($connection,'select * from tablename limit 20;');

如果你想获取一些没有固定长度的数据:

$username=Array();

while ($row = $stmt->fetch_assoc()) {
    $username[] = $row['username'];
}

echo count($username);// how many? as integer

或在 while 循环之后你可以使用 for 循环

for ( $i=0; $i<count($username); $i++){

    echo $username[$i].'<br>';

}

更新 2

如果您尝试仅存储和显示第一个用户名,那么您可以这样做:

while ($row = $stmt->fetch_assoc()) {
    if(!isset($username)){
        $username = $row['username'];
    }
}
echo $username;// first only

或更短一些:

while ($row = $stmt->fetch_assoc()) {
    $username = $username ?: $row['username'];
}
echo $username;// first only

遇到这种情况我就是这么做的。

更改循环按钮

while ($row = $stmt->fetch_assoc()) {
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td><button type=\"button\" class=\"btn btn-info btn-sm modal-trigger\" data-uname='" .  $row['username'] . "'>Username</button></td>";
    echo "<td>" . $row['password'] . "</td>"; // Don't worry the password is hashed
    echo "<td>" . $row['email'] . "</td>";
    echo "<td>" . $row['admin'] . "</td>";
    echo "</tr>";
}

并将模式更改为

<div class="modal-body">
    <p id="uname-select"></p>
</div>

jquery代码

$('body').on("click", '.modal-trigger', function() {
    var GetUname = $(this).attr('data-uname');
    console.log('Selected Username: ' + GetUname);
    $('#uname-select').html(GetUname); // load the <p> tag with username selected
    $('.modal').modal(); // Make Modal & Show
});

试试这个..