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

后端 未结 13 879
一个人的身影
一个人的身影 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:37

    The string literals in MySQL and PHP are the same.

    A string is a sequence of bytes or characters, enclosed within either single quote (“'”) or double quote (“"”) characters.

    So if your string contains single quotes, then you could use double quotes to quote the string, or if it contains double quotes, then you could use single quotes to quote the string. But if your string contains both single quotes and double quotes, you need to escape the one that used to quote the string.

    Mostly, we use single quotes for an SQL string value, so we need to use double quotes for a PHP string.

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

    And you could use a variable in PHP's double-quoted string:

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

    But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)

提交回复
热议问题