Return results from mysql, using user functions

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];
}

Upvotes: 0

Views: 39

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30463

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];
}

Upvotes: 2

Related Questions