1

Okay, this may seem very basic but I am so tired of seeing everyone write their queries just a little differently, and I am looking for the generally accepted best practice.

I see in the PHP documentation that their query examples have no backticks for the table names:

mysqli_query($link, "SELECT Name FROM City LIMIT 10")

However, I see many people using backticks for the table names, like:

mysqli_query($link, "SELECT `Name` FROM `City` LIMIT 10")

So, which is it? I am leaning more towards not using them, because not only does the PHP documentation page linked to above not use them, I also found on this page it says: "Unlike some other languages, backticks have no special meaning within double-quoted strings."

Well, every MySQLi query will be contained within double-quotes, right? So, is there no point in using them?

MultiDev
  • 10,389
  • 24
  • 81
  • 148
  • The only time I've had to use the back-ticks is in specific software that requires it. Otherwise, I just omit them. – Michael Aug 13 '15 at 22:07
  • From the accepted answer there: "Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue." – Don't Panic Aug 13 '15 at 22:12
  • Read the documentation: http://dev.mysql.com/doc/refman/5.7/en/identifiers.html The second paragraph says everything. – axiac Aug 13 '15 at 22:13
  • If I were making an object that assembled a query, like an ORM, I'd have the code use backticks. I see backticks as pedantic accuracy, and to me that's fine for an object. Plus the object isn't going to "know" if one of the columns it is messing with is a reserved word or has something else funky about it, so I err on the side of caution. If I am writing the queries by hand, I usually forgo them for basically no better reason than laziness. – Chris Baker Aug 13 '15 at 22:14

1 Answers1

3

The backticks aren't there for the sake of the PHP interpreter, they're there for the MySQL parser. Backticks allow you to reference tables/fields that have spaces (or other characters that would normally result in a syntax error - e.g. -) in them. For instance, if you had a field called city name, you would have to use backticks around it when referencing it in your query.

From what I've seen, the generally accepted convention is to simply avoid using spaces in field names. Since backticks no longer serve a purpose, they are generally omitted (YMMV depending on employer).

Sculper
  • 756
  • 2
  • 12
  • 24