What are common pitfalls when using PHP to interact with a database and how can they be avoided?

One common pitfall when using PHP to interact with a database is not properly sanitizing user input, which can lead to SQL injection attacks. To avoid this, always use prepared statements with parameterized queries to prevent malicious SQL code from being injected.

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

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

// Bind parameters and execute the statement
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();

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