Mysqli搞砸了我的while循环

时间:2014-01-22 16:59:25

标签: php mysql mysqli while-loop

我正在尝试从数据库中检索人员列表。我用mysql做了大约一千次。我刚刚切换到mysqli,我检​​索人员的方法无法正常工作。

继承我的代码:

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

我的while循环重复两次数据库的第一个条目。例如:

  • [图片] Joseph Warren
  • [图片] Joseph Warren
  • [图片] Bob Robertson
  • [图片] Joseph Warren
  • [图片] Bob Robertson
  • [图片] Phil Sneider

([图片]是我从数据库中提取的图片)

1 个答案:

答案 0 :(得分:3)

$people移至循环外部。当你在里面调用它时,它将显示从前一个循环中已存储的内容。

$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;

我还建议您使用SELECT中的列列表进行最佳操作。