Php Include file within a While loop

tillabong

New Member
Messages
60
Reaction score
0
Points
0
Hi, i was wondering if it is possible to use a php include within a while loop. like this. i tried it but the results are not showing. i only get the first result from the query.
PHP:
<?php while($data = mysql_fetch_array($result))  {?>	

<div id="resultswrapper">
       <?php $path = $_SERVER['DOCUMENT_ROOT']; $path .= "/resultscontainer.php"; include_once($path);?>					
     </div>
	
<?php  }?>

the resultscontainer.php file contains a table to display the query. but i seem to be only getting the first result. but if i were to just paste the table there, the while loop works fine. is there something im missing out?

Thanks.
 
Last edited:

kadai

New Member
Messages
51
Reaction score
2
Points
0
Well, since the file loaded ($path) does not change, my guess is that PHP interpretates that there is no need to load the given file because it was already loaded.

Since the include_once is a function that includes once, and only once a file... it will be skipped each new time it is loaded with the very same file it was loaded.

A way to test different results is to simply use include($path); instead. May be risky but you'll surely get a result.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
A better solution would be to define a class or function in "resultscontainer.php" and call the function/a method of the class to display each row. Abstracting further, define another class or function to display all the results; give it the result of a query and a class or function that displays each item, and the result view loops over the results displaying each item.

Since $path is invariant over the loop, it should be set outside the loop. Otherwise, you're wasting cycles re-evaluating the expression.
 
Last edited:

tillabong

New Member
Messages
60
Reaction score
0
Points
0
ok thank you so much for your replies. i will study them carefully. thanks!
 
Top