Yugal1458
Yugal1458

Reputation: 71

While loop is not displaying all values

I am having this weird problem. There are seven admins: darth, jane, luke, najin, root, sam and sydney.

CODE:

    <table>
          <tr>
            <th style="text-align: left; width: 200px;">Username</th>
            <th colspan="2" style="text-align: left;">Action</th>
          </tr>
        <?php 

            $sql = "SELECT * FROM admins ORDER BY Admin_Username ASC";
            $result = mysqli_query($connection, $sql);
            $admin = mysqli_fetch_assoc($result);

            while($admin = mysqli_fetch_assoc($result)) { 
            ?>
          <tr>
            <td><?php echo ($admin["Admin_Username"]); ?></td>
            <td><a href="edit_admin.php?id=<?php echo urlencode($admin["id"]); ?>">Edit</a></td>
            <td><a href="delete_admin.php?id=<?php echo urlencode($admin["id"]); ?>" onclick="return confirm('Are you sure you want to delete this admin?');">Delete</a></td>
          </tr>
        <?php     
} 
?>
</table>

If I use ASC order, the first admin, darth is not displayed in the loop and if I use DESC order, the last admin, sydney doesn't show up. What could be the problem here?

Upvotes: 4

Views: 126

Answers (5)

Pratik Joshi
Pratik Joshi

Reputation: 11693

$admin = mysqli_fetch_assoc($result);

This must be in while loop So you can descard/remove old value above while

Upvotes: 0

deviloper
deviloper

Reputation: 7240

    <?php 

            $sql = "SELECT * FROM admins ORDER BY Admin_Username ASC";
            $result = mysqli_query($connection, $sql);    
            while($admin = mysqli_fetch_assoc($result)) { 
            ?>
          <tr>
            <td><?php echo ($admin["Admin_Username"]); ?></td>
            <td><a href="edit_admin.php?id=<?php echo urlencode($admin["id"]); ?>">Edit</a></td>
            <td><a href="delete_admin.php?id=<?php echo urlencode($admin["id"]); ?>" onclick="return confirm('Are you sure you want to delete this admin?');">Delete</a></td>
          </tr>
    <?php     
    } 
    ?>

Upvotes: 2

Mureinik
Mureinik

Reputation: 311063

You have a redundant call to $admin = mysqli_fetch_assoc($result); before the while loop which will cause you to skip the first row of the result. Just remove it and you should be fine.

Upvotes: 2

arif_suhail_123
arif_suhail_123

Reputation: 2509

remove this line

 $admin = mysqli_fetch_assoc($result);//You already fetching the first result here

Upvotes: 3

Amber
Amber

Reputation: 526543

Get rid of the first $admin = line.

Your loop will fetch all of them; you don't need to fetch the first one separately (and if fact by doing so are skipping it, because your loop immediately fetches the second before the first one could be written out).

Upvotes: 4

Related Questions