How can POST variables be properly sanitized and validated to prevent SQL injection attacks in PHP scripts?

To prevent SQL injection attacks in PHP scripts, POST variables should be properly sanitized and validated before being used in SQL queries. This can be done by using functions like mysqli_real_escape_string() to escape special characters and prepared statements to prevent malicious SQL queries.

// Sanitize and validate POST variables to prevent SQL injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Prepare a SQL statement using prepared statements
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Handle the user data
}

$stmt->close();
$conn->close();