By pan69 on
HI guys. I seem to be having a problem with db_query and I can't seem to figure out what the problem is. I'm sure I'm doing something wrong, I just don't know what that is.
Oke this code seems to work:
$items = db_query('SELECT nid FROM {node} WHERE type="news"');
But that doesn't seem right. First of all, I have to hard code the "news" in there which is supposed to be bad practice. So I want to use this code instead:
$items = db_query('SELECT nid FROM {node} WHERE type=%s', 'news');
But that doesn't work, even if I make the second parameter to db_query '"news"'.
I'm sure I'm doing something wrong. If someone could give me a pointer in the right direction, that would be great!
Thanks,
Luke
Comments
Surround embedded strings with quotes
If the node type will always be "news" and doesn't come from user input, then hard coding as you did in the first statement is totally cool and fits within "best practices".
Use variable substitution for anything that derives from user input or is not 100% within your control.
To get your 2nd statement working correctly, surround the %s with quotes, like this:
That tells your database server that the value in between the quotes is a string.
Thanks for that. I was
Thanks for that. I was assuming that the %s would do that for me since it's always meant to be a string. Silly me. :)