What are the best practices for handling string values in SQL queries when using PHP for database operations?

When handling string values in SQL queries in PHP, it is important to properly escape the strings to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries, which separate the SQL query from the user input. This helps to ensure that the input is treated as data and not as part of the SQL query, thus preventing malicious code execution.

// 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 query 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);

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

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