3

Possible Duplicate:
MySQL - when to use single quotes, double quotes, and backticks?

Question 1

Why does this work?

"SELECT `id` FROM `table` WHERE x= '".$y."'"

but not this?

"SELECT `id` FROM `table` WHERE 'x' = '".$y."'"
                                ^ ^
                              Notice the extra single quotes

Question 2 Is it better to do id over `id` (with the weird quotes)? Or is it because that double quotes make it interpret as a variable?

Community
  • 1
  • 1
Wulf
  • 163
  • 9
  • What that really needs is some [proper SQL escaping](http://bobby-tables.com/php). You should **never** be inserting user data directly in a query. Use placeholders or there could be severe consequences. – tadman Dec 25 '12 at 04:10

1 Answers1

6

because the server reads x as a value as it is wrap with single quote. backtick escapes a reserved keyword used within the query, usually it is used to wrap around columnNames and tableNames.

in your query,

SELECT `id` FROM `table` WHERE 'x' = '$y'

x there is not a column but a string value.

for question 2, you can eliminate those backticks around id since it is not a Reserved Keyword, here is a full list of reserved keywords in MySQL

As a sidenote, the query is vulnerable with SQL Injection. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

Community
  • 1
  • 1
John Woo
  • 258,903
  • 69
  • 498
  • 492