[KLUG Members] php and quotation marks

bill bill at billtron.com
Tue Sep 27 14:40:52 EDT 2005


On Tue, 2005-09-27 at 14:24, adam at morrison-ind.com wrote:
> >> Right use single outer quotes, always.
> > Just my experience here:  I used to do that and it was a problem.
> > Assume we're talking about displaying HTML.  If I start with single
> > outer quotes (') I often have to change the code later to contain a
> > variable.  If I started with single quotes it wouldn't display the value
> > of the variable.  Bummer.  I'd have to go back and change them to double
> > quotes, and then also change any other quotes they affected.  AAAARGH.
> 
> Use printf

printf is hard to read and easy to mess up.

Look at the example in this thread

$query = sprintf('UPDATE single SET category="%s", ques2="%s", ans2="%

oops word wrap

s", ques4="%s", ans4="%s", ques8="%s", ans8="%s", ques16="%s", ans16="%

oops word wrap

s", ques32="%s", ans32="%s", ques64="%s", ans64="%s", ques128="%s",
ans128="%s", ques256="%s", ans256="%s"',
  addslashes($category), addslashes$ques2), 

oops no opening parenthesis

addslashes($ans2),                
addslashes($ques4), 
  addslashes($ans4), addslashes($ques8), addslashes($ans8),
addslashes($ques16), 
  addslashes($ans16), addslashes($ques32), addslashes($ans32),
addslashes($ques64),
  addslashes($ans64), addslashes($ques128), addslashes($ans128),
addslashes($ques256),
  addslashes($ans256));

Quick now, are all the values in the right order?  Do you have too many
in the first part, not enough in the second?  They're hard to match
up.   Plus you have twice as many places to drop a comma or add an extra
quote (or forget a parenthesis).  

The original query, while tedious because he doesn't build it with
arrays, is still easier to read:

$query="UPDATE single SET
        category='$category', ques2='$ques2', ans2='$ans2',
ques4='$ques4', 
ans4='$ans4', ques8='$ques8', ans8='$ans8', ques16='$ques16', 
ans16='$ans16', ques32='$ques32', ans32='$ans32', ques64='$ques64', 
ans64='$ans64', ques128='$ques128', ans128='$ans128', 
ques256='$ques256', ans256='$ans256'

It's easy to see that category is being populated with $category and
ans32 matches with $ans32, etc.  If there were a missing field or a
missing value it would stand out.  If there were an ans512 missing it
would be easy to see.

Thus, printf makes it more complicated than it was to start with, more
likely to contain errors, and harder to debug.

Soooo, double quotes and escaping (\) when necesary is what I prefer
when I write code and GREATLY prefer when I modify it later.

kind regards,

bill


> 
> ______________________________________________________________________




More information about the Members mailing list