PHP Rating System Tutorial
Feb 2, 02:23 AM By Eoghan O'Brien.OK, so what do I need, well...
* Access to PHPMyAdmin
* A php/html editor
* Something to drink
If you have all these, then we're ready to go, the way this is gonna work is i'm gonna make a rating system for rating the quality of an article. I'll give you the code then I'll explain each section.
First of all we're goin to get your database set up!
CREATE TABLE `articles` (
`id` int(11) NOT NULL auto_increment,
`header` varchar(255) NOT NULL default '',
`body` text NOT NULL,
`date` datetime NOT NULL default '0000-00-00 00:00:00',
`slug` varchar(255) NOT NULL default '',
`article_rating` float NOT NULL default '0',
`article_num_votes` int(11) NOT NULL default '0',
PRIMARY KEY (`id`)
);
This is all basic MySQL stuff the row slug can be left out if you wish, thats for using search engine friendly URL's if you want a function that will turn your header into a slug, let me know and i'll sort you out.
Next onto the PHP, an firstly of course we need the db connection.
// Define Server Connection Variables
define("HOST", "localhost");
define("USER", "yourusername");
define("PASS", "yourpassword");
define("DB", "yourdbname");
if ($dbc=@mysql_connect(HOST,USER,PASS)) {
if (!mysql_select_db(DB)) {
echo "Could not select the database: ".mysql_error();
echo "<br />The site management system is currently experiencing technical difficulties!.<br /> "
."We apologize for any inconvenience.";
exit();
}
} else {
echo "Could not connect to the database: ".mysql_error();
echo "<br />The site management system is currently experiencing technical difficulties.<br /> "
."We apologize for any inconvenience.";
exit();
}
This is basically just to connect to the database, its checking to see if it can connect to the database then if it can select the database, if it cant it sends the user an error message. Save this file as dbc.php.
Next we have to create our functions page. This page will have 3 functions which will:
* Create a Rating Menu - rateMenu($id) - Accepts an Id
* Insert the Rating Into the Database - doRating($id,$rating) - Accepts an Id and the rating from the form
* Create the images to represent to rating - makeImages($article_rating) -
We'll start with the rating menu...
/*=======================================
Rate Menu Fucntion
=======================================*/
function ratemenu($id) {
$output=<<<HTML
<form name="rating" method="post" action="actions.php">
<strong>Rate this Article:</strong>
<select name="rating">
<option value="5.00" selected>5 - This is the Crunk!<-/option>
<option value="4.00">4 - Very Informative</option>
<option value="3.00">3 - Good Effort</option>
<option value="2.00">2 - Needs some more work</option>
<option value="1.00">1 - Could be better</option>
<option value="0.00">0 - This is Junk!</option>
<input type="hidden" name="action" value="doRating" />
<input type="hidden" name="id" value="$id" />
<input type="submit" value="Rate!" />
</select>
</form>
HTML;
echo $output;
}This function simply creates your rating form, take note of the action in the form, its going to actions.php, that will be of importance later on in the script. Also, note the hidden fields which send the id of the article and the rating with the form.
Next Up, DoRating($id, $rating) Function...
/*=======================================
Do Rating Function
============================
function doRating($id, $rating) {
if (session_is_registered("article$id")){
$_SESSION['ratemsg']="You already voted";
} else {
$sql="SELECT article_rating, article_num_votes FROM articles WHERE id=$id";
$get_count=mysql_query($sql);
while(list($article_rating, $article_num_votes)=mysql_fetch_array($get_count)){
$new_count = ($article_num_votes + 1);
$article_rating2 = ($article_rating * $article_num_votes);
$new_rating = (($rating + $article_rating2) / ($new_count));
$new_rating2 = number_format($new_rating, 2, '.', '');
$update_rating = mysql_query("UPDATE articles SET article_rating='$new_rating2',article_num_votes='$new_count' WHERE id=$id");
$sessionvar = "article$id";
session_register($sessionvar);
}
$_SESSION['ratemsg']="Thanks for your vote!";
}
}
This is the only different part to the script, whats happening here is the function is checking to see if you've already voted on this article by checking if "article$id"(eg.article4) is registered if it is it passes the "ratemsg" variable into the session array and wont allow anyone to vote on it again while that session is still there.
If "article$id" is not set then it continues on with the script by Selecting the rating and number of votes from the articles table, then adds 1 to the number of votes, multiplies the article rating by the number of votes, then adds the rating given by the user to the sum of the article rating by the number of votes and divides that the new number of votes(ie. the amount of votes originally in the database + 1). Then it puts the number in the correct decimal format and Updates the values in the database.
Finally, it registers the "article$id" variable in the session and sends a thank you message to the "ratemsg" session variable. Damn, thats a lot of text and we're only half way there.
Ok. Next Up and the final function we need to write is a function to show images for each value. I think this is a far better way of showing the rate rather than using crappy text like 4.5/5
/*===================
Make Images based on the score
===================*/
function makeImages($article_rating) {
if((($article_rating >= 0)or($article_rating == 0)) && ($article_rating <= 0.50)){
echo "<img src='rating/0.gif' width='100' height='16' />";
}
if((($article_rating >= 0.50)or($article_rating == 0.50)) && ($article_rating <= .99)){
echo "<img src='rating/05.gif' width='100' height='16' />";
}
if((($article_rating >= 1.00)or($article_rating == 1.50)) && ($article_rating <= 1.49)){
echo "<img src='rating/10.gif' width='100' height='16' />";
}
if((($article_rating >= 1.50)or($article_rating == 1.50)) && ($article_rating <= 1.99)){
echo "<img src='rating/15.gif' width='100' height='16' />";
}
if((($article_rating >= 2.00)or($article_rating == 2.00)) && ($article_rating <= 2.49)){
echo "<img src='rating/20.gif' width='100' height='16' />";
}
if((($article_rating >= 2.50)or($article_rating == 2.50)) && ($article_rating <= 2.99)){
echo "<img src='rating/25.gif' width='100' height='16' />";
}
if((($article_rating >= 3.00)or($article_rating == 3.00)) && ($article_rating <= 3.49)){
echo "<img src='rating/30.gif' width='100' height='16' />";
}
if((($article_rating >= 3.50)or($article_rating == 3.50)) && ($article_rating <= 3.99)){
echo "<img src='rating/35.gif' width='100' height='16' />";
}
if((($article_rating >= 4.00)or($article_rating == 4.00)) && ($article_rating <= 4.49)){
echo "<img src='rating/40.gif' width='100' height='16' />";
}
if((($article_rating >= 4.50)or($article_rating == 4.50)) && ($article_rating <= 4.99)){
echo "<img src='rating/45.gif' width='100' height='16' />";
}
if($article_rating == 5.0){
echo "<img src='rating/50.gif' width='100' height='16' />";
}
}
This function is very simple, all its doing is taking the rating given from which ever article you're viewing and divides it up to give you the corresponding image. You can of course change the images to suit your needs.
Now that you have all 3 functions in one page, Save it as functions.php
Now, you're almost there.
Next you have to co-ordinate each script and make them work together. To do this, create a new page and type or paste the following...
<?php
session_start();
include "dbc.php";
include "functions.php";
$aid=$_GET['id'];
switch ($_GET['type']) {
case "article":
$sql="SELECT * FROM articles WHERE id=$aid";
$query=mysql_query($sql);
if (!$query) { echo "Error: ".mysql_error(); }
$row=mysql_fetch_array($query);
// You can also check for errors here if you wish, again I'm not going to
$id = $row['id'];
$header = $row['header'];
$date = $row['date'];
$body = $row['body'];
$article_rating = $row['article_rating'];
$article_num_votes = $row['article_num_votes'];
// Echo back the format for your article
echo "<h1>".$header."</h1>"
."<h4>".$date."</h4>"
."<p>".$body."</p>";
?>
<h3>Rating: </h3>
<?php
makeImages($article_rating);
?>
<?php
$id=$_GET['id'];
if (session_is_registered("article$id")) {
echo $_SESSION['ratemsg'];
} else {
ratemenu($id);
}
/* This will give you something like 4.25/5 of 25 Votes
echo "$article_rating/5 of $article_num_votes Votes";*/
break;
default:
$sql="SELECT * FROM articles";
$query=mysql_query($sql);
// You can check for errors here if you wish, I'm not going to
while ($row=mysql_fetch_array($query)) {
$id = $row['id'];
$header = $row['header'];
echo "<a href='index.php?type=article&id=".$id."'>".$header."</a>";
}
break;
}
?>
Ok then, this little snippet of code is basically just a template from which you can work, I've made it very basic just to get the point across. Save this file as index.php
And...Finally... the final part of the script.
<?php
session_start();
include "dbc.php";
include "functions.php";
switch ($_POST['action']) {
case "doRating":
$id=$_POST['id'];
$rating=$_POST['rating'];
doRating($id,$rating);
$referer=$_SERVER['HTTP_REFERER'];
header("Location: $referer");
break;
}
?>
Save this file as actions.php. And that's all folks. Have fun!
If anyone wants to do modifications to this, then you’ll be pleased to know it’s implemented in a coding Wiki (the CWH Coding Wiki). See http://www.coding.cwhnetworks.com/index.php/PHP_Rating_System
The Wiki allows you to change any of the pages . Please see http://coding.cwhnetworks.com/ for more information on the Wiki.
Cool! These are great Eoghan!! I hope these get archived.. deffo going to try it out some time!