How to store data which contains quotes in MySQL - php

In one of my forms I use the rich text editor from Yahoo!.
Now i want to store the data from that textarea in a MySQL database.
The user can enter anything in that textarea, e.g. many double or single quotes.
How can I store that data?
Normally we store by adding that data in one variable and then put that in sql, but the quotes cause problems.

You use a PDO prepared statement (or mysql_real_escape_string)

You can use 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(). If binary data
is to be inserted, this function must
be used.
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.
This function must always (with few
exceptions) be used to make data safe
before sending a query to MySQL.
e.g.
$value = mysql_real_escape_string(" ' \" etc ");
$sql = "INSERT INTO blah VALUES ('$value')";
But a better solution is to use PDO and prepared statements.

If PDO isnt an option you might be able to use mysqli instead of course with a prepared statement.

This is how my data as API response looks like, which I want to store in the MYSQL database. It contains Quotes, HTML Code , etc.
Example:-
{
rewardName: "Cabela's eGiftCard $25.00",
shortDescription: '<p>adidas gift cards can be redeemed in over 150 adidas Sport Performance, adidas Originals, or adidas Outlet stores in the US, as well as online at adidas.com.</p>
terms: '<p>adidas Gift Cards may be redeemed for merchandise on adidas.com and in adidas Sport Performance, adidas Originals, and adidas Outlet stores in the United States.'
}
SOLUTION
CREATE TABLE `brand` (
`reward_name` varchar(2048),
`short_description` varchar(2048),
`terms` varchar(2048),
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
While inserting , In followed JSON.stringify()
let brandDetails= {
rewardName: JSON.stringify(obj.rewardName),
shortDescription: JSON.stringify(obj.shortDescription),
term: JSON.stringify(obj.term),
}
Above is the JSON object and below is the SQL Query that insert data into MySQL.
let query = `INSERT INTO brand (reward_name, short_description, terms)
VALUES (${brandDetails.rewardName},
(${brandDetails.shortDescription}, ${brandDetails.terms})`;
Its worked....

Better yet! When submitting the content to the database, use addslashes();
When retrieving and displaying the string use stripslashes();
$string = "That's awesome!";
addslashes($string);
will come out as That\'s Awesome in the database (and won't break anything)
Then stripslashes($string);
will return it to normal.
http://php.net/manual/en/function.addslashes.php
I use this all the time - simple and straight-forward.

Thanks you guys,
for your replay.
But i had only replace the quotes characters...by this..
html = html.replace(/\'/g, "'"); // 39 is ascii of single quotes
html = html.replace(/\"/g, """); // 39 is ascii of double quotes
and then stored in the database.
its working great..by this way...
and when i want that data then i just replace to its orginal.
But thanks for your replay..
Nitish.
Panchjanya Corporation

Related

MySQL SELECT and then save or update to a different table when special characters are in the first table. leave_my_text_alone();

I have text correctly saved into a mariahDB 10.2 database. The text, to complicate matters, is in fact a combination of Regular Expressions and a hybrid code invented by someone else.It can be used unchanged in another application as a text file - not PHP. But it just text at the end of the day. I want to grab data from this table, change it a small amount, and save it in a new table.
The problem is less so about changing the original data much, but more about SELECTING and saving data that is full of backslashes, single quotes, and double quotes to a new table without it being changed when it is saved. Is there a simple way in PHP and MySQL to take text from a table and resave it exactly as it is so the second table is not different from the the first?
For example the first table has the following in it.
add list to list(%section,$plugin function("XpathPlugin.dll", "$Generic Xpath Parser", $document text, "//p[1]/a[#class=\'result-title hdrlnk\' and 1]", "outerhtml", "False"),"Don\'t Delete","Global")
But if I put this into a variable and then INSERT or UPDATE that to another table, MySQL seems to strip out the backslashes, or add backslashes and throw errors for incorrectly formatted SQL.
For instance Don\'t Delete becomes Don't Delete and in other examples \\ become \
In another case ?=\")" loses the a backslash and becomes ?=")"
I have tried dozens of combinations of PHP function to leave the text alone, such as addslashes(), htmlentities(), preg_replace(), various string substitution and nothing get the data back into the table the same way as it came out.
Does anyone have the trick to do this? I would call the function leave_my_text_alone(); !!
EDIT
To add a few things that did not do the trick to get a variable I could update into the database I tried
$omnibotScript = addcslashes($omnibotScript,"'");
I then found I need to do this twice to consider the backslash being removed from before the apostrophe in Don't Delete....or it would throw a MySQL parsing error..Doing it again fixed that. So then I had to put two backslashes back to have one removed. I then added this to consider a double backslash being reduced to single backslash.
$pattern = '/\\\\"/';
$replacement = '\\\\\\\"';
$omnibotScript = preg_replace($pattern, $replacement, $omnibotScript);
But the list went on.
Use prepared statements.
If you use a prepared statement, MySQL will take care of all the escaping you need to get the string back into the table exactly as it came out of it. For example, using MySQLi:
$query = "SELECT s1 FROM t1";
if (!$result = $con->query($query)) {
exit($con->error);
}
$row = $result->fetch_assoc();
$value = $row['s1'];
$query = "INSERT INTO t2(s1) VALUES (?)";
$stmt = $con->prepare($query);
$stmt->bind_param('s', $value);
$stmt->execute();
The value of s1 in t2 will be exactly the same as the value in t1.

ckeditor storing datas php

It's new for me to use richtext but a user has to be able to insert pictures or to change his text. So I'm using ckeditor but i've some trouble with it.
When a user write into the rich text he can write things using apostrophe and comas.
I'll use an example. Let's imagine i want to write :
It's quite difficult to open a picture, a file blablabla
The problem is that in the inserting query looks like that
Insert into tab (txt1,txt2) values ('value1','value2')
If the user uses comas or apostrophe the richtext cannot be correctly inserted. Moreover, I use longtext in my MySQL database to store the text.
My questions are :
How to store the richtext written by the user
What type should be the column in my MySQL database to correctly store the richtext to be able to give it back
The problem i have is
Erreur SQL !INSERT INTO detail_article(ID,Problem,Num,URL,Solving,Description) VALUES(16,'Chrome : clearing datas',4,'','
\r\nCHROME CACHE CLEARING :
\r\n\r\n
blablabala
\r\n\r\n
In the 'windows explorer', do the fallowing statment....blablabla
\r\n','')
It's a sample of my text but i think the problem is caused by the quotes and the coma
Your problem must come from your PHP script which seems not to escape the pieces of data it send.
If it's not working with the richtext containing commas and apostrophes, then it's probably that the query send to your database isn't escape.
For example, if you have such content :
$value2 = "Catch',em all";
$value1 = "Hello boys";
And if you try to store it in database without escaping it, then the resulting SQL query will looks like :
INSERT INTO tab (value1, value2) VALUES ('Hello boys', 'Catch', em all);
which will be an incorrect SQL statement because of incorrect syntax.
If you use some escape method like PDO::quote(), your input will be inserted in a safe way that won't produce any error (syntax).
Make sure your script does escape the params you send with either PDO::quote() (https://php.net/manual/fr/pdo.quote.php) or either mysqli_real_escape_string (http://php.net/manual/fr/mysqli.real-escape-string.php)

Sql - insert text with carriage returns

In my application, i send a big text as a post parameter to the server. The text is like the code below:
{"objects":[{"type":"path","originX":"center","originY":"center","left":138,"top":250.25,"width":184,"hei
ght":254,"fill":null,"overlayFill":null,"stroke":{"source":"function
anonymous() {\n\n var squareWidth = 10, squareDistance =
2;\n\n var patternCanvas =
fabric.document.createElement('canvas');\n
patternCanvas.width = patternCanvas.height = squareWidth +
squareDistance;\n var ctx =
patternCanvas.getContext('2d');\n\n ctx.fillStyle =
\"#005E7A\";\n ctx.fillRect(0, 0, squareWidth,
squareWidth);\n\n return patternCanvas;\n
\n}","repeat":"repeat","offsetX":0,"offsetY":0},"strokeWidth":15,"strokeDashArray":null,"strokeLineCap":"round","strokeLineJoin":"round","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"selectable":true,"hasControls":true,"hasBorders":true,"hasRotatingPoint":true,"transparentCorners":true,"perPixelTargetFind":false,"shadow":null,"visible":true,"clipTo":null,"path":[["M",69.5,0],["Q",69.5,0,70,0],["Q",70.5,0,70.75,0],["Q",71,0,71.5,....
As you there are carriage returns in it. An i want to insert this text into mysql table as a blob. But it's not successfull. I think the reason is carriage returns in it because other examples without carriage returns work well.
How can i succeed to insert this kind of a text to my table?
By the way, i'm using codeigniter cart class with db session and try to keep this text as cart item option.
You have to understand how escaping works. If you put something escaped in a string like this:
s = "Hello\nthere";
...then the result will contain a REAL linefeed. The variable itself will look like "Hello" plus linefeed plus "there". Now if you hand this over to some sql, it will get the linefeed, not the backslash plus n, which would be the proper version of telling sql to insert a linefeed. No, instead you created an sql string with a real newline inside the quotes.
So you'll have to say "let's make a string that tells sql to insert a newline", and to do this, you have to tell the language (whichever you use) to make a string that makes a string that makes a linefeed. THIS IS WHY you'll have to escape what's already escaped. It's kinda "tell Bob to tell Claire to come here" thing.
So I've seen the "how can I escape it in PHP" question twice from the OP, so here's how to escape in PHP using codeigniter:
First queries with CodeIgniter
You need to use query bindings to help ensure everything is cleaned up before it's run.
assume the following:
$sql = 'SELECT * FROM my_table WHERE first_name=? AND city=?';
Note the two question marks. These are placeholders for our input values.
When I do the following
$this->db->query($sql,array('Mike','Asheville'));
There is a 1-1 mapping for each value in the array to each ?, so the first ? will be replaced by Mike, and the second ? will be replaced by Ashevile. Both values will be escaped appropriately.

Php: I need to insert one & within my mysql database

I'm having trouble with the ampersand symbol, because I've to allow user to insert page_title within database.
The problem is that in my mother language many companies have the symbol in their names like per example "Santos & Filhos".
The question is, how can I insert this, without break my database and without opening security issues?
using this the database gets broken
$title = preg_replace('/&/', '&', $title);
$final_title = utf8_encode($title);
I'm using utf8_encode because of the other accents like á or ã
Thanks, hope you can help me here
EDIT
ok, first thanks to all, most of you were wright, mysql_real_escape_string is indeed one of the best options, if not the best.
I discovered that I was missing one escape (in query) before post my variables to be processed by php and inserted within the database.
So I manage to get my & but now I can't manage to have accents...
So far my php code looks like this
$title = mysql_real_escape_string($_POST['title']);
$sql = "UPDATE bodytable SET body_title = '".utf8_encode($title)."'";
and then in my frontage I've
utf8_decode($row['body_title']);
the result is
<title>Santos & Filhos - Repara?es de autom?veis</title>
Escape characters going into the database with something like mysql_real_escape_string() or PDO and use htmlentities() when displaying it.
This covers securing user input: What's the best method for sanitizing user input with PHP?
Try using an escape character in front of all your special characters you want to insert in the database. Encoding is ok but for example, if the following string was to be added to mysql string field you would get an error.
"special characters don't work"
And you can do this to prevent these errors
"special characters don\'t work"
I belive there is a methods called addslashes(string x) and stripslashes(string x) that will do that for you.
$title_to_insert_in_database = $str = addslashes($title);
$title_for_page = htmlspecialchars($title_from_database);

Issues with inserting special characters CodeIgniter

I am trying to insert a mysql query itself into a table field(Executing a series of queries when certain conditions met), but whenever there is any special characters in query, it is converted in to its corresponding entities.
For example, if Iam inserting this query to table, the quote will become " '" , > to > and space to &# . Is there any way to insert the query as it is and display in correct form .
"select
case item_id
when 206 then '1 Column'
when 255 then '2 Columns'
end as split,
# case oi.product_id
# when 24 then 'XXXX'
# when 28 then 'CCCC'
# when 30 then 'EEEE'
# else 'Something Else'
# end as product,
case oi.price_id
when 72 then 'UYT - Single Pay'
when 73 then 'UYT - Single Pay'
when 74 then 'UYT - Single Pay'
else 'Upsell'
end as product,
count(distinct(al.cust_id)) as the_count
from logtable al
where item_id in (206,255) and
activity_dts > '2012-01-31 19:15:00' and
o.order_is_refunded = 0 and
t.response_code = 1 and
t.response_reasontext not like '%testmode%'
group by 1,2;"
Please give me suggestions or Am I missing any thing here. The charset used by my CI installation is UTF-8.
There shouldn't be any problem with inserting your string, as it IS a string, and the database library doesn't make any character encoding by itself, afaik. What encoding are the database and the tables? (the connection should be UTF-8, as per default settings)
Since you're using the framework, you can use its methods (and not mysql_real_escape_string() or, god, addslashes()!! like suggested in other answers).This should work:
$string_query = "select
case item_id
when 206 then '1 Column'
when 255 then '2 Columns'....";
$sql = "INSERT INTO table(column) VALUES (?)";
$this->db->query($sql, array($string_query));
The query bindings automatically escapes FOR SQL, so for that you're safe (you could have used ActiveRecord with the same result). I don't know what couldn't be working in this, surely NO FUNCTIONS encodes html.
Maybe you're doing the encoding somewhere else: are you sure you're not calling xss_clean(), htmlspecialchars()/htmlentities(), or you have XSS protection enabled, or you pass TRUE as second paramenter of $this->input-> ?
If all the above for some reason - for wich you didn't provide enought information - fails, you can alwasy encode everything:
$string_query = base64_encode("select.....");
// HERE YOU MAKE THE INSERT QUERY
and when you retrieve it, you base64_decode() the string. But the ideal solution is not this, it should work without flaws anyway.
PHP addshlashes
This function will help you add the query along with its quotes as it is, in your db.
Also you can do this way,
If your queries just have multiple single quotes only, then border it by double quotes:
like $tmp = "See single' quotes";
or vice-versa like:
$tmp = 'See double " quotes';
Try following
$data_insert = mysql_real_escape_string($values);
Also you can find it in detail http://php.net/manual/en/function.mysql-real-escape-string.php

Categories