Search code examples
phpwhile-loopecho

PHP echo variable outside of while loop returning last value


Hope everyone has had a good new year

I am trying to echo a value from a loop however it just returns the last value of a for loop

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'];
}

On my modal body is

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

I've tried using .= instead of = but that just concatenates all the usernames together

I understand it is probably an easy fix and have tried looping through the variable assigning section but it just returns 0

Thanks in advance


Solution

  • This is what i do in this kind of case.

    change the loop button

    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>";
    }
    

    and change modal to

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

    jquery code

    $('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
    });
    

    give this a try..