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

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

    If table cols and values are variables then there are two ways:

    With double quotes "" the complete query:

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

    Or

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

    With single quotes '':

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

    Use back ticks `` when a column/value name is similar to a MySQL reserved keyword.

    Note: If you are denoting a column name with a table name then use back ticks like this:

    `table_name`. `column_name` <-- Note: exclude . from back ticks.

提交回复
热议问题