I’m starting a new project shortly and going to use coding standards. I’ve always written SQL statements like this:
$sql = sprintf("INSERT INTO users (name) VALUES ('%s')", $name);
I’m wondering if there is any performance gained by using one of these:
$sql = "INSERT INTO users (name) VALUES ('".$name."')";
$sql = "INSERT INTO users (name) VALUES ('$name')";
Also: Does this performance difference fluctuate with the addition of more “parameters” (as in the case of the first line of code) ?
Thanks.
Yes, this will increase performance. sprintf is an additonal function call, your string must be scanned for the %s which requires additional time.
The second option using the string concat operator (.) is faster, but the third alternative, just placing the string variable in a string is fastest due to other optimizations that PHP performs.
Anyway, while investigating how PHP deals with string concatination and how it performs is interesting you should never create sql queries like this, because it opens your code to SQL injections. apply mysql_real_escape() to your parameters first or use prepared statements.