Why should we escape double quotes and NULL inside MySql queries? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Today, mysql_real_escape_string() is escaping single quotes AND double quotes
I understand that single quotes and backslash have special meaning so they need to be escaped if we want them to be interpreted for their literal meaning.
As far as I understand , double quotes are not allowed in mysql queries to represent strings(if this assumption is correct, is this the only reason to escape them ?) and we should use single quotes instead to represent strings.
And what about NULL? Looking for specific examples to understand why double quotes and NULL need to be escaped.
Just to add, I've already searched here on stackoverflow and I see most examples refer to single quotes which I already understand... But I need to understand the reasoning behind double quotes and I cannot find any examples for that...

In default mode, MySQL allows for string literals to be enclosed in single quotes OR in double quotes.
SELECT 'single', "double"
For compatibility with other DBMS, and just in case MySQL mode is set to ANSI_QUOTES, most SQL authors use single quotes to specify string literals. There's really no advantage to using double quotes. (And why write a query in a way that will cause the query to be "broken" when someone changes a variable in their MySQL server session.)
So, the short answer is that double quotes do not need to be escaped in all cases, e.g.
SELECT 'Bob cried "Wheeeee!"'
They do need to be escaped in some cases:
SELECT "Sue screamed \"Stop!\""
But it doesn't hurt to escape the double quotes in any case:
SELECT 'Bob cried \"Wheeeee!\"', "Sue screamed \"Stop!\""

From manual; The mysql client truncates quoted strings containing NUL characters if they are not escaped
If you want to insert binary data into a string column (such as a BLOB column), you should represent certain characters by escape sequences. Backslash (“\”) and the quote character used to quote the string must be escaped. In certain client environments, it may also be necessary to escape NUL or Control+Z. The mysql client truncates quoted strings containing NUL characters if they are not escaped, and Control+Z may be taken for END-OF-FILE on Windows if not escaped. For the escape sequences that represent each of these characters, see Table 9.1, “Special Character Escape Sequences”.
Ref: http://dev.mysql.com/doc/refman/5.0/en/string-literals.html#character-escape-sequences
And you don't need to escape double-quotes, but I think this is not a proper way while playing with strings.
# intead of this
INSERT INTO table (1, "John's cats")
# preferred by many programmer
INSERT INTO table (1, 'John\'s cats')
# but needs to escape here
"INSERT INTO table (1, \"John's cats\")"

Related

PHP mysqli query searching for backslashes [duplicate]

This question already has answers here:
How to search for slash (\) in MySQL? and why escaping (\) not required for where (=) but for Like is required?
(5 answers)
Closed 2 years ago.
I have an SQL query which searches for json strings, these json strings include backslashes within them to escape quotation marks.
The SQL query I am using works to find what I am looking for but I'm struggling to get a PHP mysqli query working due to having to have backslashes within the query which are literal and not escape characters, but also having to use backslashes to escape quotation marks within the mysqli query.
So the string I'm searching for is this, with the backslashes actually appearing within the string:
[insert=\"userform\",id=\"1\"]
The SQL query I use is:
SELECT id, name FROM `posts` WHERE content LIKE '%[insert=\\"userform\\",id=\\"1\\"]%' ESCAPE "|"
This works to find the rows I want by changing the default excape character. But then when I try to use the same query in PHP I have to escape the single quotes around the LIKE statement causing issues.
$mysqli->query('SELECT id, name FROM `posts` WHERE content LIKE \'%[insert=\\"userform\\",id=\\"1\\"]%\' ESCAPE "|"');
I'm trying to use mysqli_real_escape_string as I think that will do what I need, but haven't been able to get it right yet, what am I doing wrong?
It's because php escape character is backslash, you need to escape them too like.
$mysqli->query('SELECT id, name FROM `posts` WHERE content LIKE \'%[insert=\\\\"userform\\\\",id=\\\\"1\\\\"]%\' ESCAPE "|"');
A good solution to check it's to echo the query before execute to check if the final result is good.

how to escape strings that are meant for database column names with double quotes?

PHP's pdo:quote() escapes only single quotes, but sqlite needs backticks or double quotes for string to be interpreted as column name.
edit:
found this: Escaping column names in PDO statements
This is something you'd hope the data access layer would have a function for, but PDO doesn't.
Summary of the summary of the summary: gnnnnnnnnnnnh.
edit2: there was a request for it but I really don't understand why they dismissed it: http://pecl.php.net/bugs/bug.php?id=3442

SQL Query Help—Confused About Quotes and Concatenating

I'm trying to wrap my head around writing queries in SQL and I'm having some difficulty understanding this example that I've found.
$q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
."VALUES ('".$_POST["username"]."', "
."PASSWORD('".$_POST["password"]."'), "
."'".$_POST["email"]."')";
I guess I'm stumbling over the use of double quotes, single quotes, and the back-ticks. I compared this statement to the example on the W3 website and am just really confused as it seems much more complicated. Could you please explain to me what is going on in the above query? Thank you for your help!
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
The double quotes are used to define the elements that build your $q string. The single quotes identify strings within the SQL query that you are building and the backticks are used to escape object names in MySQL.
The double quotes surround the strings that will be a part of the query string. The dots between each double-quoted section are the concatenation operator. They are joining individual string pieces together.
You'll notice that there is a double-quote and dot before every $_POST[] array variable, and a dot and double-quote after.
e.g. " . $_POST["username"] . "
The first double quote ends the previous string section. The one at the end starts the next string section. Everything between the two dots is the POST variable. The reason the dots are necessary is because of the quotes around "username". In your W3 version they did not use quotes around the $_POST[] array key string (e.g. $_POST[firstname] and not $_POST["firstname"] or $_POST['firstname']) and so they did not need to use dots and quotes.
If you want to keep things simple, don't use the quotes inside of the $_POST[] variables and you won't have to use all those dots and quotes around them.
If you try version 1 without the dots and quotes the php parser will fail and you will see an error.
Backticks ` are to escape MySQL keywords (usually used for table and column names). Single or double quotes are required around any strings which are inserted.
Note that you should call mysql_real_escape_string on any string you're concatenating into a SQL query. Otherwise, it's possible to break out of quotes if $_POST also includes quotes. This can potentially be used to allow the execution of arbitrary SQL commands in what is known as a SQL injection attack.
The `back ticks` are optionally used to quote mysql field names, you will need them if you accidentally use one of mysqls reserved words to name a field - otherwise you don't need them.
When you enter a string into a field you have to 'quote it'.
The whole statement has to be quoted, but not clash with 2) above, hence the use of "double quotes".
Non scalar values such as arrays do not automatically expand, so you have to "drop out" . and . "back in" to PHP to build your string using concatenation sign a dot .
The backticks are a MySQL artifact in case you are using reserved words as your table/field names, and the single quotes delineate string literals in SQL. The double quotes are PHP-specific and separate strings in PHP. So, your query below would look like the following:
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('".$_POST["firstname"]."','".$_POST["lastname"]."','".$_POST["age"]."')";
One thing that the author above is doing is also breaking the PHP string into separate strings, probably to improve readability. MySQL server doesn't care about that.
There's actually a lot of unnecessary stuff in that first query. There are best practices to take into account but it could be re-written as such:
$q = "INSERT INTO dbUsers (username, password, email)
VALUES ('".$_POST["username"]."',
PASSWORD('".$_POST["password"]."'),
'".$_POST["email"]."')";
First thing: INSERT INTO dbUsers:
All this is doing is telling us what table we're inserting our data into.
(username, password, email)
Specifying the columns we're inserting into (order specific)
VALUES ('".$_POST["username"]."', PASSWORD('".$_POST["password"]."'), '".$_POST["email"]."')
Our values to be inserted (dependent on the order of the columns), then a terminating semicolon.
If you re-write this with hard coded values rather than concatenation, it would look like:
VALUES ('myUserName', PASSWORD('myPassword'), 'myEmail')
All of that should be self explanitory. Each value is contained within single quotes (') as they are strings. Then the password value is passed through the MySQL function PASSWORD which hashed the password for security purposes.
The double quotes are part of the PHP code, telling it that the items inside the double quotes are strings. They're not part of the SQL being built.
The single quotes are used to surround values in the resulting SQL. Ie, you're telling the database the value "bob" is used here. For some types of value (integers, boolean, etc) you don't need the single quotes. For many others (varchar, dates, etc), you need the single quotes.
The backticks perform much the same function as single quotes, except they're used around table names, field names, etc... rather than around actual values. They're used when the name in question wouldn't be interpreted by the database correctly there, for example if you had a field named count, since that's a keyword in SQL. As noted elsewhere, the backticks aren't necessary in your example, but many people put them in all the time because it doesn't hurt to have them; as a safety net, kindof.
To give a visible, simpler example
$name = "bob";
$sql = "SELECT * FROM `mytable` WHERE `name` = '" . $name . "'";
This would result in the $sql variable being
SELECT * FROM `mytable` WHERE `name` = 'bob'
As you can see, the double quotes are not part of the string.. they're just used in creating it. In the resulting SQL, the backticks surround the table/field names, and the single quotes surround the actual value bob.
As a complete side note, using the POST values directly in created SQL is dangerous as it allows for SQL injection attacks. The values should be escaped or a parametrized query should be used.

How to properly escape a string via PHP and mysql

Can someone explain what is the difference between using mysql_real_escape_string on a string or wrapping `` around the column.
For example "insert into table (``column``) values ('$string')"
or
$escapestring = mysql_real_escape_string($string);
"insert into table (column) values ('$escapedstring')"
What is the difference between these two and what should I use? Thanks.
There's a difference between the backtick ` and the single quote '.
The backtick is intended to escape table and field names that may conflict with MySQL reserved words. If I had a field named date and a query like SELECT date FROM mytable I'd need to escape the use of date so that when MySQL parses the query, it will interpret my use of date as a field rather than the datatype date.
The single quote ' is intended for literal values, as in SELECT * FROM mytable WHERE somefield='somevalue'. If somevalue itself contains single quotes, then they need to be escaped to prevent premature closing of the quote literal.
Those two aren't related at all (as far I know anyway)
From the manual : http://php.net/manual/en/function.mysql-real-escape-string.php
Escapes special characters in the
unescaped_string, taking into account
the current character set of the
connection so that it is safe to place
it in a mysql_query().
So essentially what it does is, it will escape characters that are unsafe to go into mysql queries (that might break or malform the query)
So o'reily will become o\'reily

MySql + InnoDB + PHP Single Quote Discrimination?

Okay, I've recently converted a number of tables to the InnoDB storage engine and I've been getting errors whenever I use a single-quote ' in the column list of the INSERT statement:
INSERT INTO 'Table' ('Col1', 'Col2') VALUES ('Val1', 'Val2')
When I tired using phpMyAdmin to generate a proper statement, it looked virtually the same, so I pasted it in my app, and it worked. Then my next statement had the same error so I started to get suspicious. After a bit of playing around I found that the problem was that the query needed a back-tick instead of single-quotes, but not for the whole thing.
INSERT INTO `Table` (`Col1`, `Col2`) VALUES ('Val1', 'Val2')
works, so it's not like MySql doesn't understand the single-quote. What is going on here? I also can't just leave the columns unquoted like before with MyISAM (ie: Table(Col1, Col2))
That's because single quotes denote string literals, whereas backticks denote database/table/column identifier escapes.
Removing backticks causes an error because TABLE is a reserved word, so in order to use it as a table name you have to include backticks.
You put single quotes around string values, and you use backticks around object names. The backticks are technically not necessary though unless that name of your table/column is a reserved word or has spaces/funny characters in it.

Categories