views:

83

answers:

3

I have some PHP code which stores whatever is typed in a textbox in the databse. If I type in bob's apples, it gets stored in the database as bob's apples.

What can be the problem?

The table storing this has the collation of latin1_swedish_ci.

+5  A: 

Looks like your PHP code is converting special char to HTML entities using htmlentities. You can make use of the function html_entity_decode to get back the original string.

$a = "bob's apples";
echo htmlentities($a,ENT_QUOTES);                                // bob's apples
echo html_entity_decode(htmlentities($a,ENT_QUOTES),ENT_QUOTES); //bob's apples
codaddict
Actually that function or the other similar function isn't being used, but the decoding function is helpful. Are you sure this isn't anything to do with the mysql collation?
Click Upvote
Pretty sure. print out the insert statement and see for yourself.
Mike B
We'd have to see some code, but it seems clear *something* is HTML-escaping at the input phase, which as Ollie explains is totally bogus. Unfortunately, it is a common mistake for PHP authors. Are you using some kind of framework that might sneakily be doing it?
bobince
A: 

The function htmlspecialchars() with ENT_QUOTES for the seconde parameter also converts a single quote to '

htmlspecialchars($a, ENT_QUOTES);
Charlotte Moller
+2  A: 

Your HTML escaping strings (with either htmlspecialchars() or htmlentities()) before inserting into the database, which is a bad idea. You can use html_entity_decode() to repair the damage but it's better not to do it in the first place.

The time when you should be escaping HTML is right before you output to the browser usually with the fetched rows from SELECT queries:

Do a Google for XSS.

Not that HTML escaping has little to do with "adding slashes" that you should be doing before inserting string into the database with mysql_real_escape_string(). This is to avoid SQL injection vulnerabilities.

<?php $row =  mysql_fetch_row($result);
echo htmlspecialchars($row['someField']); // good place to escape HTML.

<?php $str = htmlspecialchars($_GET['foo']); // bad place to escape HTML.
$str = mysql_real_escape_string($str); // good place to escape for DB.
$q = 'INSERT INTO .... VALUES (' . $str . ')';
mysql_query($q);
Ollie Saunders