How can the use of SQL injection be prevented when querying a database in PHP?

SQL injection can be prevented when querying a database in PHP by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input data, preventing malicious SQL code from being injected into the query.

// 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 with user input data
$stmt->bindParam(':username', $_POST['username']);

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

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

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