0
 <?php function getnews()
{

global $db;

$news=$db->query("select * from news order by news_id desc");

$row=$news->fetch_object();

return $row;

}?>

`

foreach (getnews() as $result)
 { 
   echo $result->news_title . "<br>";
 }
?>

but foreach not work out of function

any help

1
  • Can you provide any errors? Commented May 14, 2016 at 16:23

1 Answer 1

1

Your getnews() function only ever returns a single row from the database, even though your query will fetch them all.... perhaps consider a loop in the getnews() function that returns each one in turn, maybe using a generator so that you can use them in a foreach loop

function getnews() {
    global $db;
    $news=$db->query("select * from news order by news_id desc");
    while ($row=$news->fetch_object()) {
        yield $row;
    }
}

foreach (getnews() as $result) { 
   echo $result->news_title . "<br>";
}

Though using a generator does require PHP >= 5.5

If you're using an earlier version of PHP, then build an array in getnews() and return that, but it isn't as efficient:

function getnews() {
    global $db;
    $news=$db->query("select * from news order by news_id desc");
    $items = array();
    while ($row=$news->fetch_object()) {
        $items[] = $row;
    }
    return $items;
}

foreach (getnews() as $result) { 
   echo $result->news_title . "<br>";
}
Sign up to request clarification or add additional context in comments.

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.