Tuesday, December 16, 2008

Escaping SQLite strings

So that last few days have been an annoying trail of tears for me in trying to find out exactly what is supposed to be done to escape strings so that they can be safely inserted into a SQLite database.

Google revealed unto me that PHP users should make use of the sqlite_escape_string function. But what does it do?

Looking at the PHP code revealed the answer about the same time the IRC channel (#sqlite on Freenode) did: the sqlite3_mprintf function, which is similar to the C++ printf function.

Apparently the most reasonable way to escape your strings is by doing something like this:

strMyEscapedString = sqlite3_mprintf("%q", strMyString);

What this formatting function does to strings passed in using %q, I don't know (other than doubling up single quotes). But it appears to be the Right Way To Do It.