0

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?

4
  • Aren't the single and double quotes already escaped in the database? Commented Aug 16, 2010 at 14:35
  • @simnom — they should be escaped for the database (preferably with PDO since PHP is in use). The act of pulling them out of the database will unescape them. Commented Aug 16, 2010 at 14:39
  • sorry edited my post slightly....I needed something slightly different than what I posted originally Commented Aug 16, 2010 at 14:40
  • … and I've rewritten my answer to compensate. Commented Aug 16, 2010 at 14:42

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Extension? It is part of core! uk2.php.net/manual/en/json.requirements.php
I'm on 5.1.6. Don't think it's part of the core in that version.
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.
1

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.

1 Comment

Be careful using real_escape_string(). It can open the door insertion attacks. php.net/manual/en/function.mysql-real-escape-string.php . you are better off searching for and replacing characters on your own that way you can dump and invalid strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.