Switch to full style
:read: Start PHP with us. Includes topics to help you in php
Post a reply

Add voting by stars images to your website content

Tue Jan 29, 2013 11:52 pm

In this article we talk about how to add a voting stars your PHP project , we use example for rating web sites (themes) on a themes database website where use vote each style(Anything in your case), for sure the example proposed in this article can be implemented at any website, the voting module presented in this example allow you the following functionality:
VotingExample.gif
Voting page screenshot
VotingExample.gif (20.56 KiB) Viewed 46633 times

  • Use stars images to define vote degree.
  • Save the vote in the database without changing the current webpage.
  • Use JavaScript to change stars images.
  • Disable the user re-vote for the current page only, it means when u close the browser or open the page again , you can re-vote ,(Can be enhanced using IP address)
  • A message appears for the user when one tries to re-vote "You have already voted".

This example uses a code snippets from larger project we have implemented lately, the most important page is the view style PHP page when user can view, comment and vote for a specific style ( or any topic in your case).
php code
<div class='content'>
<?php

$styleID=$_GET['styleID'];
$pathlocation="../../../";
$rating2 = 0;

$result2=GetStyleById($styleID);
$noticia = mysql_fetch_array($result2);

$datapath= $pathlocation."stylesdata/".$TYPE_NAME;
$image=$datapath."/images/".$noticia['STYLE_ID'].".PNG";
$file=$noticia['STYLE_NAME']."_".$noticia['STYLE_ID'].".zip&id=".$styleID;
$STYLE_NAME=$noticia['STYLE_NAME'];
$query2=" update styles set VIEWS= VIEWS+1 where STYLE_ID= ".$styleID;
$result2=mysql_query($query2);
echo mysql_error();

include 'Controllers/ratingcontroller.php';
$rating = rateValue($styleID,$rating2);
echo " <div class='styleroundcont'>
<div class='styleroundtop'>
<img src='".$pathlocation."Template/Images/c1.gif'
width='15' height='15' class='corner'
style='display: none' /></div><center>";

echo "<strong>$noticia[STYLE_NAME]</strong><br />";
echo "<img name='$image' alt=$noticia[STYLE_NAME] src='$image' width='150' height='112' /><br />";

echo " </center> <div class='styleroundbottom'>
<img src='".$pathlocation."Template/Images/c4.gif'
width='15' height='15' class='corner'
style='display: none' /> </div></div><br/>";
?>

<script>
var rating=-1;
function doVoteNow(val){
if(rating<1||rating>5)
{

if(val== 1){

rating = 1;
}
else if(val== 2){

rating = 2;
}
else if(val== 3){

rating = 3;
}
else if(val== 4){

rating = 4;
}
else if(val== 5){

rating = 5;
}

document.getElementById("rate").innerHTML="Thanks for rating.";
document.getElementById("rateValue").value = val;
document.getElementById("styleId").value = <?php echo $styleID;?>;
document.ratingForm.submit();
<?php $rateflag=false; ?>
}

}
function over(val){

if(rating<1||rating>5)
document.getElementById("rate").innerHTML=val;
else
document.getElementById("rate").innerHTML="you have already rated."+rating;

}
function out(){
document.getElementById("rate").innerHTML="";
}



function validateComment()
{
//alert("Please enter name");
document.getElementById('errorDiv').innerHTML="";
var errorDiv = document.getElementById('errorDiv');
var name = document.getElementById('username').value;
var comment = document.getElementById('comment').value;



if(name== null || name=="")
{
//alert("Please enter your name");
errorDiv.innerHTML = "<li><font color='red'>Please enter your name</font></li>";
return false;
}



if(comment== null || comment=="")
{
//alert("Please enter the message");
errorDiv.innerHTML = "<li><font color='red'>Please enter the comment</font></li>";
return false;
}

}
</script>

<table class="tablep" cellspacing='0' cellpadding='0' border='0'>
<tr>
<td width='150'>Author:</td>
<td><a href='http://gokin.pl/' target='new'><?php echo"$noticia[AUOTHER]"; ?></a></td>

<td rowspan='5'>

&nbsp;


<img src='<?php echo $pathlocation;?>Template/Images/Buttons/download.png'
onClick="javascript:parent.top.location.href='<?php echo $pathlocation;?>

styles/download2.php?file=<?php echo $file;?>&typename=<?php echo $TYPE_NAME;?>'" class='imglink' >
<br />
<br />
&nbsp;
<img src='<?php echo $pathlocation;?>Template/Images/Buttons/Demo.png'

onClick="javascript:parent.top.location.href='<?php echo $pathlocation;?>

demos/<?php echo $TYPE_NAME;?>/<?php echo $STYLE_NAME;?>'" class='imglink' >

<br />
</td>
</tr>
<tr>
<td width='150'>Style version:</td>
<td><?php echo"$noticia[STYLE_VR]"; ?></td>

</tr>
<tr>
<td width='150'>Type name:</td>
<td><?php echo"$TYPE_NAME.".$noticia['TYPE_VR']; ?></td>
</tr>
<tr>
<td width='150'>Style Category:</td>
<td><?php echo $noticia['CATEGORY']; ?></td>
</tr>
<tr>
<td width='150'>Viewed:</td>

<td><?php echo"$noticia[VIEWS]"; ?></td>
</tr>
<tr>
<td width='150'>Downloads:</td>
<td><?php echo"$noticia[DOWNLOADS]"; ?></td>
</tr>
<tr>
<form name="ratingForm" id="ratingForm" action="#" method="post" >
<input type="hidden" name="rateValue" id="rateValue" value="" />
<input type="hidden" name="styleId" id="styleId" value="<?php echo $styleID;?>" />
</form>
<td width='150' >Rating:</td>
<td width='0' colspan='2'>
<?php
if(!isset($_POST['rateValue'])){
$rateflag=false;
?>
<ul class="star-rating" onmouseout="out()">
<li class="current-rating" style="width:<?echo $rating;?>%;" >Currently 3/5 Stars.</li>
<li><a href="#" title="poor" class="one-star" onclick="doVoteNow(1);" onMouseOver="over('poor')">1</a></li>
<li><a href="#" title="fair" class="two-stars" onClick="doVoteNow(2);" onMouseOver="over('fair')">2</a></li>
<li><a href="#" title="average" class="three-stars" onClick="doVoteNow(3);" onMouseOver="over('average')">3</a></li>
<li><a href="#" title="good" class="four-stars" onClick="doVoteNow(4);" onMouseOver="over('good')">4</a></li>
<li><a href="#" title="awesome" class="five-stars" onClick="doVoteNow(5);" onMouseOver="over('awesome!')">5</a></li>
</ul>
<?php }else{
if(isset($rateflag))
if(!$rateflag){
addRateValue($styleID,$_POST['rateValue']);
}

$rating=getrateValue($_POST['rateValue']);
?>
<ul class="star-rating" onmouseout="out()">

<li class="current-rating" style="width:<?php echo $rating;?>%;"

onMouseOver="over('you have already rated')" >Currently 3/5 Stars.</li>

</ul>
<?php }?>
<div style="color:#666666" style="font-family:'Times New Roman', Times, serif" id="rate"></div><br />
</td>
<tr><td>

<?php
include 'Controllers/showcommentcontrol.php';
echo $comments;
?>
</td></tr>
<tr><td>
<p>
<div id ='errorDiv'></div>
<form name='commentform' action="<?= $pathlocation?>styles/comment.php" method="post" onSubmit="return validateComment();">

Name: <input type="text" name="username" id="username" maxlength="40" alt="enter your name" /> <br />
Comment: &nbsp;<br/><textarea rows="6" cols="45" name="comment" id="comment"></textarea><br/>
<input type="hidden" name="download" value="styles/download2.php?file=<?=$file?>&typename=<?=$TYPE_NAME?>" />
<input type="hidden" name="styleId" value="<?=$styleID?>" />
<br />
<input type="submit" class="ygbtem" value="" title="" border="0" />
<br />

</td> </p>
</tr><tr><td colspan="2">

</form>

</td>
</tr>
</table></div>



<div class="content">
<h2>More information</h2>
<table class="tablep" cellspacing='0' cellpadding='0' border='0'>
<tr>
<td width='150'>Submitted:</td>
<td><?php echo"$noticia[SUBMIT_DATE]"; ?></td>
</tr>

<tr>
<td width='150'>Last updated:</td>
<td><?php echo"$noticia[UPDATE_DATE]"; ?></td>
</tr>
</table>
</div>


The code above contains lot of lines related to printing information about the current style which is not related to our topic which is voting, but the most related part is :
php code
<tr>
<form name="ratingForm" id="ratingForm" action="#" method="post" >
<input type="hidden" name="rateValue" id="rateValue" value="" />
<input type="hidden" name="styleId" id="styleId" value="<?php echo $styleID;?>" />
</form>
<td width='150' >Rating:</td>
<td width='0' colspan='2'>
<?php
if(!isset($_POST['rateValue'])){
$rateflag=false;
?>
<ul class="star-rating" onmouseout="out()">
<li class="current-rating" style="width:<?echo $rating;?>%;" >Currently 3/5 Stars.</li>
<li><a href="#" title="poor" class="one-star" onclick="doVoteNow(1);" onMouseOver="over('poor')">1</a></li>
<li><a href="#" title="fair" class="two-stars" onClick="doVoteNow(2);" onMouseOver="over('fair')">2</a></li>
<li><a href="#" title="average" class="three-stars" onClick="doVoteNow(3);" onMouseOver="over('average')">3</a></li>
<li><a href="#" title="good" class="four-stars" onClick="doVoteNow(4);" onMouseOver="over('good')">4</a></li>
<li><a href="#" title="awesome" class="five-stars" onClick="doVoteNow(5);" onMouseOver="over('awesome!')">5</a></li>
</ul>
<?php }else{
if(isset($rateflag))
if(!$rateflag){
addRateValue($styleID,$_POST['rateValue']);
}

$rating=getrateValue($_POST['rateValue']);
?>
<ul class="star-rating" onmouseout="out()">
<li class="current-rating" style="width:<?php echo $rating;?>%;"

onMouseOver="over('you have already rated')" >Currently 3/5 Stars.</li>

</ul>
<?php }?>
<div style="color:#666666" style="font-family:'Times New Roman', Times, serif" id="rate"></div><br />
</td>
<tr>

Where you can see that JavaScript functions are used to apply the voting actions. We define five links (Because we use scale of five steps- five stars) , when you move your mouse over a link, CSS event is triggered to change link look to a dark yellow star(Another Image - you can download the CSS files used at the end of this article), another important action to explain is calling onMouseOver="over('awesome!')" which calls :

javascript code
function over(val){

if(rating<1||rating>5)
document.getElementById("rate").innerHTML=val;
else
document.getElementById("rate").innerHTML="you have already rated."+rating;

}

This script shows a message below the mouse pointer with the current voting rank. Another action is when the user press on a voting option (Stars Images) the function doVoteNow(#) is called to submit the current form where in the same time the value determined for voting in hard-coded per each choice doVoteNow(1),doVoteNow(2)..doVoteNow(5) , but note the action attribute of form(ratingForm) element is equals "#", which means that you recall the same page once submit is proceed but this time with a $rateflag equals to false, $rateflag value is changed inside the doVoteNow(val) function. In such case the voting insertion to database is called at this section
php code
<?php }else{
if(isset($rateflag))
if(!$rateflag){
addRateValue($styleID,$_POST['rateValue']);
}

$rating=getrateValue($_POST['rateValue']);
?>

Here we just insert the styleID(IN your case AnthingID), with the voting value to a database record, Here this the MYSQL database table definition :

sql code
CREATE TABLE IF NOT EXISTS `vote` (
`STYLE_ID` int(11) NOT NULL DEFAULT '0',
`VOTE_VALUE` float DEFAULT '0',
KEY `FK_VOTE_RELATION` (`STYLE_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `vote`
--

INSERT INTO `vote` (`STYLE_ID`, `VOTE_VALUE`) VALUES
(6, 3);

Now, you may be wondering about the code snippet of PHP where we get the current total votes or insert new vote to database which was mentioned in the lines :
php code
include 'Controllers/ratingcontroller.php'; 
$rating = rateValue($styleID,$rating2);


Ratingcontroller.php , which is :
php code
<?php

include('Model/rating.php');

function getRatingImg($id,&$rating){

$folderpath="styles/";

$rater_rating = getRating($id);

if ($rater_rating <= 0 ){$rating=0;return $folderpath."img/00star.gif";}
if ($rater_rating <= 0.5){$rating=0.5;return $folderpath."img/05star.gif";}
if ($rater_rating <= 1 ){$rating=1;return $folderpath."img/1star.gif";}
if ($rater_rating <= 1.5){$rating=1.5;return $folderpath."img/15star.gif";}
if ($rater_rating <= 2 ){$rating=2;return $folderpath."img/2star.gif";}
if ($rater_rating <= 2.5){$rating=2.5;return $folderpath."img/25star.gif";}
if ($rater_rating <= 3 ){$rating=3;return $folderpath."img/3star.gif";}
if ($rater_rating <= 3.5){$rating=3.5;return $folderpath."img/35star.gif";}
if ($rater_rating <= 4 ){$rating=4;return $folderpath."img/4star.gif";}
if ($rater_rating <= 4.5){$rating=4.5;return $folderpath."img/45star.gif";}
if ($rater_rating <= 5 ){$rating=5;return $folderpath."img/5star.gif";}

}
function rateValue($id,$rating){

$rating = getRating($id);
if ($rating <= 0 ){return 0;}
if ($rating <= 0.5 ){return 10;}
if ($rating <= 1 ){return 20;}
if ($rating <= 1.5 ){return 30;}
if ($rating <= 2 ){return 40;}
if ($rating <= 2.5 ){return 50;}
if ($rating <= 3 ){return 60;}
if ($rating <= 3.5 ){return 70;}
if ($rating <= 4 ){return 80;}
if ($rating <= 4.5 ){return 90;}
if ($rating <= 5 ){return 100;}
}
function getrateValue($rating){

if ($rating <= 0 ){return 0;}
if ($rating <= 0.5 ){return 10;}
if ($rating <= 1 ){return 20;}
if ($rating <= 1.5 ){return 30;}
if ($rating <= 2 ){return 40;}
if ($rating <= 2.5 ){return 50;}
if ($rating <= 3 ){return 60;}
if ($rating <= 3.5 ){return 70;}
if ($rating <= 4 ){return 80;}
if ($rating <= 4.5 ){return 90;}
if ($rating <= 5 ){return 100;}
}
function addRateValue($id,$rating){

setRating($id,$rating);
}
?>

The group of if conditions at the start of the code above must be explained , actually getRatingImg function is not used in this example, you can just remove it, but it is used on other page to represents the current voting for each style but using other images of stars(Other partitions of scale-these images can be found in the archive attached.). The functions rateValue and getrateValue are used in this example at :
php code
include 'Controllers/ratingcontroller.php'; 
$rating = rateValue($styleID,$rating2);

and
php code
addRateValue($styleID,$_POST['rateValue']);
}
$rating=getrateValue($_POST['rateValue']);
?>

The two functions do the same job but with one difference which is the rateValue functions searches in database for voting value while getrateValue not. I suggest that you remove the repeated code and makes rateValue calls getrateValue and remove the conditions of rateValue. The job of $rating variable here is to controls the width of current voting or in other words to represents the amount of stars for current voting value (Average of all votes) . By this way you present the true voting results at :
html code
<li class="current-rating" style="width:<?echo $rating;?>%;" >Currently 3/5 Stars.</li>


current-rating is a CSS class which loads a star.gif image and repeats it on X- axis :
css code
.star-rating .current-rating{
background: url(star.gif) left -1000px repeat-x;
}

So when you control its width at style="width:<?echo $rating;?>%;" you control the current voting stars appearing to the website viewer.
Vote2.gif
.current-rating effect
Vote2.gif (1.64 KiB) Viewed 46624 times


RatingController.php also includes include('Model/rating.php') :

php code
<?php
function getRating($id){

$query2=" SELECT AVG( VOTE_VALUE ) AS avg FROM vote where STYLE_ID=".$id;
$result2=mysql_query($query2);
echo mysql_error();
$rater_rating=mysql_fetch_array($result2);

return $rater_rating['avg'];
}

function setRating($styleID,$rating){

$query2=" INSERT INTO `vote` ( `STYLE_ID` , `VOTE_VALUE` )VALUES ('$styleID', '$rating') ";
$result2=mysql_query($query2);
echo mysql_error();
}

?>


You can notice clearly in the code above that we calculate the average of all the records voting for a specific style (or Anything) and this function is called once the view style page is loaded to the view the current voting for the style( or Anything) . The last thing to say that you have to use some CSS files which is start_rating.css at your header :
css code
.star-rating,
.star-rating a:hover,
.star-rating a:active,
.star-rating a:focus,
.star-rating .current-rating{
background: url(star.gif) left -1000px repeat-x;
}
.star-rating{
position:relative;
width:125px;
height:25px;
overflow:hidden;
list-style:none;
margin:0;
padding:0;
background-position: left top;
}
.star-rating li{
display: inline;
}
.star-rating a,
.star-rating .current-rating{
position:absolute;
top:0;
left:0;
text-indent:-1000em;
height:25px;
line-height:25px;
outline:none;
overflow:hidden;
border: none;
}
.star-rating a:hover,
.star-rating a:active,
.star-rating a:focus{
background-position: left bottom;
}
.star-rating a.one-star{
width:20%;
z-index:6;
}
.star-rating a.two-stars{
width:40%;
z-index:5;
}
.star-rating a.three-stars{
width:60%;
z-index:4;
}
.star-rating a.four-stars{
width:80%;
z-index:3;
}
.star-rating a.five-stars{
width:100%;
z-index:2;
}
.star-rating .current-rating{
z-index:1;
background-position: left center;
}

/* for an inline rater */
.inline-rating{
display:-moz-inline-block;
display:-moz-inline-box;
display:inline-block;
vertical-align: middle;
}

/* smaller star */
.small-star{
width:50px;
height:10px;
}
.small-star,
.small-star a:hover,
.small-star a:active,
.small-star a:focus,
.small-star .current-rating{
background-image: url(star_small.gif);
line-height: 10px;
height: 10px;
}

You may have a question when you run this project, how to image of the Stars changes when i move the mouse pointer on it , the answer is in this part where we change the background image position of the voting links :
css code
.star-rating a:hover,
.star-rating a:active,
.star-rating a:focus{
background-position: left bottom;
}


All the needed images and CSS files are attached to this article.


Attachments
VotingNeededFiles.zip
Voting Needed Files
(21.92 KiB) Downloaded 705 times

Post a reply
  Related Posts  to : Add voting by stars images to your website content
 Web content & Website Design     -  
 Triangle of stars (C++)     -  
 Sequence of Images , draw several images in a row     -  
 Drawing rectangle using stars in java     -  
 show the content of set     -  
 Hide the content of the div     -  
 Displaying Images using servlets     -  
 aligning the scanned images     -  
 Displaying Images in a Gallery     -  
 lowercase table content     -