How can SQL injection vulnerabilities be avoided when querying a MySQL database in PHP?

SQL injection vulnerabilities can be avoided by using prepared statements with parameterized queries in PHP when querying a MySQL database. This technique helps to prevent malicious SQL code from being injected into the query by treating user input as data rather than executable code.

// Establish a connection to the MySQL database
$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 parameter value to the query
$stmt->bindParam(':username', $_POST['username']);

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

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

// Loop through the results and do something with them
foreach ($results as $row) {
    // Do something with the data
}