How can PHP developers ensure proper data validation and sanitization when retrieving and displaying content from a database?

To ensure proper data validation and sanitization when retrieving and displaying content from a database, PHP developers can use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, they can use functions like htmlspecialchars() to sanitize user input and prevent cross-site scripting (XSS) attacks.

// Example of using prepared statements with parameterized queries to retrieve and display content from a database

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a statement
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE id = :id');

// Bind parameters
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);

// Execute the query
$stmt->execute();

// Fetch the results
$result = $stmt->fetch();

// Display the content
echo htmlspecialchars($result['content']);