What are some common pitfalls to avoid when writing PHP scripts that interact with databases?

One common pitfall to avoid when writing PHP scripts that interact with databases is not properly sanitizing user input, which can leave your application vulnerable to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries instead of concatenating user input directly into your SQL queries. Example:

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

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

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

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

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