What are some best practices for handling and manipulating strings retrieved from a database in PHP?

When handling and manipulating strings retrieved from a database in PHP, it is important to sanitize the data to prevent SQL injection attacks and other security vulnerabilities. One way to do this is by using prepared statements with parameterized queries. Additionally, it is recommended to use PHP's built-in functions for string manipulation, such as trim(), addslashes(), and htmlspecialchars(), to ensure data integrity and prevent unexpected behavior.

// Example of sanitizing a string retrieved from a database
$dbString = "Hello, <script>alert('XSS attack!');</script>";
$sanitizedString = htmlspecialchars($dbString, ENT_QUOTES, 'UTF-8');

echo $sanitizedString;