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

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);

Related

Updating mysql (json) with several quotes (don't want escape characters in database)

I am trying to update a Json datatype inside a database (row format = longtext).
Le'ts say this is the data I want to copy and put into another field via PHP (using PDO):
{"migration1": "something something",
"migration2": "something something something",
"migration69": "["something1", "something2", "something3"]"}
My Problem lays with the data in migration69.
Here is the SQL satement:
UPDATE mytable SET myfield=(SELECT JSON_SET(myfield,
'$.migration1', :mig1,
'$.migration2', :mig2,
'$.migration69', :mig69
)
FROM mytable WHERE id=1234)
WHERE id=1234
When I execute the statement in PHP it does puts excape characters into my database before every quotation mark exept for the first and last one (it does not show them here...):
"migration69": "["something1", "something2", "something3"]"
But i do need it EXACTLY like this but without the escape characters.
I sure have tried around a bit but maybe there is an easy solution?
Cheers for some help - i'd really appreciate it.

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.

mysql_query returns nothing when called with special characters (The danish characters: æøå)

I generate a mysql query from a form with a free text search field.
Something like:
SELECT ... FROM ... WHERE 'something' LIKE '%SEARCH%'
All this works fine and returns the valid rows when the search does not contain any special characters, like the danish characters ÆØÅ.
When these letters ARE used, the query returns no results, all though when i take the generated query string and plug it into phpMyAdmin i get exacly the result i want.
Thanks
add this line of code in your connection file...
mysql_set_charset("utf8", $db);
it is better for you to encode your data to UTF-8 before you pass it into query...
I'm not using Danish but Czech but I think there are the same (at least by UTF8 implementation) - you must keep in mind used encoding (original server script, data tables self and also your database connection handler).
I think you have an encoding problem, maybe phpMyAdmin is using a different client encoding than your other client. SET NAMES 'encoding' should just do what you need, I think.
Also we can use PHP variable and convert it before the select operation (supposing data base is ISOO-8859-2) .
Example:
// word with special characters
$search='kötészeti';
// conversion to ISO
$search=iconv("UTF-8","ISO-8859-2", $search);
// create search condition
$condition="SELECT ... FROM ... WHERE 'something' LIKE '%$search%'";
// apply query
mysql_query($condition);

Categories