0

i searched all over the web or i just don't see it.

I want to do the following:

<?php

 function abc(){
   $sql = "SELECT * FROM table";
   $result = mysql_fetch_assoc($sql);
   $data = mysql_fetch_assoc($result);
}

?>

<? while(abc()) : ?>

   <?=article_title()?>
   <?=article_content()?>

<?=endwhile;?>

Could somebody give me a direction and/or example?

Thank you very much

4
  • 2
    wat do u want to achieve exactly ? Commented Apr 23, 2012 at 17:58
  • mysql_free_result() on the result when you are done. Commented Apr 23, 2012 at 18:00
  • something like wordpress they use, while(function()):, endwhile;. i want to make something similar, it makes a template designing much easier Commented Apr 23, 2012 at 18:03
  • do you want to print the results of the function ? do whiel loops r quite simple to use, but I still dont know what exactly u want to achieve, apart from using a do while loop ! Which u find all over the web ! So give us a bit more detail on why u want this loop, what u want to achieve ! Commented Apr 23, 2012 at 18:21

2 Answers 2

2

PHP does not have generator/iterator functions, so you cannot do that.

You can however return an array and iterate over that array:

function abc() {
    // ...
    $rows = array();
    while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
    return $rows;
}

foreach(abc() as $row) {
    // do something
}

If the functions you call need access to the row, pass it as an argument. Using global variables for it would be very bad/nasty

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

1 Comment

That's why I said iterator functions. In python you could do what the OP wanted using the yield keyword - which does not exist in PHP.
1

have you tried to do something like that?

<?php
function getData(){
    //get the data from the database
    //return an array where each component is an element found
}

$elems = getData();
foreach($elems as $e){
    doSomethingWith($e);
}

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.