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 backticks without any real thought.
Example:
$query = 'INSERT INTO table (id, col1, col2) VALUES (NULL, val1, val2)';
Also, in the above example, consider that table
, col1
, val1
, etc. may be variables.
What is the standard for this? What do you do?
I've been reading answers to similar questions on here for about 20 minutes, but it seems like there is no definitive answer to this question.
In combination of PHP and MySQL, double quotes and single quotes make your query-writing time so much easier.
$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";
Now, suppose you are using a direct post variable into the MySQL query then, use it this way:
$query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";
This is the best practice for using PHP variables into MySQL.
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')
In MySQL, these symbols are used to delimit a query `
,"
,'
and ()
.
"
or '
are used for enclosing string-like values "26-01-2014 00:00:00"
or '26-01-2014 00:00:00'
. These symbols are only for strings, not aggregate functions like now
, sum
, or max
.
`
is used for enclosing table or column names, e.g. select `column_name` from `table_name` where id='2'
(
and )
simply enclose parts of a query e.g. select `column_name` from `table_name` where (id='2' and gender='male') or name='rakesh'
.
Single quotes should be used for string values like in the VALUES() list.
Backticks are generally used to indicate an identifier and as well be safe from accidentally using the reserved keywords.
In combination of PHP and MySQL, double quotes and single quotes make your query writing time so much easier.
Besides all of the (well-explained) answers, there hasn't been the following mentioned and I visit this Q&A quite often.
In a nutshell; MySQL thinks you want to do math on its own table/column and interprets hyphens such as "e-mail" as e
minus mail
.
Disclaimer: So I thought I would add this as an "FYI" type of answer for those who are completely new to working with databases and who may not understand the technical terms described already.
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.)
It is sometimes useful to not use quotes... because this can highlight issues in the code generating the query... For example:
Where x and y are should always be integers...
SELECT * FROM table
WHERE x= AND y=0
Is a SQL syntax error... a little lazy but can be useful...
There has been many helpful answers here, generally culminating into two points.
AND as @MichaelBerkowski said
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.
There is a case though where an identifier can neither be a reserved keyword or contain whitespace or characters beyond limited set but necessarily require backticks around them.
EXAMPLE
123E10
is a valid identifier name but also a valid INTEGER
literal.
[Without going into detail how you would get such an identifier name], Suppose I want to create a temporary table named 123456e6
.
No ERROR on backticks.
DB [XXX]> create temporary table `123456e6` (`id` char (8));
Query OK, 0 rows affected (0.03 sec)
ERROR when not using backticks.
DB [XXX]> create temporary table 123451e6 (`id` char (8));
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '123451e6 (`id` char (8))' at line 1
However, 123451a6
is a perfectly fine identifier name (without back ticks).
DB [XXX]> create temporary table 123451a6 (`id` char (8));
Query OK, 0 rows affected (0.03 sec)
This is completely because 1234156e6
is also an exponential number.
There are two types of quotes in MySQL:
'
for enclosing string literals`
for enclosing identifiers such as table and column namesAnd then there is "
which is a special case. It could be used for one of above-mentioned purposes at a time depending on MySQL server's sql_mode
:
"
character can be used to enclose string literals just like '
ANSI_QUOTES
mode the "
character can be used to enclose identifiers just like `
SELECT "column" FROM table WHERE foo = "bar"
The query will select the string literal "column"
where column foo
is equal to string "bar"
The query will select the column column
where column foo
is equal to column bar
"
so that your code becomes independent of SQL modes(There are good answers above regarding the SQL nature of your question, but this may also be relevant if you are new to PHP.)
Perhaps it is important to mention that PHP handles single and double quoted strings differently...
Single-quoted strings are 'literals' and are pretty much WYSIWYG strings. Double-quoted strings are interpreted by PHP for possible variable-substitution (backticks in PHP are not exactly strings; they execute a command in the shell and return the result).
Examples:
$foo = "bar";
echo 'there is a $foo'; // There is a $foo
echo "there is a $foo"; // There is a bar
echo `ls -l`; // ... a directory list
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.
SQL servers and MySQL, PostgreySQL, Oracle don't understand double quotes("). Thus your query should be free from double quotes(") and should only use single quotes(').
Back-trip(`) is optional to use in SQL and is used for table name, db name and column names.
If you are trying to write query in your back-end to call MySQL then you can use double quote(") or single quotes(') to assign query to a variable like:
let query = "select id, name from accounts";
//Or
let query = 'select id, name from accounts';
If ther's a where
statement in your query and/or trying to insert
a value and/or an update
of value which is string use single quote(') for these values like:
let querySelect = "select id, name from accounts where name = 'John'";
let queryUpdate = "update accounts set name = 'John' where id = 8";
let queryInsert = "insert into accounts(name) values('John')";
//Please not that double quotes are only to be used in assigning string to our variable not in the query
//All these below will generate error
let querySelect = 'select id, name from accounts where name = "John"';
let queryUpdate = 'update accounts set name = "John" where id = 8';
let queryInsert = 'insert into accounts(name) values("John")';
//As MySQL or any SQL doesn't understand double quotes("), these all will generate error.
If you want to stay out of this confusion when to use double quotes(") and single quotes('), would recommend to stick with single quotes(') this will include backslash() like:
let query = 'select is, name from accounts where name = \'John\'';
Problem with double(") or single(') quotes arise when we had to assign some value dynamic and perform some string concatenation like:
let query = "select id, name from accounts where name = " + fName + " " + lName;
//This will generate error as it must be like name = 'John Smith' for SQL
//However our statement made it like name = John Smith
//In order to resolve such errors use
let query = "select id, name from accounts where name = '" + fName + " " + lName + "'";
//Or using backslash(\)
let query = 'select id, name from accounts where name = \'' + fName + ' ' + lName + '\'';
If need further clearance do follow quotes in JavaScript
Source: Stackoverflow.com