How can SQL injection vulnerabilities be prevented when writing PHP functions that interact with databases?

SQL injection vulnerabilities can be prevented by using prepared statements with parameterized queries instead of directly concatenating user input into SQL queries. This helps to separate the SQL logic from the user input, making it much more difficult for attackers to inject malicious SQL code.

// 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 a parameterized statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the parameter in the query
$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>';
}