Reputation: 15
Is there any possibility in PHP to save new lines in an textarea into a sql database?
I mean without typing in html commands like br ?
If not, how its done here? And how i can install it into my programm?
Thanks for help!
$descriptionraw = mysqli_real_escape_string($conn, $_POST['setdescription']);
$description = nl2br($descriptionraw);
Upvotes: 0
Views: 8304
Reputation: 1
User php function nl2br
echo nl2br("This\r\nis\n\ra\nstring\r");
Upvotes: -1
Reputation: 2061
The premise of this question is flawed, as the newlines are stored in the database already.
At least as long as you haven't done anything to remove them prior to saving the input, that is.
The question should be how to display the newlines in HTML pages, and for this you have a couple of methods.
<pre>
tag around the output. This will cause the text to be showns preformatted, and thus include the newlines as actual content. The bad side about this is that the text won't break normally, and as such can (and will) break out of the natural flow of your page.nl2br()
or a custom nl2p()
function, when echoing the content to the browser. This translates the newlines into <br>
(or <p>
) tags, and will follow the normal flow of your site's layout. Which makes this the recommended method.PS: This line is wrong:
$description = nl2br($descriptionraw);
This is function to format output
to a HTML-compatible viewer, a database is not. Using nl2br()
and similar functions before you save stuff to the database will only cause you headaches, especially if you ever want to view the data in something that is not equipped to handle HTML code. (Such as the native MySQL client.)
Quick and dirty examples, using PDO: First for saving the data:
$input = filter_var ($_POST['input'], FILTER);
$stmt = $db->prepare ("INSERT INTO `table`(`input`) VALUES (:data)");
$stmt->exec (array (':data' => $input));
Then for displaying it:
$output = '';
$res = $db->exec ("SELECT `input` FROM `table`");
foreach ($res->fetchArray () as $row) {
$output .= nl2br ($row['input']);
}
echo $output;
Upvotes: 5