Skip to content
PHP Logo

How can PHP be used to preserve line breaks in form input stored in a database?

When storing form input with line breaks in a database using PHP, the newline characters (\n) may not be preserved by default. To ensure that line breaks are maintained, you can use the PHP function nl2br() to convert newline characters to HTML line breaks (<br>). When retrieving the data from the database and displaying it on a webpage, you can use the nl2br() function again to convert the HTML line breaks back to newline characters for proper formatting.

php
// Storing form input with line breaks in a database
$input = $_POST['input'];
$input_with_line_breaks = nl2br($input);
// Store $input_with_line_breaks in the database

// Retrieving and displaying the data with preserved line breaks
$data_from_db = "Data with line breaks from database";
echo nl2br($data_from_db);