[GLLUG] PHP Concatinating Strings
Jeremy Bowers
jerf at jerf.org
Thu Feb 19 09:25:46 EST 2004
Ex Fed wrote:
>> I don't do PHP and am greatly surprised that PHP's mysql interface
>> doesn't seem to have a printf-like command like every other scripting
>> language I've seen. That lets you insert placeholders, pass in the
>> values, and let the library do the quoting, like this:
>
>
> PHP does in fact support PRINTF and SPRINTF
That's not what I was talking about, quite. In Python (for sure) and
Perl (I'm pretty sure), you can do something like the following psuedocode:
$connection = makeDatabaseConnectionToSomething()
$connection->execute("SELECT Record FROM Table WHERE SomeString = ?",
"T'Pal");
and the database structure will escape the string, *depending on the
database you connected to*. If you connected to a database that only
uses apostrophe for the string delimiter, it will result in
SELECT Record FROM Table WHERE SomeString = 'T\'Pal'
whereas if the database also allows quotes, it might return
SELECT Record FROM Table WHERE SomeString = "T'Pal"
You can't do that directly with sprintf. You *can* build something that
works like this based on sprintf but it can be tricky to get it right.
So I remain surprised that PHP doesn't seem to have this, and more
particularly that even the mysql_* functions didn't seem to have some
escaping built in (at least based on my quick scan). If I were working
with databases in PHP, one of the first things I'd do is try to kludge
something together that would outsource the escaping to all one
function, to make sure I didn't make any escaping mistakes. Otherwise
you're asking for it, because *everybody* forgets a function call now
and then, and when you don't get an error immediately, you may not
notice until it's too late. This will also make it easier to change
databases later if you want, which is a good thing; if you're doing
bog-simple queries anyhow, it's worth staying database independent.
More information about the linux-user
mailing list