开发者

Preserve user comments format in database

HI,

I am creating on comments form where users will be commented and will be stored in the MYSQL database. The problem what I a开发者_开发问答m facing is, it is stored as the single line in the database. It should be stored with exact format how user is entered in the form(like new lines and everything). I am using PHP to store it in the MySQL db.


First store it as text or longtext. Second, when showing the comment, use a function like nl2br to convert newlines to html <br> elements. This way, linebreaks are preserved.


Your text is stored just fine in the database if you are putting it into a long enough text-type field (e.g. TEXT), including the newlines in the user input.

Your problem is how to display the text formatted the way the user was seeing it when entering it. This is a more generic problem, and it only has to do with how HTML treats whitespace.

One approach would be to call nl2br on the comments, as Ikke says. This would replace all newlines (which the browser disregards) with <br> tags which have a visible effect on the rendered output.

Another option would be to put the text inside a <pre>...</pre> tag. This will force the browser to render it with whitespace preserved.

It's really up to what's more convenient/suitable for you.

Update: Just to be clear: do not modify the user input before inserting it in the database (unless it's part of your input validation, like e.g. stripping HTML tags from the input). Store it in an "untouched" format, and only do some processing on it before you output the data. This way, you always have the option of performing the correct processing if your output channel changes in the future (e.g. export comments to a text file vs displaying them as HTML).


you can store the comments in the same form in the mysql database. one difference would be when you retrieve the comments that has new line your code should look for \r\n and interpret it.. and also when you insert the data in mysql you will have to escape ' and \ characters from the comment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜