0

Please tell, why this code is wrong?

function myres () {
   $db = new mysqli("localhost","userrr","pass","mvc");
   $res = $db->query("SELECT * FROM news ");
   return $res;
}


while ($row = myres()->fetch_row()) {
    echo  $row[0];
}

P.S. this code is working:

$db = new mysqli("localhost","userrr","pass","mvc");
$res = $db->query("SELECT * FROM news ");
while ($row = $res->fetch_row()) {
    echo  $row[0];
}
3
  • 1
    Your myres() is executed each time the while condition is checked. If you extract it to a variable before the while loop, it will work better. Commented Jul 28, 2012 at 15:59
  • 1
    Why don't you just take the query out of the function, or have it return an array and do a foreach? Commented Jul 28, 2012 at 15:59
  • Thanks very much all, my error is undestood, thanks. Commented Jul 28, 2012 at 16:11

1 Answer 1

2

Here you call myres() every time, I think:

while ($row = myres()->fetch_row()) {
  echo  $row[0];
}

So every time $row contain first row of the result, and it will not stop. It will works fine, I think:

$res = myres();

while ($row = $res->fetch_row()) {
  echo  $row[0];
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is not an answer, and would be more-suitable as a comment.
This lends credence to the idea it's being called new each time: codepad.org/9DeSMUvu

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.