What are the common pitfalls when directly inserting user input into SQL queries, and how can developers mitigate these risks in PHP applications?

Common pitfalls when directly inserting user input into SQL queries include SQL injection attacks, where malicious input can manipulate the query to perform unintended actions. To mitigate this risk in PHP applications, developers should use prepared statements with parameterized queries to separate the SQL logic from the user input.

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

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

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

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

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