MySQL LONGTEXT doesn't accept an apostrophe ' - mysql

I was building a portal for my college with posting messages option. Hence I used LONGTEXT to store the message in mysql. But somehow the LONGTEXT doesn't accept the apostrophe mark.
It gives following error whenever I post some sentence with apostrophe mark:
"Error: You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 's open singles
tournament, will Electrical be able to maintain their dominance o' at line 1"
PS: not in the escape string, but in <textarea>, if I input the apostrophe mark it gives the error!

Escape it with a backslash like
SELECT 'This is a escape \' quote test';
EDIT
If you are taking information directly from a web form and inserting it into a data base - this is a massive security risk. This is how SQL injection is done.

You have two problems.
You copied the value of the long text into your 'query' (presumably an INSERT or UPDATE statement, though it could simply be the value to compare with in a SELECT).
You did not notice that the first unescaped single quote after the opening quote terminates the string.
Given that you are using MySQL, I believe you have two options on escaping:
Standard SQL (applies to most, if not all, SQL DBMS): use two consecutive single quotes to insert one:
'''' -- Insert a string consisting of one single quote
'He said, "Don''t do that!"' -- A string containing a single quote
MySQL (may also be an option elsewhere, but not every SQL DBMS will recognize it): use a backslash to escape the single quote:
'\'' -- As above
'He said, "Don\'t do that!"' -- Also as above
There may also be functions you can use to do the escaping for you - depending on the host language you are using. However, the preferred way to get values into an SQL statement, especially ones that might contain random characters, is to use placeholders. The mechanics depend on the host language in which you are embedding the SQL, but the general idea is:
The raw SQL string looks like: INSERT INTO SomeTable VALUES(?, ?, ?);
You PREPARE the statement, more or less explicitly.
When you execute it, you provide the data as parameters to the EXECUTE.
Or, if it is a SELECT statement, you PREPARE it, you DECLARE a cursor for it, then you OPEN the cursor and provide the parameter values at that time.
In one SQL-based language (IBM Informix 4GL):
DEFINE a INTEGER, b DECIMAL(10,2), c VARCHAR(250)
LET a = 1
LET b = 99999999.99
LET c = 'He said, "Don''t do that!"'
PREPARE p1 FROM "INSERT INTO SomeTable(a,b,c) VALUES(?, ?, ?)"
EXECUTE p1 USING a, b, c
PREPARE p2 FROM "SELECT * FROM SomeTable WHERE c = ?"
DECLARE c2 CURSOR FOR p2
OPEN c2 USING c
Note that if you do not use placeholders, you have to be extremely careful not to fall into the SQL Injection trap.

use the backslash character to escape the string:
"Carlito\'s Ways"
You may need to unescape later, but PHP has a built-in function for that.
insert into customers(firstname, lastname)
values ('Bill', 'O\'Connor');

I'm assuming you need to escape your apostrophes with a backslash character (\), but it would also be intuitive to provide the SQL query that you attempted to execute in order for people to help you further.

Related

MySQL statement fails due to encoded quotes

Following on from this question MySQL database contains quotes encoded and unencoded and it's breaking javascript
I am executing this MySQL query:
DELETE FROM `example` WHERE `name` = ''12345''
However it fails because the value in the database is '12345'. It seems that old data in the database has a mixture of encoded and unencoded quotes. Is it safe to to update all ' to ' in the database?
In most cases (yours included), store text without any "encoding". That is, do not store htmlentities, store the actual characters, do not store unicode 'codes', store the actual characters, etc.
Do likewise for anything you need to compare to what is in the database.
You will, however, have to escape strings when building SQL statements. Otherwise, you can't get quotes (in text) inside quotes (that are part of the SQL syntax.
That is, you will end up with this SQL when searching for that Irishman:
... WHERE `name` = 'O\'Brian'

DECODE Function in SQL

I am trying to insert the following query and I get syntax errors. Can you please help me with the below query:
INSERT INTO ABCTABLE (COLUMN1) values ('DECODE(MDSE_CD,NULL,'0000000000000000',LPAD(TO_NUMBER(MDSE_CD,'16',' '))');
Since you haven't really said anything other than "this query doesn't work, fix it", I have to take a stab in the dark what you want. From the query you have, I'm therefore guessing you want the value of the column to be DECODE(MDSE_CD,NULL,'0000000000000000',LPAD(TO_NUMBER(MDSE_CD,'16',' '))
In which case, you have to escape the single quotes within your string literal. Do this by doubling up the quotes:
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('DECODE(MDSE_CD,NULL,''0000000000000000'',LPAD(TO_NUMBER(MDSE_CD,''16'','' ''))')
Try properly escaping the inner single quotes
INSERT INTO ABCTABLE (COLUMN1)
VALUES ('**DECODE**(MDSE_CD,NULL,''0000000000000000'',**LPAD**(TO_NUMBER(MDSE_CD,''16'','' ''))');
The problem is the use of quote marks. If we tried to break up your query it would look like this:
INSERT INTO ABCTABLE
(COLUMN1)
values
(
'DECODE(MDSE_CD,NULL,'
0000000000000000
',LPAD(TO_NUMBER(MDSE_CD,'
16
','
'))'
);
...which clearly makes no sense.
You might want to think about how to escape a quote mark inside a string.
Sql Server:
DECOD function in Sql Server can be replaced with CASE construct
LPAD function in Sql Server has not a direct correspondence but you can pad your string using string manage function REPLACE (replicate a character a number of specified times)
My Sql:
DECOD function in MySql can be replaced with CASE construct
LPAD function in MySql is existent
What do you want to store... a string literal 'DECODE(MDSE...))', or did you want to call a function to derive a value?
To store a string literal containing single quotes, you need to "escape" each single quote within the string with an extra single quote, e.g.
O'Hare Int'l ==> 'O''Hare Int''l'
The DECODE function is Oracle specific. That expression will need to be rewritten using different functions in both MySQL and SQL Server.

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"

passing string in a query to MySQL database in MATLAB

I am using MySQL with MATLAB, and I want to get a name from user, and pass it to the table in mySQL, but it is rejecting a variable name in place of string
var_name=input('enter the name:');
mysql('insert into table (name) values (var_name)');
Any suggestions?
FIRST read the comments to this question - you don't want to shoot yourself in the foot with a mysql injection security problem. You have been warned. Now, to solve your current problem, without addressing the security risk of the whole approach when it comes to building SQL queries, read on...
In principle Amro has already posted two solutions for you which work, but since you have not accepted it I'll explain further.
Your problem is that you are not telling MATLAB which parts of your query it should interpret as a literal string, and which parts it should interpret as a variable name. To solve this, you can just end the literal string where appropriate, i.e. after the opening brackets, and then start them again before the closing brackets.
In between those literal strings you want to add the contents of your variables, so you need to tell MATLAB to concat your literal strings with your variables, since the mysql command probably expects the whole query as a single string. So in essence you want to take the string 'insert into table(' and the string saved in the variable name and the string ') values (' and so on and glue them into one big string. Amro and Isaac have shown you two solutions of how to do this without much explanation:
horzcat('insert into table (', name, ') values (', var_name, ')')
uses the function horzcat, while
['insert into table (' name ') values (' var_name ')']
uses the fact that MATLAB treats strings as arrays of characters so that you can just use square brackets to form a large array containing the strings one after the other.
The third solution, offered by Amro, is a bit more sublte:
sprintf('insert into table (%s) values (%s)',name,var_name)
It tells the function sprintf (which is made for that purpose) "take the string which I supply as first parameter and replace occurences of %s with the strings I supply as the following parameters. This last technique is in particular useful if you also need to insert numbers into your string, because sprintf can also convert numbers to string and allows fine control over how they are formatted. You should have a close look at the help page for sprintf to know more :-).
Try this instead:
mysql(['insert into table (' name ') values (' var_name ')']);
or even:
mysql(sprintf('insert into table (%s) values (%s)',name,var_name));
I believe the problem you are having is the same as the one in this other question. It sounds like you want to create a command string that itself contains a ' delimited string, which would require you to escape each ' with another ' when you create your command string (note the first example in this string handling documentation). Note also you may want to use the 's' option for the INPUT function:
var_name = input('Enter the name: ','s'); %# Treats input like a string
commandString = sprintf('insert into table (name) values (''%s'')', var_name);
%# Note the two apostrophes --^
mysql(commandString);
If I were to enter Ken for the input, the string commandString would contain the following:
insert into table (name) values ('Ken')
And of course, as others have already mentioned, beware injection vulnerabilities.

SQL syntax error

I cannot find the error in the following sql:
$query = "INSERT INTO users('username', 'password', 'key', 'email', 'rank',
'ip','active') VALUES ('$username','$password','$random','$email','1','$ip',
'0')";
For some reason I keep getting the error
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''username', 'password', 'key', 'email', 'rank', 'ip', 'active') VALUES ('wx','79' at line 1
transform
('username', 'password', 'key', 'email', 'rank', 'ip', 'active')
to
(`username`, `password`, `key`, `email`, `rank`, `ip`, `active`)
In MySQL, field names should either be un-quoted or backticked (enclosed in back-ticks or back quotes).
In MS SQL Server, field names should either be unquoted or enclosed in [square brackets].
Other SQL DBMS mostly follow the SQL standard, and field names should either be unquoted or enclosed in "double quotes", and are then called 'delimited identifiers'. Sometimes, you have to turn on delimited identifier handling (which is itself non-standard behaviour).
Lose the quotes around the column names.
Don't put the column names in single quotes:
$query = "INSERT INTO users(username, password, key, email, rank, ip, active)
VALUES ('$username','$password','$random','$email','1','$ip','0')";
We'll ignore the SQL injection problems for now. :-)
"right syntax to use near ''user..." is a good hint. You should drop the ' ' around the column names.
In addition to removing the apostrophes around the names as already has been mentioned, you may need to specify some of the names as identifiers if they are reserved keywords in your database provider.
For SQL Server you would use brackets to specify an identifier: [password], however from your error message it seems as you are using MySQL, which uses backticks (`) instead of brackets. (As this forum uses backticks for code blocks I haven't been able to write an example, but I think that you get it anyway.)
Depending on the data types in your table you may also have to remove apostrophes around some values. If for example rank is a numeric field, there should be no apostrophes around the number 1 in the values.
Judging from where the error occurred, you're not escaping the data before sending it to the database, and the third character in the password was an apostrophe (').
Depending on which MySQL API you're using, you'll want one of the following functions:
mysql_real_escape_string, mysqli_real_escape_string, or pdo_quote to escape each variable before passing it to the database.
Alternately, if you're using MySQLi or PDO, use prepared statements with bind parameters which does this for you.
Get rid of the single quotes around your field names.
The error message is giving you a hint to your problem.
check the manual that corresponds to
your MySQL server version for the
right syntax to use near ''username',
'password', 'key', ...
INSERT INTO users('username', ...
As pointed out by Itay, there is no need for single quotes here. If you want/need to use reserved words as names, you have to delimit them in something else, either:
`backticks`, the default MySQL way, or
"doublequotes", the standard ANSI SQL way supported by other databases.
It's not a bad idea to set the sql_mode of your connection (or the server default, if that wouldn't interfere with other applications) to allow ANSI_QUOTES, if you would like to use cross-DBMS-compatible code here.
('$username', ...
Oops! Unless you processed $username to escape it previously, you've just invited a lovely SQL injection security hole into your applications. See mysql_real_escape_string or, better, use parameterised queries to avoid this.