How can one properly sanitize and validate variables used in SQL queries in PHP to prevent SQL injection attacks?

To properly sanitize and validate variables used in SQL queries in PHP to prevent SQL injection attacks, you can use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious input from altering the query structure.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the sanitized user input to the parameter
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$stmt->bindParam(':username', $username);

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

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