What are some common pitfalls to avoid when working with database queries in PHP scripts?

One common pitfall to avoid when working with database queries in PHP scripts is SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to sanitize user input and prevent malicious SQL code from being executed.

// Example of using prepared statements to prevent SQL injection

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

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

// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);

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

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