How can PHP developers prevent SQL injection when processing form data?

To prevent SQL injection when processing form data in PHP, developers should use prepared statements with parameterized queries. This method separates SQL code from user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the SQL query, developers can ensure that user 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 parameter to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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