What's wrong with increasing the memory limit?
Reminds me of some production PHP I saw once, returned the entire database (`SELECT * from 'db'`) and manually walked through it with a for() loop. It wasn't very efficient at scale.
If you're building SomeSimpleBasicSite.com and you do this, you're probably a bad programmer. If you're truly facing scalability problems, it's table stakes.
Based on your comments in this thread you're out of your depth, man.