How can SQL injection vulnerabilities be prevented when querying databases in PHP?

SQL injection vulnerabilities can be prevented in PHP by using prepared statements with parameterized queries. This approach separates the SQL query logic from the data, making it impossible for an attacker to inject malicious code into the query. By binding parameters to the query, the database engine treats them as data rather than executable code, effectively preventing SQL injection attacks.

// 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 parameter to a variable
$username = $_POST['username'];
$stmt->bindParam(':username', $username);

// Execute the prepared statement
$stmt->execute();

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

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