I am trying to insert a description text field into the database.
I was previously just doing something like this:
$group_description = mysql_real_escape_string($_POST['group_description']);
But it was creating problems because when I was taking things out of the database, they were being displayed with \n\r strings instead of new lines.
Here is an example of a page with that problem:
http://www.comehike.com/hikes/hiking_group.php?hiking_group_id=48
So I tried to fix it by adding nl2br like this:
$group_description = mysql_real_escape_string(nl2br($_POST['group_description']));
But that just inserted an extra line 🙁 Here is the example of the current problem:
http://www.comehike.com/hikes/hiking_group.php?hiking_group_id=50
Here is an example of an insert statement I use:
$insert_group_sql = 'INSERT INTO hiking_groups( title , group_description ) VALUES ( "'.$group_name.'" , "'.$group_description.'" ) ';
What is the proper way to do this?
Here is the code I use to display the $group_description
//Convert all urls to links
$group_description = preg_replace('#([\s|^])(www)#i', '$1http://$2', $group_description);
$pattern = '#((http|https|ftp|telnet|news|gopher|file|wais):\/\/[^\s]+)#i';
$replacement = '<a href="$1" target="_blank">$1</a>';
$group_description = preg_replace($pattern, $replacement, $group_description);
$group_description = str_replace("\'" , "'", $group_description );
$group_description = nl2br($group_description);
/* Convert all E-mail matches to appropriate HTML links */
$pattern = '#([0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.';
$pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i';
$replacement = '<a href="mailto:\\1">\\1</a>';
$group_description = preg_replace($pattern, $replacement, $group_description);
First, I suggest that you do as Spudley suggests, keep it in the original form in the database and format it once you display it.
nl2br()should work, so I suggest that you check the input data to see exactly what is being input (which is easier to do if you don’t format it before you store it in the DB). What it do is it takes \n, \n\r, \r\n and \r and inserts a<br/>instead. You should check that for instance there is no space in between \n and \r.Also, make sure that you only use
nl2br()in one place, since it doesn’t replace the new lines, it just inserts the<br/>(that is, if you donl2br(nl2br($group_description))you will get two<br/>)Update:
I see in the additional code that when you display the description, you already have a
nl2br(). You need to remove one of them, so that you only add the<br/>s once.Also, instead of this:
Try this:
That should remove all the sanitizing that
mysql_real_escape_string()did, which should solve the problem of the \n\r showing in the text.