使用数学公式更新数据库

时间:2012-01-07 21:04:48

标签: php mysql select

我正在努力让我的评级系统成为我网站的基础。如何使用+1(到number_of_ratings)列更新数据库并将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">

1 个答案:

答案 0 :(得分:0)

您需要为此创建一个单独的表。列将是

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

或者,您也可以拥有ID字段,但这不是强制性的。然后,为了获得评级,您可以根据产品ID使用mysql的AVG()函数选择投票的平均值。如果他们之前已经对产品进行了投票,请记得更新人员评级

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

的用户