Foreach和while循环打印相同的值

时间:2014-06-29 14:04:11

标签: php mysql foreach while-loop

我正在尝试从每个用户那里获取信息,这就是我正在尝试的内容:

$db_conexion = mysqli_connect("localhost", "foo", "bar", "users");
if(mysqli_connect_errno()){
    printf("Ocurrio un error en la conexion de la base de datos: %s\n", mysqli_connect_error()); exit();
}

// I got $evUsers from previous MySQL query
// It looks like: 1,2,4,6,10,25;
// Each number = userID
$cleanUsers = preg_replace('/\;$/', '', $evUsers);
$members = explode(',', $cleanUsers);

foreach($members as $member){
    $result = mysqli_query($db_conexion, "SELECT * FROM users WHERE userID=$member");
    while($row = mysqli_fetch_array($result)){
        $memberID = $row['userID'];
        $memberName = $row['userName'];
        $memberAddress = $row['userAddress'];

        echo "ID: ".$memberID." - Name: ".$memberName." - Address: ".$memberAddress.PHP_EOL;
    }
}

mysqli_free_result($result);
mysqli_close($db_conexion);

此代码一遍又一遍地打印第一个用户的信息。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

试试这个

$members = preg_replace('/\;$/', '', $evUsers);
//$members = explode(',', $cleanUsers); <--- take this off

//foreach($members as $member){ <--- take this off as well
    $result = mysqli_query("SELECT * FROM users WHERE userID IN ($members)");
    while($row = mysqli_fetch_array($result)){
        $memberID = $row['userID'];
        $memberName = $row['userName'];
        $memberAddress = $row['userAddress'];

        echo "ID: ".$memberID." - Name: ".$memberName." - Address: ".$memberAddress.PHP_EOL;
    }
//}