When building SQL queries in PHP, what are the best practices for handling variable values like strings?

When building SQL queries in PHP, it is important to handle variable values like strings properly to prevent SQL injection attacks. One common best practice is to use prepared statements with parameterized queries, which allows you to bind variables to placeholders in the query. This way, the values are automatically escaped and sanitized, reducing the risk of SQL injection.

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

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

// Bind the variable value to the placeholder
$username = 'john_doe';
$stmt->bindParam(':username', $username);

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

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

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}