1

I have this code which is partially shown here for brevity:

global $wpdb;
// creates jwp_bids in database if not exists
$table = $wpdb->prefix . "jwp_bids"; 
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE IF NOT EXISTS $table (
    `id` mediumint(9) NOT NULL AUTO_INCREMENT,
    `bid_amt` text NOT NULL,

When I originally typed the code, I used ' within the parentheses and the code would not run.

I then changed the Single Quote to a Backtick and the code ran perfectly.

Would someone please explain:

  • What is the proper term for the oddball quotes :)
  • Why are they used instead of ' ?
  • Is this only pertinent to MySQL? WP? Php?
  • Where can I find a technical reference for this sort of thing so I don't have to bug you fine folk?
  • 1
    What happens if you leave out the backticks entirely, does it still run? I'm pretty sure this is a MySQL nuance and it has to do with interpreting column names as Strings ( when using single quotes ) instead of identifying them as columns ( using backticks or nothing at all ). – Howdy_McGee Jan 4 '17 at 22:40
  • I'll give it a test to see. What's the best reference resource out there for MySQL where such things are illuminated? – James Jan 4 '17 at 22:55
  • Okay so it does work WITHOUT backticks. Technical reference that is good for such details? – James Jan 4 '17 at 23:49
6

Backticks and regular quotes (both single and double) have distinct meanings in SQL. Quotes indicate a literal string, whereas backticks are quoted identifiers. This isn't specific to WordPress, but rather a general way in SQL of quoting columns or tables.

For example, imagine you're running a query comparing two columns:

SELECT * FROM wp_posts WHERE post_name = post_title

If you compare with single quotes ('post_name' = 'post_title') this would compare the literal strings, which are never equal. However, with backticks, it would refer to the column.

Why use backticks at all? If a column is named the same as a reserved word in SQL, or contains a space, you need to quote it. For example, if you had a column called count, you'd need to quote that every time you refer to it, as COUNT() is a function (and hence, reserved word) in MySQL.

See also https://dba.stackexchange.com/questions/23129/benefits-of-using-backtick-in-mysql-queries

| improve this answer | |
  • 1
    "If you compare with single quotes ('post_title' = 'post_title') this would compare the literal strings, which are never equal." They look pretty equal actually. Maybe you wanted to say 'post_name' = 'post_title'? – Frhay Jun 25 '18 at 16:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.