What are the recommended methods for handling user input and preventing SQL injection in PHP applications?

To handle user input and prevent SQL injection in PHP applications, it is recommended to use prepared statements with parameterized queries. This method separates SQL code from user input, making it impossible for an attacker to inject malicious SQL code. Additionally, input validation and sanitization should be performed to ensure that only expected data is passed to the database.

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

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

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

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

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