PHP - Why while(mysql_fetch_array(mysql_query())) loops?

爱⌒轻易说出口 提交于 2019-12-13 04:24:19

问题


So I have the code:

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


回答1:


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.

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




回答2:


It is because your query is inside which tells the while to execute the query again and again. If you are looking for a much simpler alternative, you can try using an ORM such phpactiverecord.



来源:https://stackoverflow.com/questions/17249861/php-why-whilemysql-fetch-arraymysql-query-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!