Collections functions
General functions
Node functions
Render functions
Theme permission functions
User functions
Resource functions

user_rating_save()

Parameters

ColumnTypeDefaultDescription
$userref
$ref
$rating

Location

include/resource_functions.php lines 5088 to 5155

Definition

 
function user_rating_save($userref,$ref,$rating)
    {
    
# Save a user rating for a given resource
    
$resource=get_resource_data($ref);

    
# Recalculate the averate rating
    
$total=$resource["user_rating_total"]; if ($total=="") {$total=0;}
    
$count=$resource["user_rating_count"]; if ($count=="") {$count=0;}

    
# modify behavior to allow only one current rating per user (which can be re-edited)
    
global $user_rating_only_once;
    if (
$user_rating_only_once)
        {
        
$ratings=ps_query("select user,rating from user_rating where ref=?",array("i",$ref));

        
#Calculate ratings total and get current rating for user if available
        
$total=0;
        
$current="";
        for (
$n=0;$n<count($ratings);$n++){
            
$total+=$ratings[$n]['rating'];

            if (
$ratings[$n]['user']==$userref){
                
$current=$ratings[$n]['rating'];
                }
            }
        
# Calculate Count
        
$count=count($ratings);

        
# if user has a current rating, subtract the old rating and add the new one.
        
if ($current!=""){
            
$total=$total-$current+$rating;
            if (
$rating == 0) {  //rating remove feature
                
ps_query("delete from user_rating where user=? and ref=?",array("i",$userref,"i",$ref));
                
$count--;
            } else {
                
ps_query("update user_rating set rating=? where user=? and ref=?",array("i",$rating,"i",$userref,"i",$ref));
            }
        }

        
# if user does not have a current rating, add it
        
else
            {
            if (
$rating != 0)
                { 
// rating remove feature
                
$total=$total+$rating;
                
$count++;
                
ps_query("insert into user_rating (user,ref,rating) values (?,?,?)",array("i",$userref,"i",$ref,"i",$rating));
                }
            }
        }
    else
        {
        
# If not using $user_rating_only_once, Increment the total and count
        
$total+=$rating;
        
$count++;
        }

    if (
$count==0){
        
# avoid division by zero
        
$average=$total;
    } else {
    
# work out a new average.
    
$average=ceil($total/$count);
    }

    
# Save to the database
    
ps_query("UPDATE resource SET user_rating = ?, user_rating_total = ?, user_rating_count = ? WHERE ref = ?", array("d"$average"i"$total"i"$count"i"$ref));
    }

This article was last updated 19th March 2024 05:05 Europe/London time based on the source file dated 11th March 2024 14:25 Europe/London time.