I always hated writing big queries in php by concatenating strings. Its very ugly and can get hard to follow with quotes and double quotes. Heredoc to the rescue. If you’re unfamiliar with heredoc, its basically a syntax with php (and some other perl based languages) to type blocks of text without having to escape characters. This can also be useful when writting our big multi join/union/where/group/having/order by query. Here’s how:
$sql=<<<EOD
select *
from pages
where pagename='$pn'
EOD;
You have to be very cautious though with spacing. Heredoc does not like spaces on the lines with the opening and closing identifiers (EOD in this case), however everything in between can be spaced to suit your fancy. Give it a shot!
Related posts:


4 Responses
Shad
09|Apr|2008 1Sounds like you miss cfquery. Maybe you should check out some PHP ORM’s and make a few posts on your experience.
trent
10|Apr|2008 2I like ColdFusion’s cfquery and love Django’s ORM. PHP does lack in that area, but its availability is what propels it despite this. Are you a PHP man yet?
Chris Jordan
16|Apr|2008 3Hey Trent, nice tip! I’ve been forced into some PHP coding recently, and this was a pet peeve of mine. I used to use heredocs all the time when I did lots of Korn Shell scripting for an old employer of mine back in the 90′s. I’ve got some client’s who just can’t afford CF (a concern soon to be quashed with OpenBD) and PHP has ruled the day for those clients, so I’ve had to adapt.
Anyway, thanks for the tip!
Gilberto Albino
02|Jun|2008 4Hey, Trent!
Very good blog!
I am impressed with your approach:
Simple and objective!
And, about HEREDOC,
hey! I haven’t thought about it yet!
So simple a solution for great clean code!
Nice day!
Leave a reply