What are the potential pitfalls of not properly sanitizing user input in PHP when working with databases?

Not properly sanitizing user input in PHP when working with databases can lead to SQL injection attacks, where malicious users can manipulate the database queries to access, modify, or delete data. To prevent this, always use prepared statements with parameterized queries to sanitize user input before executing SQL statements.

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

// Sanitize user input using prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

// Fetch and display the results
while ($row = $stmt->fetch()) {
    echo $row['username'] . '<br>';
}