What are common pitfalls for beginners when working with PHP scripts and how can they be avoided?

One common pitfall for beginners when working with PHP scripts is not properly sanitizing user input, leaving the application vulnerable to security risks such as SQL injection attacks. To avoid this, always use prepared statements or parameterized queries when interacting with a database to prevent malicious code from being executed.

// Example of using prepared statements to avoid SQL injection
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $username]);
```

Another common pitfall is not handling errors effectively, which can lead to unexpected behavior or crashes in the application. To avoid this, always use try-catch blocks to catch and handle exceptions, and implement proper error logging to track and troubleshoot issues.

```php
// Example of using try-catch blocks to handle errors
try {
    // Code that may throw an exception
} catch (Exception $e) {
    // Handle the exception, log the error, and display a user-friendly message
    echo 'An error occurred: ' . $e->getMessage();
}
```

Additionally, beginners often overlook the importance of code organization and structure, leading to messy and hard-to-maintain code. To avoid this, follow best practices such as using meaningful variable names, breaking down complex tasks into smaller functions, and adhering to coding standards like PSR-1 and PSR-2.

```php
// Example of organizing code into smaller functions
function calculateTotal($price, $quantity) {
    return $price * $quantity;
}

$total = calculateTotal($productPrice, $productQuantity);