Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Surfing the web I find two approaches on storing data in databases.

Approach 1:
Store data in the database with the html-specialcharacters sanitized

$userdata = $_POST['field'];
store_in_db_via_PDO(htmlspecialchars($userdata), 'field');
display_on_page(get_from_db('field'));

Approach 2:
Store data as raw as possible in database and sanitize on display:

$userdata = $_POST['field'];
$store_in_db_via_PDO($userdata, 'field');
display_on_page(htmlspecialchars('field'));

BTW I'm not speaking about sqlinjection atacks, these are 'caught` by the PDO-driver

Is there an industry standard on storing data, which shouldn't include html-code, in a database?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

I would generally store data in its purest form.

You should verify the data as you read it before pushing it out to the client anyway, in case a bug elsewhere has allowed data that is badly formed (either accidentally or maliciously) to be added to the database, so escaping the data on the way in does not save you any significant processing on the way out.

Storing the data pure also saves you a lot of hassle if you find a bug in the encoding routine or change your mind how you want things encoded (not likely an issue here as you are working to a pre-defined standard with HTML text, but good habits are easier to keep to if you use them religiously even when they make no difference). If you change you encoding standard then data that is stored pure doesn't need to be touched, but existing encoded data needs to be read, decoded, re-encoded using the new rules, and saved again.

share|improve this answer
    
Thanks for the answer; storing everything in its purest form is also my first idea. But if user input should not contain html-tags it is better to strip those before inserting in database? –  stUrb Mar 6 at 15:36
1  
Removing things that should not be there is different to encoding things that should/could be there but need protection against being used for injection and other problems. If tags should not be there remove them on the way in, or better still give the user a message and refuse to save until they provide valid input. If tags are valid then keep the input as-is in the DB and verify+escape as needed on the way out. –  David Spillett Mar 6 at 15:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.