What are potential pitfalls when working with SQL queries in PHP?

One potential pitfall when working with SQL queries in PHP is SQL injection attacks, where malicious code is inserted into the query to manipulate the database. To prevent this, you should always use prepared statements with parameterized queries, which separate the SQL code from the user input.

// Example of using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$username = $_POST['username'];
$stmt->execute();

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