How to escape single & double quotes in MySQL select? - mysql

select name from movies where id = 1; gives me
name
----------
How the 'A' Stole Christmas
How would I select in order to get
name
----------
How the \'A\' Stole Christmas
I can use replace(title,'\'','\\\'') which turns ugly since I need to do it twice one for single & double quote, Curious to know if there is cleaner approach

Struggling with escaping characters is a sign that you may be unnecessarily converting strings manually as data flows through different systems. The question I would ask is whether it is necessary to have escaped strings for your requirements.
When constructing and executing your queries you should use bind variables which removes the need to quote strings to build up your Sql queries and minimizes the risk of Sql injection security issues.
See http://php.net/manual/en/mysqli-stmt.bind-param.php
Once you have Sql results in a variable or PHP structure it is often better to find functions/libraries such as JSON functions described at https://coderwall.com/p/p2kumg/json_encode-vs-serialize-with-php-arrays
And of course there's http://www.w3schools.com/php/func_string_addslashes.asp as mentioned by D4V1D as a comment.
Edit ...
There also appears to be a Mysql QUOTE() function that does what you are asking.
See http://www.w3resource.com/mysql/string-functions/mysql-quote-function.php

Related

Save json_encode string to mysql db

I was save this string to DB
{"form_5_check":"N\u00e1kladov\u00e9 stredisko"}
But in mysql db is this string:
{"form_5_check":"Nu00e1kladovu00e9 stredisko"}
Pls where are "\" lost ? Thanks a lot
MySQL treats the backslash character as an escape character. If you did something like this:
query = "INSERT INTO foo (json) VALUES ('" + json + "');
you have basically three problems:
the single backslash you have will get interpreted as an escape character, not as content; unless the next character is a quote or another backslash, it will have escaped nothing, and silently disappear.
if your json contained any single quotes, and you are lucky, you will get a syntax error, as the quote that was supposed to contain the value will be closed, and gibberish that SQL can't parse follows.
if your json contained any single quotes, and you're not lucky, you're now a victim of SQL injection attack, the most infamous example being XKCD's.
To avoid all that, make sure that your data is properly sanitised before it hits the database. This can be done in two ways:
The manual, and error-prone way includes always remembering to escape any characters that need it any time you insert a string into a query. This differs between databases. Some databases want a backslash before quotes, while some prefer doubling the quotes and doing nothing to backslashes. Some allow both. Many languages and/or database access libraries have functions that do this in a way appropriate for the database.
The automated, foolproof and very much preferred way is to use parametrised queries and prepared statements that do this for you in a transparent and easy-to-use way. You do not have a specific language tagged, so I can't give you the solution, but the Bobby Tables site has answers for many commonly used programming languages.

Query binding adding slashes.. prevents me from doing searches

I am trying to search a store by its name, and when using mysql data binding, it adds a slash in between and prevents me from searching for the store name
The store name is Jimmy's Pita
When I run the query it looks like this
SELECT * FROM stores WHERE store_name = 'Jimmy\'s Pita'
But the store name in the database looks like this ... 'Jimmy's Pita & Poke'
What can I do to fix this issue?
Any help would be really appreciated!
This is to do with escaping. When you specify using single quotes you must escape other single quotes, as in:
'Jimmy\'s Pita'
If you use different quotes, which MySQL allows by default, then you can do this instead:
"Jimmy's Pita"
Both of these are equivalent and in both cases the data saved is:
Jimmy's Pita
The backslash is only there to deal with escaping issues. It is not literally part of the data.
When it comes to searching you may want to use the MySQL full-text index so you can get "close enough" matches, like searching for "jimmys pita" and so on.

SQL - Changing " or ' in SQL so adding text is easier

So I am building a database of all my text messages to get information about my habits and I'm having trouble importing the contents of the messages. Whenever there are apostrophes (often) or quotation marks (not as rare as you might think), I get syntax issues.
Is there a way to make MySQL use something other than " or ' to encase strings (specifically, the field is a VARCHAR). If I could use a ~ or some other rarely used character in text messaging my life would become a whole lot easier.
Preferably you should use parameterised queries, then your database connector takes care of sending the strings to the database in the correct way.
If you need to build the queries by concatenating the values into a query, you need to escape the strings correctly to make them string literals in the SQL code.
Stick to one delimiter for strings, don't use apostrophes around some strings and qoutation marks around others, that only makes it harder to escape them correctly. I suggest that you use apostrophes, as that is what the SQL standard specifies.
To escape the strings correctly to be a string literal delimited by apostropes, you should:
Replace all backslashes by double backslashes, then
Replace all apostrophes by a backslash and an apostrophe
For example, to make the string It's an "example" with a backslash(\). into a string literal, it should end up like this in a query:
insert into Table (txt) values ('It\'s an "example" with a backslash(\\).')
Note: This is a correct way to escape strings for MySQL. Other databases may use different characters for escaping and need other characters to be escaped, so using this for any other database may fail, or even worse open up for SQL injection attacks.

smart solution of SQL injection

These is one keyword confliction issue in the query module of my application,please see if you can tell me a smart solution.
First,In query module,each query condition contains three parts in UI:
1.field name,its value is fixed,e.g origin,finalDest...
2.operator,it is a select list which includes "like","not like","in","not in","=","!="
3.value,this part is input by user.then in back-end,it will assemble the SQL statement according to UI's query criteria,e.g if user type/select following stuff in UI
Field Name Operator Value
origin like CHI
finalDest in SEL
In back-end,it will generate following SQL:
select * from Booking where origin like '%CHI%' and finalDest in ('SEL').
But there is a bug,e.g if user type some of special symbol in "value",e.g "'","_" etc,it will lead to the generated SQL also contain ' or _ ,e.g:
select * from Booking where origin like '%C_HI%' and finalDest in ('S'EL').
you could see as there is special symbol in "where" block,the SQL can't be executed
For this problem,my solution is add escape character "/" in front of the special symbol before executing it,but what i know is just ' or _ that would conflict with the SQL keywords,do you know if there is any others similar symbol that i need to handle or do you guys have any better idea that can avoid the injection
Sorry,forgot told you what language i am using,i am using java,the DB is mysql,i also use hibernate,there are a lot of people said why i didn't use PreparedStatement,this is a little complex,simply speaking,in my company,we had a FW called dynamic query,we pre-defined the SQL fragment in a XML file,then we will assemble the SQL according to the UI pass in criteria with the jxel expression,as the SQL is kinda of pre-defined stuff,i afraid if change to use PreparedStatement,it will involve a lot of change for our FW,so what we care is just on how to fix the SQL injection issue with a simple way.
The code should begin attempting to stop SQL injection on the server side prior to sending any information to the database. I'm not sure what language you are using, but this is normally accomplished by creating a statement that contains bind variables of some sort. In Java, this is a PreparedStatement, other languages contains similar features.
Using bind variables or parameters in a statement will leverage built in protection against SQL injection, which honestly is going to be better than anything you or I write on the database. If your doing any String concatenation on the server side to form a complete SQL statement, this is an indicator of a SQL injection risk.
0 An ASCII NUL (0x00) character.
' A single quote (“'”) character.
" A double quote (“"”) character.
b A backspace character.
n A newline (linefeed) character.
r A carriage return character.
t A tab character.
Z ASCII 26 (Control+Z). See note following the table.
\ A backslash (“\”) character.
% A “%” character. See note following the table.
_ A “_” character. See note following the table
Reference
Stack Similar Question
You should use bind variables in your SQL statement. As already mentioned this is done with PreparedStatements in Java.
To make sure, only valid column names are used, you can validate the input against the database. MySQL provides schema information like columns of each table as part of the INFORMATION_SCHEMA. For further information, check the MySQL documentation:
"The INFORMATION_SCHEMA COLUMNS Table"

Is there a mySQL equivalent to Postgresql's "Dollar-Quoted String Constants"?

In postgresql, it's possible to use "Dollar-Quoted String Constants" to avoid escaping single quotes in constant strings:
Without Dollar-Quoted String Constants:
'Jeff''s table'
With Dollar-Quoted String Constants:
$$Jeff's table$$
Is there a MySQL equivalent?
On edit: I'm not looking for a way to sanitize inputs, I'm looking for a way to make queries that generate sql easier to read.
No, because it doesn't really work. An attacker just addes a pair of dollar signs to their injection attempt instead.
The correct way to handle this is a system that uses real query parameters, such that the parameter values are never substituted directly into a query string. This is also generally better for performance because the db can do a better job caching the execution plan you don't end up building string dynamically, which tends to be slow in modern languages.
Not having excess concatenation statements greatly improves the readability of the code, as well. Instead of this:
sql = "SELECT * FROM MyTable WHERE Column1=$$" + somevarialbe + "$$ AND Column2=$$" + OtherVariable";
it's just this:
sql = "SELECT * FROM MyTable wHERE Column1=#Value1 AND Column2=#Value2";
Hmm... Okay, I can see some limited utility for this feature now.
Imagine a ticket tracking system with a stored procedure to get open tickets. You might actually hard-code the literal 'open' into the where clause of the query. Not that this would be a good design — ticket status should be in a table with it's own key, so that you'd hardcode the key rather than the text. But it plants the seed for something valid and more-complicated.
You can enclose your string in double quotes instead, e.g.
"Jeff's table"
Note: If this doesn't work, it means that you've got ANSI_QUOTES SQL mode turned on. The MySQL docs say:
If the ANSI_QUOTES SQL mode is enabled, string literals can be quoted only within single quotation marks because a string quoted within double quotation marks is interpreted as an identifier.