How can SQL injection vulnerabilities be prevented when constructing SQL queries in PHP functions?

SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries in PHP functions. This method separates SQL code from user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, the database server can differentiate between code and data, effectively mitigating the risk of SQL injection attacks.

// Example PHP code snippet using prepared statements to prevent SQL injection

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

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

// Bind the parameter to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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

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