I'm trying to update my field 'avg_rating' within the the plus2net_rating rating table with the average rating that is in the field 'rating'. Seems simple enough but it's not working.

require "conn.php"; 
$sql2="UPDATE plus2net_rating SET avg_rating = (SELECT AVG(rating) FROM plus2net_rating WHERE page_name = ".$page_name.")";
$result=mysqli_query($con,$sql2) or die(mysqli_error());

    I suspect you need some quotes around the string literal, which can be more easily seen when you let PHP do variable interpolation with the main double-quoted string):

    $sql2="UPDATE plus2net_rating SET avg_rating = (SELECT AVG(rating) FROM plus2net_rating WHERE page_name = '$page_name')";
    

      A. The average is derived information and should not be stored. You would query for it whenever it is needed, so that you will always have a current and accurate value.
      B. You are probably lucky that the query isn't executing since it would update all the rating rows of data with the same value, regardless of which page the rating row is for.
      C. You are likely getting an sql syntax error, about a non-existent column in the where clause having the name of the value in $page_name, but your code isn't telling you this since the msyqli_error statement usage is incorrect. It requires the connection as a parameter. In your last thread you were using the much better and simpler PDO database extension. Why are you now using the mysqli extension and are not using a prepared query (edit: a prepared query would actually solve the sql syntax error) when supplying an external, unknown, dynamic value to the sql statement when it gets executed?

        Write a Reply...