0

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?

5
  • Because the mysql_query() gets rerun in each loop. Commented Jun 22, 2013 at 10:48
  • 3
    Q: why is the sky blue? A: read the docs Commented Jun 22, 2013 at 10:49
  • Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial Commented Jun 22, 2013 at 10:52
  • I can see the confusion. Most functions you are able to nest in this way. Commented Jun 22, 2013 at 10:53
  • Because every time your query is executed so it makes loop infinite Commented Jun 22, 2013 at 10:58

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.