PHP - 为什么 while(mysql_fetch_array(mysql_query())) 循环?

问题描述:

所以我有代码:

$sql = "SELECT * from users WHERE level = 2";
$result = mysql_query($sql);
while($write = mysql_fetch_array($result)){
    echo ''.$write['username'].'';
}

我想让它更简单,所以我这样做:

I want to make it more simple so I do:

while($write = mysql_fetch_array(mysql_query("SELECT * from users WHERE level = 2"))){
echo ''.$write['username'].'';
}

为什么第一个代码不是无限循环而第二个代码是?

Why the first code isn't infinity looping and the second code is?

第一个代码迭代一个由 mysql_query($sql);

the first code iterates a resource given by mysql_query($sql);

第二次迭代查询并每次永远加载第一行.因此,它不会转到下一行,而是创建一个新查询并从该行开始.

the second iterates the query and loads the first row each time forever. so instead of going to the next row, it makes a new query and starts on that row.

作为旁注 - 不要使用 mysql_* 函数.使用 mysqli_pdo 代替.

As a side note - dont use mysql_* functions. Use mysqli_ or pdo instead.