Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store html entities in database? Or convert when retrieved?

Tags:

php

mysql

Quick question, is it a better idea to call htmlentities() (or htmlspecialchars()) before or after inserting data into the database?

Before: The new longer string will cause me to have to change the database to hold longer values in the field. (maxlength="800" could change to a 804 char string)

After: This will require a lot more server processing, and hundreds of calls to htmlspecialchars() could be made on every page load or AJAX load.

SOOO. Will converting when results are retrieved slow my code significantly? Should I change the DB?

like image 461
Douglas Avatar asked Dec 28 '09 18:12

Douglas


People also ask

Is it good to store HTML in database?

Storing HTML code is fine. But if it is not from trusted source, you need to check it and allow a secure subset of markup only. HTML Tidy library will help you with that. Also, you need to count with a future change in website design, so do not use too much markup, only basic tags.

How do I render HTML tags from MySQL database in PHP?

The only way to display the html content is to simply echo $row3['description'] , however, this leaves you open to vulnerabilities and unless you really trust the data (ie: never) then you should clean it up first. You can try htmlpurifier for this. Show activity on this post.


1 Answers

I'd recommend storing the most raw form of the data in the database. That gives you the most flexibility when choosing how and where to output that data.

If you find that performance is a problem, you could cache the HTML-formatted version of this data somehow. Remember that premature optimization is a bad thing.

like image 80
pix0r Avatar answered Sep 23 '22 04:09

pix0r