正在使用数学公式更新数据库


Updating database with math formulas

我正在努力让我的评级系统运转起来,这将是我网站的基础。如何使用+1(到number_of_rates)列更新数据库,并将1到5(取决于用户输入[他们的评分])添加到ratings_value列。然后在php中对它们进行划分,得出average_rating,但我相信这是正确的。我对事先准备好的陈述很陌生,这正是我努力解决的问题。谢谢

<?php
include'config.php';
// Check Connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s'n", mysqli_connect_error());
exit();
}
$query = "SELECT brand, name, ratings_value, number_of_ratings, average_price, review, image, ratings_value FROM Products WHERE product_id = 0";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s<br />%s<br />%s<br />%s<br />%s<br />%s'n",
$row["brand"],
$row["name"],
$average_rating = $row["ratings_value"]/$row["number_of_ratings"],
$number_of_ratings = $row["number_of_ratings"],
$row["average_price"],
$row["review"],
$ratings_value = $row["ratings_value"]);
// using this will round value to nearest quarter - 0.25 - using 3 (nearest third), using 2 (nearest half), using 10 (nearest 10th)
//$average_rating = round(($average_rating*4), 0)/4;
$average_rating = round(($average_rating),2);
$background = round($average_rating/5*120);
if ($average_rating <= 5){ 
print ("<div style='"width:{$background}px; background-color:#ffff00'"><img style='"width:120px; height:30px'" src='"stars.png'" /></div>");
}
else { 
print ("A value over 5? Not possible!<br />We are working to solve this as soon as we can");
}
?>
<form method="POST" action="womensjeggings.php">
<input type="radio" name="new_ratings_value" value="1" />1<img src="small_star.png">&nbsp;
<input type="radio" name="new_ratings_value" value="2" />2<img src="small_star.png">&nbsp;
<input type="radio" name="new_ratings_value" value="3" />3<img src="small_star.png">&nbsp;
<input type="radio" name="new_ratings_value" value="4" />4<img src="small_star.png">&nbsp;
<input type="radio" name="new_ratings_value" value="5" />5<img src="small_star.png">
<input type="hidden" name="new_number_of_ratings" value="1" />
<input type="submit" />
</form>

//womensjeggings.php-很可能,远非正确的

<?php
mysql_query("UPDATE Products SET ratings_value = '$ratings_value+$new_ratings_value', number_of_ratings = '$number_of_ratings+$new_number_of_ratings' WHERE product_id = 0");
?>
<meta http-equiv="refresh" content="2;url=index.php">

您需要为此创建一个单独的表。色谱柱应为

user_id (int)
product_id (int)
rating (int)

可选地,您也可以有一个ID字段,但它不是强制性的。然后要获得评级,您可以使用mysql的AVG()函数根据产品ID选择投票的平均值。记住,如果在之前对产品进行了投票,请更新人员评级

当然,这是假设您的应用程序具有用户ID的的用户