Skip to content
PHP Logo

How can newlines be properly stored in a MySQL database when using a multi-line input field in PHP?

When storing multi-line input from a textarea field in a MySQL database using PHP, newlines need to be properly handled to ensure they are stored and displayed correctly. To achieve this, you can use the PHP function `mysqli_real_escape_string()` to escape special characters, including newlines, before inserting the data into the database.

php
// Retrieve the input from the textarea field
$input = $_POST['textarea_input'];

// Escape special characters, including newlines, before storing in the database
$escaped_input = mysqli_real_escape_string($connection, $input);

// Insert the escaped input into the database
$query = "INSERT INTO table_name (column_name) VALUES ('$escaped_input')";
mysqli_query($connection, $query);