What are some common pitfalls to avoid when using user input in SQL queries in PHP?

One common pitfall to avoid when using user input in SQL queries in PHP is SQL injection attacks. To prevent this, you should always use prepared statements with parameterized queries to sanitize and validate user input before executing the query.

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

// Get user input
$userInput = $_POST['user_input'];

// Prepare the SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $userInput, PDO::PARAM_STR);

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

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

// Loop through the results
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}