What are the best practices for handling string values in SQL queries in PHP to prevent errors and ensure data integrity?

When handling string values in SQL queries in PHP, it is essential to properly escape the strings to prevent SQL injection attacks and ensure data integrity. One common method to achieve this is by using prepared statements with parameterized queries, which separate the SQL code from the data values. This approach helps to prevent malicious input from affecting the query execution and ensures that the data is treated as data rather than executable code.

// Example of using prepared statements to handle string values in SQL queries
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with a placeholder for the string value
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the actual string value to the placeholder
$username = $_POST['username'];
$stmt->bindParam(':username', $username, PDO::PARAM_STR);

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

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);