nitrous
nitrous

Reputation: 1757

Mysqli is messing up my while loop

I am trying to retrieve a list of people from a database. I've done this about a thousand times with mysql. I just recently switch to mysqli and my method for retrieving people isn't working properly.

Heres my code:

$people = '';
$get_people = mysqli_query($con, 'SELECT * FROM people ORDER BY id');
while ($rows = mysqli_fetch_assoc($get_people)) {
    $fn = $rows['first_name'];
    $ln = $rows['last_name'];
    $img = $rows['picture'];

    $people .= '<li>';
    $people .= "<img src='".$img."' style='width: 20px; height: 20px;'> ";
    $people .= "<span>".$fn." ".$ln."</span>";
    $people .= '</li>';

    echo $people;
}

My while loop repeats the first entry of the database twice. Example:

([image] is the picture I pulled from the database)

Upvotes: 0

Views: 53

Answers (1)

Kermit
Kermit

Reputation: 34054

Move $people to outside your loop. When you call it inside, it will display what has already been stored from the previous loop.

$people = '';
$get_people = mysqli_query($con, 'SELECT * FROM people ORDER BY id LIMIT 2');
while ($rows = mysqli_fetch_assoc($get_people)) {
    $fn = $rows['first_name'];
    $ln = $rows['last_name'];
    $img = $rows['picture'];

    $people .= '<li>';
    $people .= "<img src='".$img."' style='width: 20px; height: 20px;'> ";
    $people .= "<span>".$fn." ".$ln."</span>";
    $people .= '</li>';
}

echo $people;

I would also suggest that you use a column list in your SELECT for best practice.

Upvotes: 3

Related Questions