Is there is proper way to do this. I want to calculate the average rating for a table and update the result in another table simultaneously. Im new to PHP and MYSQL and I would appreciate any help
$query=mysql_query("INSERT INTO review (username, restaurant, rating, review) VALUES ('$username','$restaurant','$rating','$review')");
if($query)
{
$avg_query="SELECT ROUND(AVG(rating),0) FROM review WHERE name =\"$restaurant\"";
$avg_result=mysql_query($avg_query);
$avg_row=mysql_fetch_array($avg_result);
$rating=$row['ROUND(AVG(rating),0)'];
if($avg_result)
{
$update_query= "UPDATE restaurant SET rating=\"$rating\" WHERE name =\"$restaurant\"";
$update_result=mysql_query($update_query);
}
}
else
{
}
Thanks!
UPDATE restaurant
SET rating= (SELECT ROUND(AVG(rating),0) FROM review WHERE name ='$restaurant')
WHERE name ='$restaurant'
I would combine the two into one like this:
$query=mysql_query("INSERT INTO review (username, restaurant, rating, review) VALUES ('$username','$restaurant','$rating','$review')");
if($query)
{
$avg_query="UPDATE restaurant a SET rating=(SELECT ROUND(AVG(rating),0) FROM review WHERE name =a.name) WHERE name ='".$restaurant."'";
$avg_result=mysql_query($avg_query);
}
else
{
}
Having said that, you should move over to either PDO or mysqli as the mysql_*
functions are depreciated.
Another option is to use a mysql trigger
. For example (don't hold me to the syntax):
CREATE TRIGGER after_insert_review
AFTER INSERT ON review
FOR EACH ROW
BEGIN
UPDATE restaurant
SET rating = (SELECT ROUND(AVG(rating),0) FROM review WHERE name = NEW.restaurant)
WHERE name = NEW.restaurant;
END
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.