Are there any best practices for displaying content from a database in PHP to avoid losing data or formatting issues?
When displaying content from a database in PHP, it is important to properly escape the data to prevent SQL injection attacks and to ensure that the data is displayed correctly without any formatting issues. One best practice is to use prepared statements when querying the database to prevent SQL injection. Additionally, when outputting the data, using htmlspecialchars() function can help prevent XSS attacks and preserve the formatting of the data.
// Retrieve data from the database
$stmt = $pdo->prepare("SELECT * FROM table WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch();
// Display the data with proper escaping
echo htmlspecialchars($row['column_name']);