Skip to content
Advertisement

Why is my while loop spitting out the same row 50+ times? PHP

Here is my code:

public function GetLatestUsers(){
    $statement = $this->Db->prepare("SELECT * FROM users ORDER by id DESC LIMIT 10");
    $statement->execute();
            
    return $statement->fetch(PDO::FETCH_ASSOC);
}

And here is the while loop:

<?php  
    
    while($row = $crud->GetLatestUsers()){     
?>
        <tr>
            <td></td>
            <td><?php echo $row['id']; ?></td>
            <td><img src="" style="border-radius:15px; margin-right:10px;" width="25px" height="25px">  <?php echo $row['username'] ?></td>
            <td><font color="green">Positive</font></td>
            <td>Confirmed</td>
            <td><a href="">Feedback</a></td>
        </tr>
<?php
    }    
?>

This is just returning 50+ of the same row, aka the only row in the database, but it should only return it once?

Advertisement

Answer

You’re running the query again in each loop.

$result = $crud->GetLatestUsers();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
// do whatever.
}

GetLatestUsers should return the statement.

return $statement;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement