What are the best practices for handling user input in PHP forms to prevent security vulnerabilities like SQL injection?

SQL injection is a common security vulnerability where malicious SQL queries are inserted into form inputs, allowing attackers to manipulate the database. To prevent this, always sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries in PHP.

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

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

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