What security measures should be taken when processing form data in PHP to prevent SQL injection attacks?

To prevent SQL injection attacks when processing form data in PHP, it is crucial to use parameterized queries with prepared statements. This approach separates SQL code from user input, making it impossible for malicious SQL code to be executed. Additionally, input validation and sanitization should be performed to ensure that only the expected type of data is accepted.

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

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

// Bind the user input to the placeholders
$username = $_POST['username'];
$stmt->bindParam(':username', $username);

// Execute the prepared statement
$stmt->execute();

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