What are the best practices for handling file operations and database interactions in PHP scripts for beginners?

When handling file operations and database interactions in PHP scripts, beginners should always sanitize user input to prevent SQL injection attacks and validate file paths to avoid security vulnerabilities. It's also important to properly handle errors and exceptions to ensure the script runs smoothly and securely.

// Sanitize user input to prevent SQL injection
$userInput = $_POST['input'];
$cleanInput = mysqli_real_escape_string($connection, $userInput);

// Validate file path to avoid security vulnerabilities
$filePath = '/path/to/file.txt';
if (file_exists($filePath)) {
    // File operations here
} else {
    echo "File does not exist.";
}

// Properly handle errors and exceptions
try {
    // Database interactions here
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}