What are some common pitfalls when handling database queries in PHP scripts?

One common pitfall when handling database queries in PHP scripts is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely interact with the database.

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

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

// Bind the parameter value
$stmt->bindParam(':username', $username);

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

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