drkshenronx Posted December 12, 2007 Share Posted December 12, 2007 Ok heres the deal .. I found this rating script online and I wanted to modify it a little bit so the information that it stored was also sent to a database so it would update everytime someone rated an item. First off there are 4 files that this uses and they are as follows: config, rating, rate, and index(this is where you select your rating). Below is the code from all of them by name ** In the index.php the value in quotes becomes the id number in the script ** show_ratings_control("2"); Index.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Rating Test</title> <link href="ratings/template/styles.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Rating Test</h1> <p> This page is intended to demonstrate how you can quickly add ratings to any page on your website. </p> <?php // The two lines below are all that is required to add a ratings // control to your page. Obviously, these need to be placed within // a PHP code block inside a valid PHP page. You will also need to // configure the settings in config.php properly. // // Modify these lines as follows: // // * Change the include path to reflect where DRBRatings is installed. // * Change the parameter for show_ratings_control() to reflect a unique // ID for the rating on this page. This feature allows you to store // more than one rating using the same installation of DRBRatings. // New IDs must be added to the VALID_RATING_IDS array in config.php. include_once('ratings/ratings.php'); show_ratings_control("1"); ?> </body> </html> Config.php <?php /**************************************************************************** * DRBRatings * http://www.dbscripts.net/ratings/ * * Copyright © 2007 Don Barnes ****************************************************************************/ // Modify this string to reflect the URL where DRBRatings is installed. // A trailing slash must be included. This URL will be used in the generated // HTML for the image tags, and in the URL for the form submission. $RATINGS_URL = 'ratings/'; // Names of the form input elements in the ratings form. // You probably won't need to change these unless the names conflict with some // other element on your pages. $RATING_ID_PARAM_NAME = "ratingid"; $RATING_PARAM_NAME = "rating"; // Precision to use when displaying the average rating $RATINGS_PRECISION = 2; // These are the file names for the star graphics. These graphics // files must be located immediately beneath the RATINGS_URL defined above. // Feel free to customize these graphics. $IMAGE_STAR_EMPTY = 'empty.png'; $IMAGE_STAR_HALF = 'half.png'; $IMAGE_STAR_FILLED = 'filled.png'; // These are the strings that are displayed in the rating control // and the result page. // Modify these to customize what is displayed to the user. $CURRENT_RATING_STRING = 'User Rating'; $RATING_STRING = '(%s out of %s)'; $NUMBER_OF_RATINGS_STRING = 'Rated %s times.'; $RATE_THIS_STRING = 'Rate it:'; $SUBMIT_BUTTON_STRING = 'Submit'; $RATING_LIST_DEFAULT_LABEL = 'Please Select'; $DUPLICATE_RATE_ERROR_MSG = 'You have already rated!'; $NO_RATING_SELECTED_ERROR_MSG = 'You forgot to select a rating!'; // The maximum number of stars per rating // Change this to customize the maximum number of stars. $MAX_STARS = 10; // List of valid rating IDs. All rating requests are checked against this list // to ensure that malicious users do not submit invalid rating IDs through a // cross-site request forgery. Add or modify values in this array to // customize the available rating IDs for new ratings forms. // All values in this array must be strings. In addition, they must // only use alphanumeric characters (A-Z, a-z, and 0-9). $VALID_RATING_IDS = array("1", "2", "3"); // Array containing labels for each rating value // If no labels are desired, simply leave the array blank. $RATING_LABELS = array( 1 => "Awful", 5 => "Average", 10 => "Excellent" ); ?> Rate.php <?php /**************************************************************************** * DRBRatings * http://www.dbscripts.net/ratings/ * * Copyright © 2007 Don Barnes ****************************************************************************/ include_once(dirname(__FILE__) . '/ratings.php'); function show_error() { global $rating_error_message; echo(htmlspecialchars($rating_error_message)); } // Handle action if(isset( $_POST[$RATING_PARAM_NAME] ) && isset( $_POST[$RATING_ID_PARAM_NAME] )) { // Reset error message global $rating_error_message; $rating_error_message = NULL; // Get parameter values from post $rating = trim($_POST[$RATING_PARAM_NAME]); $ratingid = trim($_POST[$RATING_ID_PARAM_NAME]); // Attempt to add a new rating if(add_new_rating($ratingid, $rating) === TRUE) { // Display success page include_once(dirname(__FILE__) . '/template/success.php'); } else { // Display error page include_once(dirname(__FILE__) . '/template/failure.php'); } } else { die("Invalid request."); } ?> Ratings.php <?php /**************************************************************************** * DRBRatings * http://www.dbscripts.net/ratings/ * * Copyright © 2007 Don Barnes ****************************************************************************/ include_once(dirname(__FILE__) . '/config.php'); $CHECK_FOR_DUPLICATE_RATINGS = TRUE; function show_ratings_control($id) { global $MAX_STARS; global $RATING_STRING; global $NUMBER_OF_RATINGS_STRING; global $CURRENT_RATING_STRING; // Validate parameters if(!is_valid_id($id)) { die('ERROR: An invalid rating ID was submitted.'); } // Get the current rating and rating count $summarylist = rating_summary_list($id); $ratingCount = get_rating_count($summarylist); $rating = get_current_rating($summarylist); // Initialize the display messages for the rating control $ratingString = sprintf($RATING_STRING, $rating, $MAX_STARS); $numberOfRatingsString = sprintf($NUMBER_OF_RATINGS_STRING, $ratingCount); // Output rating control echo("<div class=\"ratingsContainer\">\r\n"); echo("\t<div class=\"currentRating\">" . htmlspecialchars($CURRENT_RATING_STRING) . "</div>\r\n"); echo("\t<div class=\"rating\">\r\n"); show_stars($rating); echo("\t\t" . htmlspecialchars($ratingString) . "\r\n\t</div>\r\n"); echo("\t<div class=\"numberOfRatings\">" . htmlspecialchars($numberOfRatingsString) . "</div>\r\n"); show_rate_form($id); echo("</div>\r\n"); } function show_rate_form($id) { global $RATE_THIS_STRING; global $MAX_STARS; global $SUBMIT_BUTTON_STRING; global $RATING_LABELS; global $RATING_LIST_DEFAULT_LABEL; global $RATINGS_URL; global $RATING_ID_PARAM_NAME; global $RATING_PARAM_NAME; echo("\t<form class=\"rateIt\" method=\"post\" action=\"" . $RATINGS_URL . "rate.php\">\r\n"); echo("\t\t" . htmlspecialchars($RATE_THIS_STRING) . "\r\n"); echo("\t\t<select name=\"" . htmlspecialchars($RATING_PARAM_NAME) . "\">\r\n"); echo("\t\t\t<option value=\"\">" . htmlspecialchars($RATING_LIST_DEFAULT_LABEL) . "</option>\r\n"); for($i = 1; $i <= $MAX_STARS; $i++) { echo("\t\t\t<option value=\"" . $i . "\">" . $i); if(!empty($RATING_LABELS) && isset($RATING_LABELS[$i])) { echo(" - " . htmlspecialchars($RATING_LABELS[$i])); } echo("</option>\r\n"); } echo("\t\t</select>\r\n"); echo("\t\t<input type=\"hidden\" name=\"" . htmlspecialchars($RATING_ID_PARAM_NAME) . "\" value=\"" . htmlspecialchars($id) . "\" />\r\n"); echo("\t\t<input type=\"submit\" value=\"" . htmlspecialchars($SUBMIT_BUTTON_STRING) . "\" class=\"submit\" />\r\n"); echo("\t</form>\r\n"); } function show_stars($rating) { global $IMAGE_STAR_EMPTY; global $IMAGE_STAR_HALF; global $IMAGE_STAR_FILLED; global $MAX_STARS; // Iterate through the stars, and show the correct type of star image // based on the rating. for($i = 1; $i <= $MAX_STARS; $i++) { if($rating > $i - .5) { show_ratings_image($IMAGE_STAR_FILLED, "*"); } else if($rating > $i - 1) { show_ratings_image($IMAGE_STAR_HALF, "1/2"); } else { show_ratings_image($IMAGE_STAR_EMPTY, ""); } } } function show_ratings_image($filename, $alt) { global $RATINGS_URL; echo("\t\t<img src=\"" . $RATINGS_URL . urlencode($filename) . "\" alt=\"" . $alt . "\" />\r\n"); } function smarter_is_int($val) { return (is_numeric($val)?intval($val)==$val:FALSE); } function is_valid_id($id) { global $VALID_RATING_IDS; return (!empty($id) && preg_match('/^[a-zA-Z0-9]+$/D', $id) === 1 && in_array($id, $VALID_RATING_IDS, TRUE)); } function is_valid_rating($rating) { global $MAX_STARS; return (!empty($rating) && preg_match('/^[1-9][0-9]*$/D', $rating) === 1 && smarter_is_int($rating) && $rating >= 1 && $rating <= $MAX_STARS); } function get_rating_count($summarylist) { // Get rating count from summary if($summarylist === FALSE || count($summarylist) < 1) { return 0; } else { return $summarylist[0]; } } function get_current_rating($summarylist) { global $MAX_STARS; // Get total count $totalCount = get_rating_count($summarylist); if($totalCount == 0) return 0; // Prevent divide by zero // Calculate total ratings $totalRatings = 0; if($summarylist !== FALSE) { for($i = 1; $i <= $MAX_STARS; $i++) { if($i < count($summarylist)) { $totalRatings += $summarylist[$i] * $i; } } } // Return average global $RATINGS_PRECISION; return round($totalRatings / $totalCount, $RATINGS_PRECISION); } function add_new_rating($id, $rating) { global $rating_error_message; // Make sure rating wasn't left blank if(empty($rating)) { global $NO_RATING_SELECTED_ERROR_MSG; $rating_error_message = $NO_RATING_SELECTED_ERROR_MSG; return FALSE; } // Validate parameters if(!is_valid_id($id)) { die('ERROR: An invalid rating ID was submitted.'); } if(!is_valid_rating($rating) ) { die('ERROR: An invalid rating was submitted.'); } // Convert to integer value $rating = intval($rating); /////////////// Update new rating for specific ID in the ratings DB////////////////////// ///////////////////This is my Mysql Query////////////////////////////////////// $con = mysql_connect("localhost", "db_username", "db_pass"); if(!$con) { die ('could not connect:' . mysql_error()); } mysql_select_db("ratings", $con); mysql_query("UPDATE rating SET rating=".$rating." WHERE id =".$id."") ; mysql_close($con); /////////////////////////////End of my Database Query////////////////////// // Check for duplicate rating attempt global $CHECK_FOR_DUPLICATE_RATINGS; if($CHECK_FOR_DUPLICATE_RATINGS === TRUE) { $ipaddress = $_SERVER['REMOTE_ADDR']; if(has_rated($id, $ipaddress)) { global $DUPLICATE_RATE_ERROR_MSG; $rating_error_message = $DUPLICATE_RATE_ERROR_MSG; return FALSE; } } // Add rating rating_history_add($id, $ipaddress, $rating); rating_summary_add($id, $rating); return TRUE; } function rating_summary_file_path($id) { return dirname(__FILE__) . '/data/summary_' . $id . '.dat'; } function rating_history_file_path($id) { return dirname(__FILE__) . '/data/history_' . $id . '.dat'; } function rating_summary_list($id) { // Load existing $summarylist = @file(rating_summary_file_path($id)); if($summarylist !== FALSE) { $summarylist = array_map("trim", $summarylist); } return $summarylist; } function rating_summary_add($id, $rating) { // Get existing ratings $summarylist = rating_summary_list($id); // Open/create summary file $summary_fp = @fopen(rating_summary_file_path($id), "w"); if($summary_fp === FALSE) { die("Unable to open summary file for writing"); } @flock($summary_fp, LOCK_EX); // Update total rating count if($summarylist === FALSE || count($summarylist) < 1) { $count = 1; } else { $count = $summarylist[0] + 1; } fputs($summary_fp, $count . "\n"); // Add rating to history global $MAX_STARS; for($i = 1; $i <= $MAX_STARS; $i++) { if($summarylist === FALSE || $i > count($summarylist) + 1) { // This is the first rating for this number if($i == $rating) { $out = 1; } else { $out = 0; } } else { // Add to existing rating count for this number if($i == $rating) { $out = ($summarylist[$i] + 1); } else { $out = $summarylist[$i]; } } // Write out new rating count for this number fputs($summary_fp, $out . "\n"); } fclose($summary_fp); } function rating_history_add($id, $ipaddress, $rating) { // Open/create history file $history_fp = @fopen(rating_history_file_path($id), "a"); if($history_fp === FALSE) { die("Unable to open history file for writing"); } // Add IP address and rating to history @flock($history_fp, LOCK_EX); fclose($history_fp); } function explode_history($line) { return array_map("trim", explode("|", $line)); } function rating_history_list($id) { // Load existing rating history $summarylist = @file(rating_history_file_path($id)); if($summarylist !== FALSE) { $summarylist = array_map("explode_history", $summarylist); } return $summarylist; } function has_rated($id, $ipaddress) { // Find rating history $rating_history_list = rating_history_list($id); if($rating_history_list !== FALSE) { return( find_rating_history(trim($ipaddress), $rating_history_list) !== FALSE ); } else { return FALSE; } } function find_rating_history($ipaddress, $list) { // Search rating history for this IP address if(!empty($list)) { for($i = 0; $i < count($list); $i++) { if($list[$i][0] == $ipaddress) return $list[$i]; } } return FALSE; } function the_credits() { echo("<div class=\"credit\">Powered by DRBRatings, a <a href=\"http://www.dbscripts.net/ratings/\">free PHP ratings script</a></div>\n"); } ?> This is the query I'm running (its also on the ratings page so it may be better if you look at that) $con = mysql_connect("localhost", "db_username", "db_pass"); if(!$con) { die ('could not connect:' . mysql_error()); } mysql_select_db("ratings", $con); mysql_query("UPDATE rating SET rating=".$rating." WHERE id =".$id."") ; mysql_close($con); The problem is it is not using the new value for the $rating variable it is using the value I select when I choose my rating. Now I understand the concept behind this script so i will explain it a little more. The script stores the information to the scripts to 2 seperate dat files. One is the History which stores the ip, the total ratings, and the individual ratings(see below in example of summary.dat) I dont think we need to worry about this one because it seems like the script is calling the information from the summary.dat file (well to me anyways, and correct me if I am wrong). The second one is where I think the problem and solution is. Ok when you add a rating it adds it to a summary.dat file like so Ex: summary.dat 1. 50 //this is the total of all submitted ratings// //the rest are all of the individual ratings// 2. 5 3. 5 4. 5 5. 5 6. 5 7. 5 8. 5 9. 5 10. 5 11. 5 //so everyone would have rated it a 5// Then the script calls that information and adds the new value that is submitted and does the new math(with the added rating). This is the code that does the math // Return average global $RATINGS_PRECISION; return round($totalRatings / $totalCount, $RATINGS_PRECISION); Again I just want the new rating to be sent to a mysql database. If anyone could help it would be much appreciated. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.