In MySQL queries, how important is it to put backticks around a table name. Does it have something to do with security? Are MySQL injection attacks possible through the table name if the table name is created dynamically in PHP based on user inputs?
3 Answers
The backticks help you from accidentally using a name that is a reserved word in SQL for example. Take a table named "where", it's a stupid name for a table I agree, but if you wrap it in backticks it will work fine.

- 69,215
- 39
- 136
- 164
-
6This happens a lot when you have a field that's called `password`. – Alix Axel Dec 26 '09 at 11:25
-
Thanks, I learned something new. I'm guessing that marking a column named "order" with backticks would also avoid clashing with that reserved word. – eoinoc Apr 20 '12 at 14:59
-
1Do we need to use them in PostgreSQL also? – Yousuf Memon Dec 27 '13 at 03:09
In MySQL queries, how important is it to put backticks around a table name. Does it have something to do with security?
As far as backticks are concerned, I use them when there is name conflict between mysql-specifcs names and those from query.
Are MySQL injection attacks possible through the table name if the table name is created dynamically in PHP based on user inputs?
When ever there is a user input, you need to make sure that you filter and validate the input coming from the user. So yes there is security risk to it.
I would recommend you to use intval for numbers and mysql_real_escape_string function for any variables that you may use in your queries.
-
2To add to this answer... ANYTIME a variable is put into a SQL string, it's an opportunity for a SQL injection. And it doesn't matter where this data comes from, nothing is ever truly safe. Always escape everything. – TravisO Dec 27 '09 at 03:56
-
2Something I learnt recently, mysql_real_escape_string() doesn't escape backticks. If you're using a PHP variable as a table name, then it can be exploited. – Noodles Aug 04 '14 at 23:58
If you have a table name with the same name as a keyword, e.g. select, the following query will still work:
select * from `select`;

- 3,733
- 1
- 19
- 12