Toskan
Toskan

Reputation: 14931

\n in textarea gets interpreted when transferring to php server

So I enter

hello \n \n my friend \n !

into a textarea. Then I store it into db, I retrieve it, and what I get is

hello

my friend
!

But I did not want the \n get translated into actual newlines.

So this is my example setup:

<textarea name="mytextarea">$mytext</textarea>

on the server i do:

store

$mydbtextstore = $_POST["mytextarea"];

$modsql = " UPDATE mytable SET text = " . "'" . $mydbtextstore . "'" ;
mysql_query($modsql, $conn) or die(mysql_error());

retrieve

$descSQL = " SELECT  text
               FROM mytable;"
$descRes = mysql_query($descSQL, $conn) or die(mysql_error());
$descRow = mysql_fetch_array($descRes);
$mytext = $descRow["text"];

What am I missing? The textarea MUST reproduce and contain this:

\n

Upvotes: 1

Views: 84

Answers (2)

Tengiz
Tengiz

Reputation: 1920

You need to escape backslashes with another backslashes. Funny, right?

So after you submitted your text do like this:

$text = str_replace('\\', '\\\\', $text);

so you will have following:

hello \\n \\n my friend \\n !

and when you insert it in your database it will look like a string with only one backslashes

Upvotes: 1

Jeroen de Jong
Jeroen de Jong

Reputation: 337

You could use a str_replace like this, after the retrieving of the data.

$mytext = str_replace("\","&#92;",$mytext);

You will replace the slash with its html-entity if you use this code.

EDIT: or use htmlentities on the whole string.

Upvotes: 1

Related Questions