Reputation: 39
I want to insert a similar string into DB, but after inserting the characters "\n" disappear and in DB I see it as new line.
The string which I send:
[{"Index":0,"Title":"headline","Content":"first line\nsecond line","Class":"colour1"}]
For insert to DB, I use this PHP code and string I send via HTML form with method POST.
if ( $action == "save") {
$notes = $_POST['notes'];
$sql = "INSERT INTO notes (notes) VALUES ('$notes')";
if (mysqli_query($conn, $sql)) {
$saved = "Saved...";
} else {
$saved = "Error: " . mysqli_error($conn);
}
}
When I print variable "$_POST['notes']" or "$notes" before sending via the form, the string is OK, after sending the form and before inserting into DB, the string is OK too.
Upvotes: 1
Views: 3112
Reputation: 483
You Should use Textarea while inserting data and when you want to show/echo the data use this PHP function to preserve the line breaks echo nl2br($string);
For example
<textarea class="form-control" name="short_desc" required></textarea>
and for frontend echo use following function
<?PHP echo nl2br($short_desc);?>
It will preserve the line break and show content with breaks on frontend,
Also keep the Mysql data type text for it.
Upvotes: 0
Reputation: 33
"\n" is a next line statement, it is correct that MYSql take it as next line. Gotta use nl2br($value) to make it display as next line in html webpage.
Upvotes: 0
Reputation: 529
The problem arises due to interpretation of '\n' as '\\n' in MySql. To avoid this conversion,try this approach: Change your query string before making an insert to database as following:
$notes = $_POST['notes'];
//This line will replace '\n' with HTML Coded Character Set, but will be interpreted in HTML as \n itself.
$notes = str_replace('\n', '\n', $notes);
$sql = "INSERT INTO notes (notes) VALUES ('$notes')";
Upvotes: 0