我有一个评分系统,它使用以下等式生成评分平均值:
((旧评级*旧时金额)+新评级)/新评级金额
但是,如果当前评分是 3,并且它被评分过一次,当我给它评分 3 时,它说新评分是 2.5
这里有什么错误?这是完整的代码。
<?php
session_start();
include("lib/db.php");
$db = new DBConnect;
if(isset($_POST['rating']) && is_numeric($_POST['rating']) && is_numeric($_POST['story']))
{
if($_POST['rating'] > 5 || $_POST['rating'] < 1){die("INVALID RATING");}
$rating = mysql_real_escape_string($_POST['rating']);
$story = mysql_real_escape_string($_POST['story']);
$c = $db->query("SELECT * FROM cdb_stories WHERE id=$story");
$c = mysql_fetch_array($c);
$u_name = mysql_real_escape_string($_SESSION['logged_in']);
$uid = $db->query("SELECT id FROM cdb_users WHERE username='{$u_name}'");
if(mysql_num_rows($uid) < 1){die("NOT LOGGED IN");}
$uid = mysql_fetch_array($uid);
$ratingd = $db->query("SELECT * FROM cdb_ratings WHERE userid='{$uid['id']}'");
if(mysql_num_rows($ratingd) > 0)
{
$ratingd = mysql_fetch_array($ratingd);
$new_rate = (($c['rating']*$c['rating_amt'])-$ratingd['rating']+$rating)/$c['rating_amt'];
$db->query("UPDATE cdb_stories SET rating={$new_rate} WHERE id={$story}");
$db->query("UPDATE cdb_ratings SET rating={$rating} WHERE userid='{$uid['id']}'");
die();
}
$new_num = $c['rating_amt']+1;
$new_rate = (($c['rating']*$c['rating_amt'])+$rating)/$new_num;
$db->query("UPDATE cdb_stories SET rating_amt={$new_num}, rating={$new_rate} WHERE id={$story}");
$db->query("INSERT INTO cdb_ratings VALUES({$uid['id']},{$rating},{$story})");
}
else
{
die("INVALID FIELDS");
}
?>