What are the best practices for preserving formatting, including line breaks and special characters, when retrieving data from a database in PHP?
When retrieving data from a database in PHP, it's important to preserve formatting such as line breaks and special characters. To achieve this, you can use the nl2br() function to convert newlines to HTML line breaks and htmlspecialchars() function to encode special characters. This ensures that the data is displayed correctly on the web page without any formatting issues.
// Retrieve data from the database
$data = $row['content'];
// Preserve formatting
$formatted_data = nl2br(htmlspecialchars($data));
// Display the formatted data
echo $formatted_data;
Keywords
Related Questions
- What are some best practices for updating database records based on values retrieved from external APIs in PHP?
- Are there any recommended best practices for securing a PHP login system to prevent unauthorized access?
- Is it advisable to check every query for successful execution in PHP and retry if unsuccessful?