Friday 15 June 2012

Building an SQL query in PHP: beware formulae

Got in trouble with this

$sql.=" SET commsq.attempts = $newNumberOfAttempts ";
$sql.=", commssitebasics.uNextContact =".$thisU+DEFINED_CONSTANT;
$sql.=", commssitebasics.somethingElse=2";
which produced a very odd result


SET commsq.attempts = 1 1, commssitebasics.somethingElse=2


what was happening? Answer: the first line is fine, but in the second line, PHP doesn't like the "+" and ignores everything before it, adding just the value of DEFINED_CONSTANT to the string. 


Answer - always put brackets around any appended value which is the result of a computation:


$sql.=", commssitebasics.uNextContact =".($thisU+DEFINED_CONSTANT);