What are common errors to avoid when writing PHP scripts that interact with databases, like the one in the provided code snippet?

Common errors to avoid when writing PHP scripts that interact with databases include not sanitizing user input, not handling database connection errors properly, and not using prepared statements to prevent SQL injection attacks. To solve these issues, always sanitize user input before using it in database queries, handle database connection errors gracefully, and use prepared statements or parameterized queries to securely interact with the database.

// Example of using prepared statements to interact with a database

// Establish a database connection
$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 prepared statement
$stmt->bindParam(':username', $_POST['username']);

// Execute the prepared statement
$stmt->execute();

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

// Loop through the results and do something with them
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}