How do I keep user-entered carriage returns in a text field?

I have an insert.php file (thanks to spikeZ!) which uses mysql_real_escape_string. My problem is that if a user enters a lot of (allowed) text in a field they often enter carriage returns as well. I’d like to keep those carriage returns but the mysql_real_escape_string function strips them out. Is there any way to keep them?

You will be needing http://php.net/nl2br :slight_smile:

mysql_real_escape_string doesn’t remove them, they are still stored in the string, but HTML does not render them the way you think (they get compressed into a single white space)

If you need it to preserve the formatting, you can wrap the string in a <pre>, if you only need the newlines to render in HTML, as spikeZ pointed out, wrap it in nl2br()

Perfect! Thanks to both of you. Works like a charm. :>)

How does the charm work?

Ask me on St. Patrick’s Day, lampcms. ;>)

It would appear that along with preserving the carriage returns, nl2br also escapes quotation marks and apostrophes, so I have to go in manually and remove the \ characters. I did find some information on using stripslashes but it doesn’t work to wrap the nl2br instruction in the stripslashes. I’m using the nl2br in the file which displays the db entries, not in the insertion file which uses the mysql_real_escape_string, by the way.

If stripslashes is the correct thing to use to get rid of the \s, where should I use it? If it’s not the correct thing to use, what would be? TIA!

addslashes/mysql_real_escape_string on the way in - stripslashes on the way out :slight_smile:


$var = stripslashes($row['field_data']);
echo $var;

Thanks Mike but I’m still confused as to just where I should be using that. I have 3 files: the form people fill out, the insert.php file which contains the mysql_real_escape_string stuff and then the directory file which displays the records.

At present, in the insert.php file, I have: $handlerListing = mysql_real_escape_string($_POST[‘handlerListing’]); and then INSERT into handlers (handlerListing) VALUE (‘“. $handlerListing .”’)"; - (plus other values but this is the pertinent one).

Then in the directory file I have: echo (nl2br($row_rsHandlers[‘handlerListing’]));

I can’t figure out which of those (or both - or somewhere else) needs the stripslashes instruction.

Sorry - I’m slowly getting all this stuff but obviously too slowly for what I’m trying to do. :>)

Dont worry Helen, this all takes time to learn :slight_smile:

you would use it on the output, so when you echo the variable


echo nl2br(stripslashes($row_rsHandlers['handlerListing']));

note that you dont use () when echo’ing

Aha!! I had the stripslashes before the nl2br. Duh. Of course it would go after. Thanks so much!!