How to escape ' (apostrophe) in mysql? - mysql

When i am reading some text from an Xml and putting it to the database i am getting a error if the text contains '(apostrophe) . How to overcome this problem while i am inserting into the DB.

Where ever the apostrophe is add a \ (backslash) before it. Using your text editor to do a find and replace all for ' to \' should work. BE CAREFUL not to mess up the XML structure.
ex.
John's
Needs to be
John\'s
You can also use PHP or C# to escape it for you also.
Here is the PHP function.

You should always escape you input data with whatever language-specific methodology you have for doing so. For MySQL the escape character is \. Another alternative is to use prepared statements with parametrized inputs. This would eliminate the need to escape the single apostrophe.
My guess is that you also have a significant SQL injection vulnerability with the way you are doing things. If you are not even escaping your input values or using parametrized prepared statements, then one could easily inject malicious code into the XML.

I don't know what language or method you're using for your import. Typically it's the backslash character, \ . So you would need to replace 's with \'. Make sense?

From 9.1.1 String Literals in the MySQL reference:
There are several ways to include quote characters within a string:
A “'” inside a string quoted with “'” may be written as “''”.
A “"” inside a string quoted with “"” may be written as “""”.
Precede the quote character by an escape character (“\”).
A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a string quoted with “'” needs no special treatment.
Thus, the given string foo'bar can be written in MySQL1:
'foo''bar'
'foo\'bar'
"foo'bar"
While the above addresses the primary question, use placeholders (aka prepared statements) - look up the correct method per language/adapter. Placeholders eliminate the need to quote (which prevents mistakes introduced by custom logic) and prevent against many cases of malicious SQL injection.
1 The syntax chosen by MySQL differs from other common SQL implementations; this syntax is not universal.

Related

two back slash in SQL procedure with Regular expression

i'm working on a SQL procedure where i came across a Regular expression which contains this piece -
REGEXP '\\s*count\\s*\\('
i do not understand why there are two backslash ? what can be inferred from this code.
Backslash is processed at multiple levels.
It's the escape prefix in regular expressions: it makes special characters like . and ( be treated literally, and is used to created escape sequences like \s (which means any whitespace character).
But it's also the escape prefix in string literals, used for things like \n (newline) and \b (backspace). So in order for the regular expression character to get a literal backslash, you need to escape the backslash itself.
This is common in many programming languages, although a few have "raw string literals" where escape sequences are not processed, specifically to avoid having to double the slashes so much.

MYSQL commands and Encoding

I will use PhP notation for variables to make life easy.
Suppose the database is UTF-8, and the client is set to UTF-8.
There are two sides to the question. Knowing that the ASCII for ' (quote) is 39 decimal:
Client Side
When the query variable, $title, is escaped, using function such as real_escape_string(), will the function escape all bytes that have value of 39 separately? Or will it see if the byte of value 39 is a part of UTF-8 symbol?
Server Side
SELECT * from STORIES WHERE title = 'Hello'
What does MYSQL assume the query encoding to be? This includes the part:
SELECT * from STORIES WHERE title = '
Then if a $filteredTitle happens to have the byte 39 in it which is part of a UTF-8 symbol, how does MYSQL know that it is not a quote?
Let's look at two issues.
When providing a SELECT statement, strings must be "escaped". Otherwise, there would be syntax problems with quotes inside quotes. In particular ', ", and \ must be preceded by a backslash to avoid confusion. mysqli_real_escape_string() provides that function. (Don't use mysql_real_escape_string(), it belongs to the deprecated mysql_* API.) No "un-escaping" is needed when you SELECT the string.
The ascii apostrophe (decimal 39, hex 27, sometimes called "single quote") is commonly used in many programming languages for quoting strings. A long list of utf8 "quotes" can be found here.

Too many characters in character literal while converting HTML Tag to Entity reference

I have generated an HTML tag through C# code. I am able to render correctly in the text area. When I googled it, I found this. To render the HTML tags in the text area, we need to convert the '<','>' into HTML entity references. But when I am trying to replace using String.Replace, it throws an error: Too many characters in character literal
.
string psHtmlOutput="<html><body><table border='0' cellspacing='3' cellpadding='3'><tr><th> Name </th><th>DomainName</th><th>DomainType</th><th>Defualt</th></tr><tr><td>india.local</td><td>india.local</td><td>Authoritative</td><td>True</td></tr></table></body></html>";
psHtmlOutput.Replace('>','>');
psHtmlOutput.Replace('<','<');
Error: Too many characters in character literal
Please help; how can I proceed?
The String.Replace method has two overloads:
One that operates on Strings.
One that operates on Chars.
In C#, single quotation marks are used to specify Char literals. Because you have used single quotes, the second overload of the method has been used. However, your second argument is not a valid character literal because > is not a single character.
So if you actually want to replace the character with a string, just use the overload that takes strings:
psHtmlOutput.Replace(">", ">");
psHtmlOutput.Replace("<", "<");

Escaped quote as the value of a field crashes my sql script

I have the following dml sql (generated by mysql wb):
INSERT INTO `status_need` VALUES (1,1,1,'famille cherchant une autre famille (pour garde partagée ou sortie d\'école)'),(2,1,2,'famille cherchant professionnelle de la garde d\'enfants'),(3,2,1,'professionnelle de la garde d\'enfants cherchant enfants à garder');
When I run it from java, it raises an error probably because of the apostrophe/quote within the value of the field.
I am not sure why that is because the quote is escaped by a backslash and what is more, this SQL was generated by mysql itself.
Can anyone please let me know how to solve this problem?
I'm guessing that your Java code has a string literal that looks like this:
"INSERT INTO `status_need` VALU...ie d\'écol..."
?
The reason that doesn't work is that in Java, inside a string literal, \' means '. You need to escape the backslash \ by writing \\ instead:
"INSERT INTO `status_need` VALU...ie d\\'écol..."
(Or, as danihp says, you can sidestep the issue by writing '' instead of \': MySQL supports both ways of escaping a single-quote inside a single-quoted string.)
Quoting mysql documentation:
There are several ways to include quote characters within a string:
A “'” inside a string quoted with “'” may be written as “''”.
A “"” inside a string quoted with “"” may be written as “""”.
Precede the quote character by an escape character (“\”).
A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a string quoted with “'” needs no special treatment.
But the right answer is that you should look for a way that java make this for you. Somethink like real_escape php function. See : http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html
The recommended approach is mostly use prepared statements. You may refer to below link
http://lists.mysql.com/java/5469
Also replacing all occurrences manually may have strange results. For this please refer to below blog explantion.
http://www.bartbusschots.ie/blog/?p=141

Sanitizing MySQL user parameters

What are the dangerous characters that should be replaced in user input when the users' input will be inserted in a MySQL query? I know about quotes, double quotes, \r and \n. Are there others?(I don't have the option of using a smart connector that accepts parameters so I have to build the query myself and this will be implemented in multiple programming languages, including some obscure ones so solutions such as mysql_real_escape_string in PHP are not valid)
mysql_real_escape_string() from mysql.com docs:
The string in from is encoded to an escaped SQL string, taking into account the current character set of the connection. The result is placed in to and a terminating null byte is appended. Characters encoded are NUL (ASCII 0), “\n”, “\r”, “\”, “'”, “"”, and Control-Z (see Section 8.1, “Literal Values”). (Strictly speaking, MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. This function quotes the other characters to make them easier to read in log files.)
mysql_real_escape_string() is character set aware, so replicating all its abilities (especially against multi-byte attack issues) is not a small amount of work.
From http://cognifty.com/blog.entry/id=6/addslashes_dont_call_it_a_comeback.html:
AS = addslashes()
MRES = mysql_real_escape_string()
ACS = addcslashes() //called with "\\\000\n\r'\"\032%_"
Feature AS MRES ACS
escapes quote, double quote, and backslash yes yes yes
escapes LIKE modifiers: underscore, percent no no yes
escapes with single quotes instead of backslash no yes*1 no
character-set aware no yes*2 no
prevents multi-byte attacks no yes*3 no
What languages do you need to support? It is much better to use a language's built-in sanitization than to write your own.
Edit: Looking at mysql_real_escape_string on php.net:
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.