1 year ago
#70753
Arie
Why do I get \r\n stored in the database and how to display it back as a new line?
I am not sure what the safest way is to get the value of a textarea into a MySQL table, hopefully someone can get me on the right track.
Form:
<form class="form-horizontal" id="form_textarea" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<fieldset>
<div class="col-12"><label name="textarea" class="control-label ">Textarea</label></div>
<div class="col-12"><textarea class="form-control" id="textarea" name="textarea" rows="5"></textarea></div>
<div class="row-12">
<input type="hidden" id="id" name="id" value="<?php echo $_SESSION["id"]; ?>">
<input type="submit" name="submit" value="Upload textarea" />
</div>
<div id="error" class="error" style="display: none;">Sorry, something went wrong!</div>
</fieldset>
</form>
jQuery:
<script type="text/javascript">
$(document).ready(function() {
var v = jQuery("#form_bedrijfsomschrijving").validate({
submitHandler: function(form) {
var formData = new FormData(form);
// e.preventDefault();
$.ajax({
url: "ajax_textarea.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
if(data === 'success') {
alert('success');
location.href = 'index.php';
}
if(data === 'error') {
alert('error');
$("#error").show();
}
},
error: function(){}
});
}
});
});
</script>
ajax_textarea.php:
<?php
$stmt = $link->prepare("UPDATE table SET textarea = ? WHERE id = ?");
$stmt->bind_param("si", $textarea, $id);
$textarea = mysqli_real_escape_string($conn, ucfirst($_POST["textarea"]));
$id = mysqli_real_escape_string($conn, $_POST["id"]);
$stmt->execute();
if ($stmt->affected_rows == 1) {
echo "success";
} else {
echo "error";
}
$stmt->close();
$conn->close();
?>
I am inserting the textarea with this sample text:
This is a test.
Some text on one new line.
And some text after two 2 new lines.
This is what I get in the database:
This is a test.\r\nSome text on one new line.\r\n\r\nAnd some text after two 2 new lines.
First question: Is the \r\n OK in the table?
And the second question: How do I get this field on my screen, viewing exact the same as has been filled in so with the new lines?
I have tried nl2br but when I echo this I see the \r\n in stead of
The textarea field in the database is an text type with utf8_unicode_ci as charset.
ajax
mysqli
textarea
nl2br
0 Answers
Your Answer