tags:

views:

45

answers:

2

I have some html code I want to store in a database. I need a way to encode it in php so all the special characters don't break the db INSERT (the html can include all sorts of spec chars) and then a way to unencode that at the other end in javascript once i've passed it via JSON so that the html is rendered correctly.

IS there any way I can do this?

+2  A: 

Since you are using PHP:

For the database, use PDO: http://bobby-tables.com/php.html

And for the JSON, use the json methods: http://php.net/json

These handle all the escaping for you.

David Dorward
I can't install the JSON extension so I'm building json as a string in php and then sending that back. I've realised now that it's actually the special chars breaking my sql query so I need to encode it in php so this doesn't happen.
elduderino
Extension? It is part of core! http://uk2.php.net/manual/en/json.requirements.php
David Dorward
I'm on 5.1.6. Don't think it's part of the core in that version.
elduderino
Thanks that seems to be working using the PDO
elduderino
I'm not too sure, but poking around the PHP website indicates that the 5.1 series isn't updated any longer. I'd be really worried about security problems if I was still using it.
David Dorward
+1  A: 

Regarding "not breaking the db INSERT," this should be a completely moot point. You should either be appropriately escaping all user-provided data (eg. mysqli::real_escape_string) or using binding.

Adam Backstrom