What are common pitfalls when querying a database using PHP?

One common pitfall when querying a database using PHP is not sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use parameterized queries or prepared statements to safely pass user input to the database.

// Example of using prepared statements to query a database in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

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

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

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