How can developers prevent SQL injection vulnerabilities when incorporating user input into SQL queries in PHP?

Developers can prevent SQL injection vulnerabilities by using prepared statements with parameterized queries in PHP. This method separates the SQL query logic from the user input data, preventing malicious SQL code from being executed. By binding user input values to placeholders in the query, developers can ensure that the input is treated as data rather than executable code.

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

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

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