How can variables be properly masked in SQL queries in PHP?

When using variables in SQL queries in PHP, it is important to properly sanitize and escape the input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries. This allows variables to be safely passed into the query without the risk of malicious SQL code being injected.

// Example of properly masking variables in SQL queries in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

// Bind the variable to the placeholder and execute the query
$username = $_POST['username'];
$stmt->bindParam(':username', $username);
$stmt->execute();

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

// Loop through the results and do something with them
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}