Reputation: 1477
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
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>
Upvotes: 1
Views: 112
Reputation: 1
$title_to_insert_in_database = $str = addslashes($title);
$title_for_page = htmlspecialchars($title_from_database);
Upvotes: 0
Reputation: 2424
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.
Upvotes: 0
Reputation: 32165
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?
Upvotes: 2