tags:

views:

67

answers:

4

Hi,

There's an open source application that does queries like so:

$db->query('SELECT item FROM table WHERE something='.$something);

This works fine, mysql runs the query however if I use exactly the same method I get an error, mysql is seeing it as "something = (value of $something)" and it's (rightly) complaining that (value of $something) is not a row. These applications both run on the same server and I've rooted through their code for hours but I cannot work out what is causing it.

$db->query('SELECT item FROM table WHERE something='.$something);

works in their application but fails in mine. Do I need to do something with the string I'm passing? I have no problem enclosing the variables properly, like:

$db->query('SELECT item FROM table WHERE something="'.$something.'"');

but I'd like to know what causes the difference.

+3  A: 

MySQL needs the string to be enclosed. The only thing I can think is that $something is an integer or a float.

adam
Aha! I think you might be right. How did I miss that, I can't believe it. Silly me... Thankyou.
citricsquid
A: 

You can pass numbers without quotes

SELECT ... WHERE id=5

but you have to mark string literals as such with quotes

SELECT ... WHERE id='abc'

see http://dev.mysql.com/doc/refman/5.0/en/string-syntax.html

VolkerK
A: 
  1. The code is bad bad bad if $something comes from the user/browser. That's call sql_injection error

  2. Send us the exact code statement and sql log so we can see what is happening

Larry K
of course the data has been sanitized before hand! It was just a silly mistake on my part, I'd overlooked the fact that numbers and strings are treated differently by mysql, mysql will take and handle numbers fine w/out being enclosed, but if I don't enclose a string it can't handle it. Thanks!
citricsquid
right, that's a really really bad practice. avoid this way of building sql queries and start using prepared statements: http://devzone.zend.com/article/686#Heading10, http://www.petefreitag.com/item/356.cfm
knoopx
A: 

Try this

$db->query('SELECT item FROM table WHERE something={$something}');

This will work

streetparade
In my opinion a comment would be nice if someone votes down, because there is a big learning process if someone says your faults. So that i can learn from my Faults ;-)
streetparade
I imagine you were voted down because braces {} are used to wrap complex variables such as class vars or array items in strings - they won't enclose the outputted variable though.
adam
Hy adam thank you for the Information.
streetparade