What are the considerations for storing and calculating total votes and average ratings in a PHP script?

When storing and calculating total votes and average ratings in a PHP script, it's important to properly sanitize and validate user input to prevent SQL injection attacks. Additionally, you should ensure that the data is stored securely in a database and that calculations are accurate to prevent any manipulation of results.

// Sanitize and validate user input for total votes and average ratings
$total_votes = filter_var($_POST['total_votes'], FILTER_VALIDATE_INT);
$average_rating = filter_var($_POST['average_rating'], FILTER_VALIDATE_FLOAT);

// Store total votes and average ratings securely in a database
// Assuming $conn is a valid database connection
$query = "INSERT INTO ratings (total_votes, average_rating) VALUES (?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param("id", $total_votes, $average_rating);
$stmt->execute();

// Calculate total votes and average ratings
$query = "SELECT SUM(total_votes) AS total_votes, AVG(average_rating) AS average_rating FROM ratings";
$result = $conn->query($query);
$row = $result->fetch_assoc();

$total_votes = $row['total_votes'];
$average_rating = $row['average_rating'];

echo "Total Votes: " . $total_votes . "<br>";
echo "Average Rating: " . $average_rating;