How to save new rows in a MySQL database?

I gather in circles trying to decide what is the best way to store newlines in a MySQL database.

A bit of background; the user is prompted to fill out a text box. This must be stored in the MySQL database before reading the data and content included in the HTML email.

Should I store them as:

1) A string literal is certainly a dangerous and bad practice.

2) As a line with \r\n in - when I read it back from the database, it was read as 4 characters, so nl2br() could not replace them correctly.

3) As HTML <br /> - since it must be encoded in an html object that must be saved, it ends up being stored as &lt;br /&gt; , therefore, when it gets to the email <br /> , it is printed, not the actual line of the new line. Passing through html_entity_decode() will decode the other characters that need to be encoded.

Any help is greatly appreciated.

+4
source share
3 answers

Save it as is, but exit first . This is your option 1. When you need to present this data, use any function necessary to format it. If you need to display it in HTML, use the nl2br() and htmlentities() functions. This will also work for mail.

If you have data in a text area, for example,

 $text="Hello Sir, I am Robert'); Drop table students; -- ..... Yours most obedient pupil ....."; 

Just save it as soon as you escape it, or use a prepared statement.

 $text = $mysqli->real_escape_string($text); 
+9
source

use javascript str.replace(/\n/g,'\\n') string replacement function str.replace(/\n/g,'\\n')

to convert all newline characters to escaped literals in a text field when forming a url or post string.

Getting the same with PHP json_encode() and showing it through a text box is fine for me.

+2
source

It depends on the type of application (how you want to display the text).

If it's an HTML email editor, I think the html format would be better.

Most content management systems (CMS) use the HTML format (joomla, wordpress, prestashop, etc.) because you can simply read it from the database and send it to the browser.

Also, you may need other HTML tags (for example, <b> for bold or <center> ).

I think using the \r\n format is better for non-web applications when data is displayed on windows form elements.

One more thing: you can store them in both directions: - <br> for viewing HTML - \r\n for the HTML source (for adding a new line and creating more readable HTML source code)

More readable html i mean the following:

 <center> This is header </center> <p> This is paragraph. <br> Second line. </p> 

Instead of this:

 <center>This is header</center><p>This is paragraph.<br>Second line.</p> 
0
source

All Articles