What best practices should be followed when handling external variables like $_POST in PHP to prevent vulnerabilities such as SQL injection?

To prevent vulnerabilities such as SQL injection when handling external variables like $_POST in PHP, it is essential to properly sanitize and validate the input data. This can be done by using prepared statements with parameterized queries or by escaping input data using functions like mysqli_real_escape_string(). Additionally, it is crucial to avoid directly inserting user input into SQL queries without proper validation.

// Example of using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

if ($stmt = $mysqli->prepare("INSERT INTO users (username, password) VALUES (?, ?)")) {
    $stmt->bind_param("ss", $_POST['username'], $_POST['password']);
    $stmt->execute();
    $stmt->close();
}

$mysqli->close();