What best practices should be followed when handling variables and escape sequences in PHP scripts to prevent errors?

When handling variables and escape sequences in PHP scripts, it is important to properly sanitize user input to prevent errors such as SQL injection or cross-site scripting attacks. One way to achieve this is by using functions like mysqli_real_escape_string() or htmlspecialchars() to escape special characters. Additionally, always validate and sanitize input data before using it in SQL queries or outputting it to the browser to ensure the security and integrity of your application.

// Example of sanitizing user input using mysqli_real_escape_string()
$conn = mysqli_connect("localhost", "username", "password", "database");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);

    // Use $username and $password in SQL queries safely
}