Originally posted by superwormy
You're using memory for the internally stored mysql result, plus memory for your string. Not to mention, if you store it in a string, you're stuck to that one format every time, not very flexible if you ask me.
No, the memory for the MySQL result could be released at any time - including directly after the while():
$string = '';
// the "caching" - basically load the data
while($row = mysql_fetch_array($result))
$string .= 'Data: ' . $row[0] . "<br />\n";
mysql_close($link); // close DB connection
// dump the string 4 times without hitting the DB
for($a = 0; $a < 4; $a++)
echo $string;
Even if you have a large HTML string - lets say 26k. Multiply that by the number of rows (20 in the example above), you'd only have 520k of memory being used to hold the string. And you're only concatenating to the string so you're not stressing the hardware out.
But more realistically, I'd predict 1k or less would make up the string in one iteration. Multiply that by 20 and you have 20k at most. Even the most low-end equiped web server should be able to handle this without blinking.
Granted, you start pushing 1000 rows and a 64mb RAM web server is going to start choking. But at the same time, you would be feeding the client browser 26mb+ of data, which doesn't make a huge amount of sense (and in this case, an alternative approach should be used if it even comes up).
The basic idea here is to build build your basic output while you have the record set. If you want, ditch the record set and then loop just the output data as you see fit.
The additional feature to this is you do have the start of a template system...