When to use single quotes, double quotes, and backticks in MySQL

后端 未结 13 1031
一个人的身影
一个人的身影 2021-01-26 10:55

I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backt

13条回答
  •  灰色年华
    2021-01-26 11:40

    Backticks are generally used to indicate an identifier and as well be safe from accidentally using the Reserved Keywords.

    For example:

    Use `database`;
    

    Here the backticks will help the server to understand that the database is in fact the name of the database, not the database identifier.

    Same can be done for the table names and field names. This is a very good habit if you wrap your database identifier with backticks.

    Check this answer to understand more about backticks.


    Now about Double quotes & Single Quotes (Michael has already mentioned that).

    But, to define a value you have to use either single or double quotes. Lets see another example.

    INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, title1);
    

    Here I have deliberately forgotten to wrap the title1 with quotes. Now the server will take the title1 as a column name (i.e. an identifier). So, to indicate that it's a value you have to use either double or single quotes.

    INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, 'title1');
    

    Now, in combination with PHP, double quotes and single quotes make your query writing time much easier. Let's see a modified version of the query in your question.

    $query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
    

    Now, using double quotes in the PHP, you will make the variables $val1, and $val2 to use their values thus creating a perfectly valid query. Like

    $val1 = "my value 1";
    $val2 = "my value 2";
    $query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
    

    will make

    INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, 'my value 1', 'my value 2')
    

提交回复
热议问题