Help - Search - Members - Calendar
Full Version: [Intermediate] Rate It!
Weborum Webmaster Forum > TUTORIAL ARCHIVE - tutorials & scripts to save you scouring the internet. Please feel free to add your own. > PHP Tutorials & scripts
Timo
This tutorial/script allows you to create a rating system. It's easy to add new rating polls. That is described in more detail within the script. Enjoy. cowboy.gif

This is the SQL query to use.
If you don't know how to add this using phpmyadmin, refer to Leo's tutorial.


CODE

CREATE TABLE `RateTable` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`rateID` INT NOT NULL ,
`IP` TEXT NOT NULL ,
`vote` TINYINT NOT NULL ,
`date` DATE NOT NULL ,
INDEX ( `ID` )
);


The following is the first section, the processing and displaying codes, they must go in the same file.

Place in a file name of your choice.
CODE

<?php

$dbHost =""; #Your db host
$dbUser =""; #username
$dbPass =""; #Pass
$dbname =""; #Name of the database.
?>

I suggest you put this in an external file and include ''; it, but it's up to you.
It'll work fine if you put it in the code, I find it annoying to retype though.
Or if you decide to switch servers, you're going to have a lot of fun changing them all.

CODE

<?php
function dbinsans($text) {
$text = strip_tags ($text, "");
$text = str_replace(chr(10),"",$text);
$text = str_replace(chr(13), "<br>", $text);
$text = str_replace("\"","*",$text);
$text = str_replace("'","*",$text);
$text = addslashes($text);
return($text);
}
?>

This protects us from some hackers. smile.gif

CODE

<?php
$ip = $_SERVER["REMOTE_ADDR"];
#logs user IP (used to check if they voted)


if (isset($_POST['submit']))
{
#if the user has clicked the submit button

$vote = dbinsans($_POST['select']);
#how the user voted, 0 - 10

$rateID = dbinsans($_POST['rateid']);
#which poll download they voted on! Allows multiple polls

#the next few pieces of code check the user IP against database at ID

$r=0;
#We're going to use the variable r as a switch to determine if they're in the database.

$db = mysql_connect("$dbHost","$dbUser","$dbPass");
#connecting to the database area

mysql_select_db($dbname,$db);
#selecting our database

$requete = "SELECT IP FROM RateTable WHERE rateID='$rateID'";
#A query to pull IPs from the RateTable at the ID

$result = mysql_query ($requete,$db);
#Should return ips of voters

while ($article = mysql_fetch_object($result))
{
#scrolls through the ips
 if ($article->IP == $ip)
  {
  $r=1;
#if they get here they're already in the system. Set r (our switch variable) to 1
  }
}

if ($r==0)
 {
 #if r is 0 they were not found in the previous query
 $sql = "INSERT INTO RateTable (rateID, IP, vote, date) VALUES ('$rateID', '$ip', '$vote', curdate())";
  #Creates the insert query string.

  mysql_query($sql, $db);
  #Queries the database and adds the user.

 }

}
?>

This code should go anywhere above the next section, in the head is fine for it even
Up to you.

CODE

<?php
$currentID= '1';
#Ok here is where it counts, the following is the code to display the select box.
#Let me tell you why currentID is important, let's say you grabbed this from
#A query of your file? Like a page that's listing it and describing it in detail
#You could set $currentID = to whatever variable you have for the download's unique ID
#AKA two tables and you'd be using the unique ID of the downloaded item and the
#ID here to connect them. It's up to you... You could just manually change this though.
#Just change 1 to whatever # of your downloads you want.


#check IP against database at ID code again

$r=0;
#r as a switch variable (I don't know if that's a recognized term, but I'm using it as a
#switch so I figured I'd call it that. Not to be confused with a switch statement.

$db = mysql_connect("$dbHost","$dbUser","$dbPass");
mysql_select_db($dbname,$db);

$requete = "SELECT IP FROM RateTable WHERE rateID='$currentID'";
#A query to pull IPs from the RateTable at the ID

$result = mysql_query ($requete,$db);
#Should return ips of voters

while ($article = mysql_fetch_object($result))
{
 if ($article->IP == $ip)
  {
  $r=1;
#if you want this code in detail, look above it's the same as I used up there.
  }
}
if ($r==0) #if there is no ip of our user in the database
{
 if (!isset($_POST['submit']))
 {
 #if submit has not been pressed, notice the !

 #the following is the form... if you know html most of it
 #should be recognizable... the $_SERVER['SCRIPT_NAME'] is a global
 #variable and returns whatever you name this file.

 echo '<form method="post" action="'.$_SERVER['SCRIPT_NAME'].'">';
 echo '<input name="rateid" value="'.$currentID.'" type="hidden" />';
echo ' <select name="select">';
echo '   <option value="1">1 - It\'s really bad.</option>';
echo '   <option value="2">2 - It\'s bad.</option>';
echo '   <option value="3">3 - It\'s alright.</option>';
echo '   <option value="4">4 - It\'s good.</option>';
echo '   <option value="5">5 - It\'s really good.</option>';
echo ' </select><br />';
 echo "<input type=\"submit\" name=\"submit\" value=\"Submit\" />";
 echo '</form><br />';
 }
}
else
{
#already voted area if their ip is in the db then they see this.
$one = 0;
$two = 0;
$three = 0;
$four = 0;
$five = 0;
#Setting all these variables to 0...


$db = mysql_connect("$dbHost","$dbUser","$dbPass");
mysql_select_db($dbname,$db);
$requete = "SELECT vote FROM RateTable WHERE rateID='$currentID'";
#A query to pull all the votes, but no other part, from the RateTable at the ID

$result = mysql_query ($requete,$db);


while ($article = mysql_fetch_object($result))
{  
switch ($article->vote)  
#the wonderful switch statement the vote should have 0-10
   {
   case 1: #if it equals 1
   $one++;
   break;
   case 2: #and so on
   $two++;
   break;
   case 3:
   $three++;
   break;
   case 4:
   $four++;
   break;
   case 5:
   $five++;
   break;
   }
}
$total = $one + $two + $three + $four +  
$five;
#A little algebra.

#The round function works like this round($integer,amount after decimal to round to)...
#If you know html and css this shouldn't be too bad.
#The image I have growing by %... It will fill the box it's in.
#you can edit at your own will :woot:  have fun
echo 'Total Votes '.$total.'<br />';
if ($total==0) # if the total happens to be zero
$total=1; #this way it still shows the accurate votes but also will not cause a div by zero error.
echo 'It\'s really bad. - '.round((($one/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($one/$total)*100),0)).'%; height:15px;" alt="" /><br />';
echo 'It\'s not up to par. - '.round((($two/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($two/$total)*100),0)).'%; height:15px;" alt="" /><br />';
echo 'It\'s alright. - '.round((($three/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($three/$total)*100),0)).'%; height:15px;" alt="" /><br />';
echo 'It\'s good. - '.round((($four/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($four/$total)*100),0)).'%; height:15px;" alt="" /><br />';
echo 'It\'s really good. - '.round((($five/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($five/$total)*100),0)).'%; height:15px;" alt="" /><br />';

}

?>

Place this where you want your select box.

That is all the code you need to display and process the select box...
That was fun, feel free to place any questions here.
The image I made for the table is attached, but you can make your own, or such.

-Timo cowboy.gif

Also: if you want radio buttons instead,
CODE
echo ' <select name="select">';
echo '   <option value="1">1 - It\'s really bad.</option>';
echo '   <option value="2">2 - It\'s bad.</option>';
echo '   <option value="3">3 - It\'s alright.</option>';
echo '   <option value="4">4 - It\'s good.</option>';
echo '   <option value="5">5 - It\'s really good.</option>';
echo ' </select><br />';

Change to,
CODE
echo '<input type="radio" name="select" value="1">1 - It\'s really bad.<br />';
echo '<input type="radio" name="select" value="2">2 - It\'s bad.<br />';
echo '<input type="radio" name="select" value="3">3 - It\'s alright.<br />';
echo '<input type="radio" name="select" value="4">4 - It\'s good.<br />';
echo '<input type="radio" name="select" value="5">5 - It\'s really good.<br />';



Alright, now you want to add another option? Sure thing.
Let's add one we'll call 6...

CODE
echo '<form method="post" action="'.$_SERVER['SCRIPT_NAME'].'" />';
echo '<input name="rateid" value="'.$currentID.'" type="hidden" />';
echo ' <select name="select">';
echo '   <option value="1">1 - It\'s really bad.</option>';
echo '   <option value="2">2 - It\'s bad.</option>';
echo '   <option value="3">3 - It\'s alright.</option>';
echo '   <option value="4">4 - It\'s good.</option>';
echo '   <option value="5">5 - It\'s really good.</option>';
echo ' </select><br />';
echo "<input type=\"submit\" name=\"submit\" value=\"Submit\" />";
echo '</form><br />';

After
echo ' <option value="5">5 - It\'s really good.</option>';

add

echo ' <option value="6">6 - It\'s perfect.</option>';

CODE
$one = 0;
$two = 0;
$three = 0;
$four = 0;
$five = 0;
#Setting all these variables to 0...

set $six to zero...
CODE
$six = 0;



CODE
switch ($article->vote)  
#the wonderful switch statement the vote should have 0-10
  {
  case 1: #if it equals 1
  $one++;
  break;
  case 2: #and so on
  $two++;
  break;
  case 3:
  $three++;
  break;
  case 4:
  $four++;
  break;
  case 5:
  $five++;
  break;
  }

after
$five++;
break;
add
CODE
$six++;
  break;



CODE

$total = $one + $two + $three + $four +  
$five;

Here change to,
CODE

$total = $one + $two + $three + $four +  
$five+$six;




CODE

echo 'It\'s really bad. - '.round((($one/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($one/$total)*100),0)).'%; height:15px;" alt="" /><br />';
echo 'It\'s not up to par. - '.round((($two/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($two/$total)*100),0)).'%; height:15px;" alt="" /><br />';
echo 'It\'s alright. - '.round((($three/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($three/$total)*100),0)).'%; height:15px;" alt="" /><br />';
echo 'It\'s good. - '.round((($four/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($four/$total)*100),0)).'%; height:15px;" alt="" /><br />';
echo 'It\'s really good. - '.round((($five/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($five/$total)*100),0)).'%; height:15px;" alt="" /><br />';

Just add after that last code.
CODE
echo 'It\'s perfect. - '.round((($six/$total)*100),2).'%<br /><img src="rating.gif" style="width:'.(round((($six/$total)*100),0)).'%; height:15px;" alt="" /><br />';


Edit - 3/13/04: Never accounted for zero total votes, thanks Joe.
Edit - 3/16/04: Loads in itself and don't need a seperate file.
Timo
ph34r.gif I knew I forgot something, here is the image I used.

The board will give it a weird name when you download it, whatever you use, remember to name it... 'rating.gif' or change the code above.
Josh
awesome tutorial timo!
Timo
QUOTE (Josh @ Mar 12 2004, 10:55 PM)
awesome tutorial timo!

biggrin.gif Thanks.
Joe
ok, for an idiot like me can you explain this bit in a bit more detail

QUOTE
I suggest you put this in an external file and include ''; it, but it's up to you.
It'll work fine if you put it in the code, I find it annoying to retype though.
Or if you decide to switch servers, you're going to have a lot of fun changing them all.
Timo
Sure thing... You can make a seperate file... let's call it serverinfo.php
Now within serverinfo.php place just this...
CODE

<?php

$dbHost =; #Your db host
$dbUser =; #username
$dbPass =; #Pass
$dbname =; #Name of the database.
?>


Now whenever I write
CODE
<?php

$dbHost =; #Your db host
$dbUser =; #username
$dbPass =; #Pass
$dbname =; #Name of the database.
?>

anywhere in the code, instead place
CODE
<?php include 'serverinfo.php';?>

Now let's say you change servers ok? Instead of having to change every file to point to your new mysql database, you just change the one file and every file that points to it will now be accessing the new variable definitions. Saves time. :-) Cleans up code too.

If you need me to explain it better feel free to ask on points, but I think that covers it.

-Tim
Joe
ok, i think that explains it so i can understand it biggrin.gif

going to try it
Joe
hey, i got it working biggrin.gif

looks good timo, i just want to know how to make a few changes

the results look fine, but what if you wanted radio buttons instead of a drop down list?

like attached
Timo
CODE
echo ' <select name="select">';
 echo '   <option value="0">0 - It sucks, alot.</option>';
 echo '   <option value="1">1 - It\'s really really bad.</option>';
 echo '   <option value="2">2 - It\'s really bad.</option>';
 echo '   <option value="3">3 - It\'s bad.</option>';
 echo '   <option value="4">4 - It\'s semi-alright.</option>';
echo '   <option value="5">5 - It\'s alright.</option>';
 echo '   <option value="6">6 - It\'s good.</option>';
 echo '   <option value="7">7 - It\'s really good.</option>';
 echo '   <option value="8">8 - It\'s really really good.</option>';
 echo '   <option value="9">9 - It\'s excellent.</option>';
 echo '   <option value="10">10 - It\'s perfect.</option>';
 echo ' </select><br />';


to

CODE


echo '<input type="radio" name="select" value="0">0 - It sucks, alot.<br />';
echo '<input type="radio" name="select" value="1">1 - It\'s really really bad.<br />';
echo '<input type="radio" name="select" value="2">2 - It\'s really bad.<br />';
echo '<input type="radio" name="select" value="3">3 - It\'s bad.<br />';
echo '<input type="radio" name="select" value="4">4 - It\'s semi-alright.<br />';
echo '<input type="radio" name="select" value="5">5 - It\'s alright.<br />';
echo '<input type="radio" name="select" value="6">6 - It\'s good.<br />';
echo '<input type="radio" name="select" value="7">7 - It\'s really good.<br />';
echo '<input type="radio" name="select" value="8">8 - It\'s really really good.<br />';
echo '<input type="radio" name="select" value="9">9 - It\'s excellent.<br />';
echo '<input type="radio" name="select" value="10">10 - It\'s perfect.<br />';

I didn't test it, but that should work.


Also if you want less numbers showing up on your results page just delete the cells that deal with the higher numbers... Other wise they'd just show up as 0%. It's not really a big deal, but up to you.

-Tim
Joe
made some changes, still got errors though

could you take a look at it for me please
Timo
QUOTE (joe2kiss @ Mar 13 2004, 02:00 PM)
made some changes, still got errors though

could you take a look at it for me please

What line and which file has the error?
Timo
oh lol you made those changes before looking at my update.

You didn't use the right name, this should work, I reckon. Not sure what else you changed though...
Joe
QUOTE
Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 72

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 72
Zero - 0% 

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 73

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 73
One - 0% 

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 74

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 74
Two - 0% 

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 75

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 75
Three - 0% 

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 76

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 76
Four - 0% 

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 77

Warning: Division by zero in c:\program files\easyphp1-7\www\rateit\ratings.php on line 77
Timo
Errr that's right, when I tested it I had values... Give me a min.
Joe
you are right, it was because there were no values in the results, i submitted and then viewed the results and it was error free
Timo
I'll change it above too but...

CODE

echo '<tr><td colspan="2">Data Table for Download with the ID '.$rateID.' ... The total amount of votes - '.$total.'</td></tr>';


CODE

echo '<tr><td colspan="2">Data Table for Download with the ID '.$rateID.' ... The total amount of votes - '.$total.'</td></tr>';
if ($total==0) # if the total happens to be zero
$total=1; #this way it still shows the accurate votes but also will not cause a div by zero error.
Timo
QUOTE (joe2kiss @ Mar 13 2004, 02:17 PM)
you are right, it was because there were no values in the results, i submitted and then viewed the results and it was error free

Yep, thanks for that, haha. All fixed up.

-Timo
Joe
great tutorial m8 biggrin.gif

im going to see if i can change the way the results are displayed now lol
Timo
QUOTE (joe2kiss @ Mar 13 2004, 02:28 PM)
great tutorial m8 biggrin.gif

im going to see if i can change the way the results are displayed now lol

Yeah I was never good at making things look pretty. Haha. I also may update the results part later, I just was rushing to get it up. I have it write the date the person voted in the database... Using that it's possible to also chart how often people have been voting and such... Like which dates and so on... If my host allowed me to use the php image stuff I'd do something nice with it too, but since that's a no, I have no idea how to use the image stuff. sad.gif Well good luck with it.
Josh
Hi timo, couple questions on how it works. What does the variable $r do? And what is the part in red for:

echo '<form method="post" action="'.$_SERVER['SCRIPT_NAME'].'" />';
Timo
QUOTE (Josh @ Mar 13 2004, 04:05 PM)
Hi timo, couple questions on how it works. What does the variable $r do? And what is the part in red for:

echo '<form method="post" action="'.$_SERVER['SCRIPT_NAME'].'" />';

I was using $r to determine if the user was already in the database. First I set it default to 0. Then when I scanned through the rows to see if the user was in the database if it found the user it set it to 1. Then below the database checking there is a conditional statement asking if $r is equal to 0 (it would be equal to 0 if the user was not found in the database) so then it goes on.

:-)


$_SERVER['SCRIPT_NAME'] is a global variable. It contains the name of the script being executed. So, let's say you name the file Josh.php that the script is in. The variable would hold "Josh.php" so it makes it so you aren't stuck naming the script and having to go into the file and change it later.

cowboy.gif

If you're still confused, feel free to ask.

-Timo
Josh
Oh i see, thanks biggrin.gif
Xan
i ahve added the mysql entries

CREATE TABLE `RateTable` (
`ID` INT NOT NULL AUTO_INCREMENT ,
`rateID` INT NOT NULL ,
`IP` TEXT NOT NULL ,
`vote` TINYINT NOT NULL ,
`date` DATE NOT NULL ,
INDEX ( `ID` )
);

but i still get errors on my page

QUOTE
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in /var/www/scottydog.qc1.net/poll/index.php on line 84


thats on the index page

QUOTE
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in /var/www/scottydog.qc1.net/poll/ratings.php on line 37


and thats on my rating.php

:S

after a little edit, im just left with that
Timo
You have the table in MySQL?
Double check your database variables...

Remember to quote them if you haven't.
-Tim
Xan
i have it in my table in MySQL i just copied it in like that!
Timo
Your database variables, to allow access to the database though, are they quoted?

-Tim

(They're in your script)
Joe
where does the hacker bit go?

does it go in the separate file (serverinfo.php) or on the poll.php page?
Timo
You mean the dbinsans? it goes in the file...? it doesn't matter. If you use a function a lot you should put it in an external file but if you don't in the file is fine.
Oh and for people looking, it doesn't hack, it protects against it. smile.gif
-Tim

Joe if you're just editting an old version you'll have to change the $_POST[''] lines as well...
Joe
QUOTE (Timo @ Apr 6 2004, 01:54 PM)
Joe if you're just editting an old version you'll have to change the $_POST[''] lines as well...

ok, just that line though yeah?
Joe
just add this
QUOTE
<?php
function dbinsans($text) {
$text = strip_tags ($text, "");
$text = str_replace(chr(10),"",$text);
$text = str_replace(chr(13), "<br>", $text);
$text = str_replace("\"","*",$text);
$text = str_replace("'","*",$text);
$text = addslashes($text);
return($text);
}
?>
and then edit these lines

if (isset($_POST['submit']))
$vote = dbinsans($_POST['select']);
if (!isset($_POST['submit']))

just those 3?
Timo
$vote = dbinsans($_POST['select']);

$rateID = dbinsans($_POST['rateid']);
Joe
thanks man, made the changes now biggrin.gif
Bushido
hey timo, do you think you can put thoses together in a zip file for me. Please. Thanks.
Timo
QUOTE (Bushido @ Jul 8 2004, 12:52 PM)
hey timo, do you think you can put thoses together in a zip file for me. Please. Thanks.

Yep let me go find a link... I've had it all put together on my site.
http://www.alphibia.com/linkout.php?link=24

That should be the one. smile.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.