What are some best practices for handling user input in PHP to prevent SQL injection and other security vulnerabilities?

To prevent SQL injection and other security vulnerabilities when handling user input in PHP, it is crucial to use prepared statements with parameterized queries. This helps to separate SQL code from user input, preventing malicious input from altering the query structure. Additionally, input validation and sanitization should be performed to ensure that only expected and safe data is processed.

// Example 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 statement with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

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

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

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