insert and update escape charcter, simple and double quotes in the same time in a MySQL table - mysql

I am concerned about inserting text in a MySQl table w.
I have to insert/update text that contains characters such as / " and '
The escape character / could be inserted only if the NO_BACKSLASH_ESCAPES SQL mode is enabled. wich interfere with the characters " and ' see this link http://dev.mysql.com/doc/refman/5.1/en/string-literals.html#character-escape-sequences
If anyone can explain to is in earth the mysql_real_escape_string() I don't came to understated
I would like to find a pure mysql solution
I am not using php. What I am trying to do here is to "simulate " Content Management System: I am about to write a C# coded solution that manage the content in its different forms(article, category ,tag, etc..) and generate .html files, the MySQl database is local in my computer next i will upload the .html files to the server.
I did this to ensure that all my html pages are html valid and because I don't trust any existent solutions (not only when it concerns coding but in life in general)
Please help

each php db connection extension (mysql, mysqli, pdo) has a special way to safe query against sql injections, when you are using mysql extension, it's strongly recommended to use mysql_real_escape_string() function to make safe all variables used in query, it's most widely used function. i think there isn't any pure solution (when you are using mysql extension in php).
from php.net:
mysql_real_escape_string()-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().

Whatever string data can be inserted into SQL query, if formatted according to 2 rules
it is enclosed in quotes (preferably single ones)
it is passed through mysql_real_escape_string()
if both rules followed, there would be not a single problem with whatever characters, either slashes, quotes or anything.
According to your question, / has no special meaning in MySQL. It's \ that is escape character. It can be escaped by another backslash as well.
$str = 'slashes \ quotes \' or whatever " else symbols';
var_dump($str);
$str = mysql_real_escape_string($str);
$sql = "INSERT INTO table SET str='$str'";

Related

Getting error when inserting text value in MYSQL [duplicate]

The MySQL documentation says that it should be \'. However, both scite and mysql shows that '' works. I saw that and it works. What should I do?
The MySQL documentation you cite actually says a little bit more than you mention. It also says,
A “'” inside a string quoted with “'” may be written as “''”.
(Also, you linked to the MySQL 5.0 version of Table 8.1. Special Character Escape Sequences, and the current version is 5.6 — but the current Table 8.1. Special Character Escape Sequences looks pretty similar.)
I think the Postgres note on the backslash_quote (string) parameter is informative:
This controls whether a quote mark can be represented by \' in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it ('') but PostgreSQL has historically also accepted \'. However, use of \' creates security risks...
That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.
Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.
Standard SQL uses doubled-up quotes; MySQL has to accept that to be reasonably compliant.
'He said, "Don''t!"'
What I believe user2087510 meant was:
name = 'something'
name = name.replace("'", "\\'")
I have also used this with success.
There are three ways I am aware of. The first not being the prettiest and the second being the common way in most programming languages:
Use another single quote: 'I mustn''t sin!'
Use the escape character \ before the single quote': 'I mustn\'t sin!'
Use double quotes to enclose string instead of single quotes: "I mustn't sin!"
just write '' in place of ' i mean two times '
Here's an example:
SELECT * FROM pubs WHERE name LIKE "%John's%"
Just use double quotes to enclose the single quote.
If you insist in using single quotes (and the need to escape the character):
SELECT * FROM pubs WHERE name LIKE '%John\'s%'
Possibly off-topic, but maybe you came here looking for a way to sanitise text input from an HTML form, so that when a user inputs the apostrophe character, it doesn't throw an error when you try to write the text to an SQL-based table in a DB. There are a couple of ways to do this, and you might want to read about SQL injection too.
Here's an example of using prepared statements and bound parameters in PHP:
$input_str = "Here's a string with some apostrophes (')";
// sanitise it before writing to the DB (assumes PDO)
$sql = "INSERT INTO `table` (`note`) VALUES (:note)";
try {
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':note', $input_str, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
return $dbh->errorInfo();
}
return "success";
In the special case where you may want to store your apostrophes using their HTML entity references, PHP has the htmlspecialchars() function which will convert them to '. As the comments indicate, this should not be used as a substitute for proper sanitisation, as per the example given.
Replace the string
value = value.replace(/'/g, "\\'");
where value is your string which is going to store in your Database.
Further,
NPM package for this, you can have look into it
https://www.npmjs.com/package/mysql-apostrophe
I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe
eg. 'This is John's place'
Here MYSQL assumes two sentence 'This is John' 's place'
You can put 'This is John''s place'. I think it should work that way.
In PHP I like using mysqli_real_escape_string() which escapes special characters in a string for use in an SQL statement.
see https://www.php.net/manual/en/mysqli.real-escape-string.php

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.

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"

mysqli + ckeditor = escapes and breaking html

So I have been developing a little system in which, at a point, the user can type in some HTML into ckeditor, that HTML is then stored in a database (it's kind of a microCMS).
The problem is When using Mysqli, It inserts escape characters before and after " and ' in order to stop injection, logically, which breaks loads of HTML code.
for example
becomes
or somthing close to that, which breaks the code
Is there a way i can disable the injection prevention, or input it into the database another way ? Or mabi replace the /" when it is being taken from the database ?
Thanks
-jman6495
EDIT :
I have resolved the problem
I replaced the /" by " using the php str_replace function.
here's the code :
$pagecontent = str_replace('\"','"',$pagecontent);
echo $pagecontent;
thanks anyway
-jman6495
If you're seeing these characters when you fetch data back out you're somehow double-escaping the content. Check that you're only escaping it once, and doing it with the placeholder and not mysql_real_escape_string. You haven't fixed the problem. You've un-done the damage of a serious bug.
The purpose of SQL escaping is to insert the data correctly and reliably. For instance, O'Reilly should be O''Reilly for MySQL. The actual content in the database should be O'Reilly regardless of quoting.