I am writing an application where a user enters text into a textbox inside a form and the text is stored in a SQL db inside a MEDIUMTEXT field. I am testing right now so the table only has 2 field "1" for the index and "2" for the stored text.
<form method="post" action="index.php" enctype="multipart/form-data" >
<h3>Input Text Here</h3>
<textarea name="text" cols="40" rows="6" ></textarea><br/>
<input type="submit" value="Submit" />
</form>
The stored text then is retrieved in another page and displayed.
<?php
$query = "SELECT * FROM test_table WHERE 1='1'";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$results = mysql_fetch_array($result, MYSQL_ASSOC);
echo $results['2'];
if(isset($_POST['text'])) {
echo printText($_POST['text']);
function printText($txt) {
if(!empty($txt)) {
return $txt;
} else {
return 'You didn\'t write anything.';
}
}
}
?>
The problem is that when the text is displayed all the carriage returns disappear and multiple paragraphs become one.
Can anybody guide me in the appropriate direction? Should I be using regular expressions looking for carriage returns and marking them up? Is there a less search intense method? I tried nl2br(), but I guess you need actual \n entries for it to work.
I am writing this for someone to easily update a "news blub" on their landing page without having to use a text editor and writing code.
Thanks!
I tried nl2br(), but I guess you need actual \n entries for it to work.
nl2br is the function you need. From the manual:
Returns string with '<br />' or '<br>' inserted before all newlines (\r\n, \n\r, \n and \r).
If a user submits data with carriage returns then you will be getting "actual" \n entries (or one of the others mentioned in the manual description). Ensure you are calling it whenever you are echoing the pertinent text.