Hi,
Can anyone help me in writing a script for polls or voting.There are many scripts available,download them and use,but I wanted to write my own script.I have a question and 4 optins for that.I wanted to display the results in percentile and a color bar.Do I need to use DB?

Thank You.

Recommended Answers

All 24 Replies

You need to store the values in a table when someone votes. In that way, a user can vote only once. Displaying the result in % can be done by simple math calculation. I haven't worked with images, so, I am not very sure about graphs.

I have stored the values in a table.How can I calculate the %?how can I differntiate for each option?
In my DB table name is opt1 and fields Id, value.In values field am storing values which the user enters.

Since its a voting system, I guess you are having a radio button (or checkboxes). I also assume that you are saving pre-defined values in opt1 field. Count the number of votes for each option. Find the total and calculate the percentage.
votes for option A = 1
votes for option B = 4
votes for option C = 2
votes for option D = 3
Total votes = 10
Percentage of votes for A = 100/10 = 10%
Percentage of votes for B = 400/10 = 40%
... and so on..

Total no of votes can be counted.but storing all votes in the same table and count the no of votes seperately for each option how is that possible?

You know what are the available options for voting.. Right ? Can't you store them in the table ? Counting them wouldn't be difficult.

$query = "select count(*) from table where opt1 =  'A'";

This will give you the number of votes for A.

I know the available options for voting.They are:Option 1,Option 2,Option 3, Option 4.I am storing user selected values in table.
Here is my code:

<?php
include("conn.php");

$ans=$_POST['option'];
$str="INSERT INTO opt1 (ans) VALUES('".$ans."')";
echo $str;
$query = "select count(*) from opt1 where ans =  'Option 1'";
echo $query;
$res=mysql_query($query);
if(!$res){die(mysql_error());}

if(mysql_num_rows($res)!=0)
{

while($data=mysql_fetch_array($res,MYSQL_ASSOC))
 {
   echo '<tr>';
    
      echo ' <td > '.$data['ans'] .' </td > <br> ';
	 
      echo '</tr>';
	 }
  }
 else 
 echo 'Failure';
mysql_close($con);

?>

Am not getting any no.of votes of Option 1.

$query = "select count(*) as count from table where opt1 = 'Option 1'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row['count'];

Try this.

The above one is working for onli 1 option.How can I find for all the 4 options at a time?Do I need to write 4 different queris for 4 options?

No. Put the options in an array. Iterate. eg.

$options_array = array("option1","option2");
$votecount = array();
foreach($options_array as $value) {
  $query = "select count(*) as count where opt1 = '$value'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$votecount[$value] = $row['count'];
}
//by the end of this foreach loop, $votecount will have the the votes for each option. You can get the total by doing array_sum. Then again, iterate foreach $votecount value and find out the percentage.

Aieeee!
First, never execute mysql queries in a loop. This is very very bad. Any data you need from the database, unless from unrelated tables, can be pulled with one query.

I've found my self in the position where it would be the "easy" way out, but by increasing my sql knowledge, always found a better way.

Sending a query to the database is pretty expensive. If you do it in a loop your script won't scale and will break your server as soon as it sees a moderate amount of traffic.

You can do the totals in one query.
Try this (but change the field names to your db fields)

$query="Select option, count(option) as subtotal from survey
group by option;";
//do your mysql connect etc

This will produce a record set like:
option, subtotal
option1, 34
option2, 67
option3, 157
option4, 2000

What you do with this record set is academic... To get percentages, add up the subtotal column while looping through recordset, then divide each subtotal by the total. Read into the php math functions on how to get accurate floating point results.

This poll may have a small enough number of users that scalability isn't important, but sending queries in a loop is an extremely bad habit to get into.

-r

sending queries in a loop is an extremely bad habit

Why is it like that?I got the required output by the above method.

foreach($options_array as $value) { 
 $query = "select count(*) as count from opt1 where ans = '$value'";
 $result = mysql_query($query);
 $row = mysql_fetch_array($result);
 $votecount[$value] = $row['count'];
 echo $row['count'].'<br>';
 $perc=$row['count']*100;
 echo 'per is:'.$perc.'<br>';
   }
 $opsum=array_sum($votecount);
 echo 'Total:'.$opsum.'<br>';
 
      $percent=$perc/$opsum;
	  echo 'Percentage is:'. $percent.'<br>';

To get the percentage if I write outside the loop am gettig onli for the last option.If I write inside the loop then the % is calculated, but then there is problem with total.
To calculate percentage for each option what must I do?

foreach($options_array as $value) { 
 $query = "select count(*) as count from opt1 where ans = '$value'";
 $result = mysql_query($query);
 $row = mysql_fetch_array($result);
 $votecount[$value] = $row['count'];
 	echo $row['count'].'<br>';
 $perc=$row['count']*100;
 	echo 'per is:'.$perc.'<br>';
 $opsum=array_sum($votecount);
 	echo 'Total:'.$opsum.'<br>';
 $percent=$perc/$opsum;
 	echo 'Percentage is:'. $percent.'<br>';
}

The problem here is sum calculated is not for all the 4 options.what i need is calculate sum onli once and % seperately for 4 options.

Do array_sum($votecount) after foreach loop.

If I write array_sum($votecount) after foreach loop,I am getting the total but %
$perc=$row*100;
$percent=$perc/$opsum;
I need to write these both line inside the loop.If i write like that,then opsum is outside the loop.If I write those 2 lines outside the loop,then onli for option4 it is calculating.

No.. Store count for every option in an array. By the end of the foreach loop, you will have an array with count of votes for each answer. You can then get the sum of votes, iterate through the array to get each vote count to calculate the percentage.

How can I Store count for every option in an array?Is it something like this
$votecount[$value] = $row;
$perc=$row*100;
$opt=$topt[$perc];

Something like this.

foreach($options_array as $value) { 
 $query = "select count(*) as count from opt1 where ans = '$value'";
 $result = mysql_query($query);
 $row = mysql_fetch_array($result);
 $votecount[$value] = $row['count'];
}
$opsum=array_sum($votecount);
foreach($votecount as $key => $value) {	
	$perc=$value*100;
 	echo 'per of '.$key.' is:'.$perc.'<br>';
 	echo 'Total:'.$opsum.'<br>';
 	$percent=$perc/$opsum;
 	echo 'Percentage of '.$key .' is:'. $percent.'<br>';
}

ok....so I need to write for loop again.I thought I must write in the same loop.
Thank You :)
Now for images can i use switch case?

What images ? You can use it in the 2nd foreach loop itself !

Image which I mean is a bar which shows the % in some colors,usually seen in all poll results.

this script is from someone else which i have found useful and used it in one of my
Processing Votes
This code should be placed below the database connection, but above the rest of the script.

//We only run this code if the user has just clicked a voting link
if ( $mode=="vote")
{

//If the user has already voted on the particular thing, we do not allow them to vote again $cookie = "Mysite$id";
if(isset($_COOKIE[$cookie]))
{
Echo "Sorry You have already ranked that site <p>";
}

//Otherwise, we set a cooking telling us they have now voted
else
{
$month = 2592000 + time();
setcookie(Mysite.$id, Voted, $month);

//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
Echo "Your vote has been cast <p>";
}
}

The voting links we created in the previous step simply sent us back to the same page passing along the site ID we wanted to vote for and our rating for it.

In order to hinder people spamming the rankings, we place a cookie in their browser before we update the database. If we detect this cookie is already there, the script will not let the user vote again. Otherwise, the information is updated. If your site's users need to register to be able to rank, a better way to prevent multiple votes would be to store this information right in the database and not as a cookie.

1. The Database
2. Voting and Results
3. Processing Votes

<< Previous | Next


Voting and Results

<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("topbass_abouttest") or die(mysql_error());

//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM vote") or die(mysql_error());

//Now we loop through all the data
while($ratings = mysql_fetch_array( $data ))
{

//This outputs the sites name
Echo "Name: " .$ratings."<br>";

//This calculates the sites ranking and then outputs it - rounded to 1 decimal
$current = $ratings[total] / $ratings[votes];
Echo "Current Rating: " . round($current, 1) . "<br>";

//This creates 5 links to vote a 1, 2, 3, 4, or 5 rating for each particular item
Echo "Rank Me: ";
Echo "<a href=".$_SERVER."?mode=vote&voted=1&id=".$ratings[id].">Vote 1</a> | ";
Echo "<a href=".$_SERVER."?mode=vote&voted=2&id=".$ratings[id].">Vote 2</a> | ";
Echo "<a href=".$_SERVER."?mode=vote&voted=3&id=".$ratings[id].">Vote 3</a> | ";
Echo "<a href=".$_SERVER."?mode=vote&voted=4&id=".$ratings[id].">Vote 4</a> | ";
Echo "<a href=".$_SERVER."?mode=vote&voted=5&id=".$ratings[id].">Vote 5</a><p>";
}
?>

The code above connects to the database, and retrieves the information on all of the items we are rating. It then displays it, and gives the users the option to place their vote. You could easily apply some nice HTML formatting around this if you wanted, or replace the text vote links with images. The comments in the code tell you what each step is doing.

1. The Database
2. Voting and Results
3. Processing Votes

<< Previous | Next >>

Processing Votes
This code should be placed below the database connection, but above the rest of the script.

//We only run this code if the user has just clicked a voting link
if ( $mode=="vote")
{

//If the user has already voted on the particular thing, we do not allow them to vote again $cookie = "Mysite$id";
if(isset($_COOKIE[$cookie]))
{
Echo "Sorry You have already ranked that site <p>";
}

//Otherwise, we set a cooking telling us they have now voted
else
{
$month = 2592000 + time();
setcookie(Mysite.$id, Voted, $month);

//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
Echo "Your vote has been cast <p>";
}
}

The voting links we created in the previous step simply sent us back to the same page passing along the site ID we wanted to vote for and our rating for it.

This new code only runs if the person has clicked one of those links, otherwise it is ignored.

In order to hinder people spamming the rankings, we place a cookie in their browser before we update the database. If we detect this cookie is already there, the script will not let the user vote again. Otherwise, the information is updated. If your site's users need to register to be able to rank, a better way to prevent multiple votes would be to store this information right in the database and not as a cookie.

1. The Database
2. Voting and Results
3. Processing Votes

<< Previous | Next
------------------------------------------------
Now All you have to do is Just change it so instead of saving it into cookies, it saves it into the db..

I got the % in numbers.To calculate the % in color bars can I write like this:In a for loop can I use switch case?

foreach($votecount as $key => $value) {	$perc=$value*100; 
	$percent=$perc/$opsum; 
	echo 'Percentage of '.$key .' is:'. $percent.'<br>';
switch ($percent) {
case "0":if ($percent==0)
   		 echo "<img src="green_rating/0.gif" />";
   		 break;
case "1":if (($percent==1) && ($percent==10))
    	 echo "<img src="green_rating/1.gif" />";
   		 break;
case "2":if (($percent==11) && ($percent==20))
    	 echo "<img src="green_rating/2.gif" />";
   		 break;
case "3":if (($percent==21) && ($percent==30))
    	echo "<img src="green_rating/3.gif" />";
    	break;
                                      .                                  
                                      .	
                                      .

case "10":if (($percent==91) && ($percent==100))
    	 echo "<img src="green_rating/10.gif" />";
  		  break;	
}

	}

Umm.. Why do you need a switch case ? Why not do it directly ?

if($percent > 0 && $percent < 20) { //show red image
} elseif ($percent > 20 && $percent < 50) {
 //show orange image
} elseif ($percent > 50 && $percent < 100) {
//show green image
} 
//... and so on

Your condition will not work because, $percent can have only 1 value. It can't be 1 as well as 10.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.