views:

78

answers:

3

Under what conditions do I need to single quote a variable in a Mysql statement in PHP?

A: 

In theory only varchars, texts, and BLOBs I think, but I say quote `em all. That has nothing to do with PHP by the way but only with the way you build your mySQL query, unless you mean something completely different.

Pekka
yeah, I too wrap every variable with single quote, be it varchar, text, int, boolean. It's just my personal preferences
silent
Also dates generally need to be quoted (except for unix style timestamps of course)
MindStalker
A: 

Not a direct answer, but I suggest a database class like Zend DB to interact with your database. I have found this to be a great way to abstract away some of the grunt work like figuring out what to do with variables.

For example:

$db->select()->from('users', array('uid'))->where('email = ?', $indata['email'])->where('actkey = 0')

Makes a cleaner query than building the same by hand, and also takes care of making those variables safe a lot better than I would.

Hope that's helpful info.

Ben Dauphinee
+1  A: 

If you put values directly in the query, as in SELECT * FROM users WHERE age > 25, then the single quotes are used only with strings. If you write SELECT * FROM users WHERE age > '25', the query works the same, but you are forcing MySQL to convert the string to an integer (if the field age is an integer), which is a not necessary operation.

kiamlaluno