TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Poll Vote Percentages (http://www.talkphp.com/general/1539-poll-vote-percentages.html)

 CMellor 11-28-2007 07:29 PM

Poll Vote Percentages

Hey all,

I think I got my poll to how I want it to work, though usually in my case, I get some form of an error, but I'll cross that bridge when I get to it. Any who... I basically want to calculate the percentage of the votes in my poll, so if their was one vote for 'yes' and one for 'no' then each would be 50%... you get the idea, I hope.

I'm no good with math in PHP, hell... math in general. Below is a structure of my poll tables, just to give you an idea of how things are laid out, so hope it helps.

poll
• poll_id
• question
• creator_id
• who_voted
poll_options
• poll_options_id
• from_poll_id
• choice
poll_vote
• vote_id
• option_id
• voter_id
Hope someone is kind enough to help me out :)

 Wildhoney 11-28-2007 07:41 PM

You need to `COUNT(*)` all the choices that pertain to the poll_id you're after. Say you've got a total of 9 votes, take the 9 and store it. Then get all the options you have, `COUNT` them individually whilst using `GROUP BY` on the option they can select.

So if you have 5 yes, and 4 no, making a total of 9. You would do it like this (in pseudo form):

Code:

```GET YES = 5 GET NO = 4 GET TOTAL = 9 GET PERCENT YES = 5 * 100 / 9 GET PERCENT NO = 4 * 100 / 9```
Like you, I'm no good at maths. I have to nip out now but there's the theory. I hope someone helps you out properly, or at least I will when I return!

 CMellor 11-28-2007 08:21 PM

Hey,

Thanks for the response, I'll definitely try that, though I'll admit I've never really had to use GROUP BY, so I'm not 100% on that one.

If you helped later on, that'd be great! :D

 trmbne2000 11-30-2007 04:36 PM

Poll sample

Hi, this is my first post... A way back I did a simple poll for a web site, here is a snippet from the code that displayed everything: (its an excrept from a class, but everything you need should be there)
PHP Code:

``` \$pid = \$this->pollID;         \$maxWidth = 120;         \$sql = "SELECT COUNT(ID) FROM poll_responses WHERE Poll_id = \$pid";         \$rData = mssql_query(\$sql);         \$rRow = mssql_fetch_array(\$rData);         \$vCount = \$rRow[0];         \$sql = "SELECT * FROM poll_answers WHERE Poll_id = \$pid ORDER BY sOrd ASC";         \$rData = mssql_query(\$sql);         \$x = 1;         \$t = 0; //total counted         \$n = mssql_num_rows(\$rData); //number of questions         if (\$vCount != 0) {         while(\$rRow = mssql_fetch_assoc(\$rData)) {             \$rid = \$rRow["ID"];             \$txt = \$rRow["Text"];             \$sql = "SELECT COUNT(ID) FROM poll_responses WHERE Poll_id = \$pid AND Ans_id = \$rid";             \$dData = mssql_query(\$sql);             \$dRow = mssql_fetch_array(\$dData);             \$newcount = \$dRow[0];             \$avg = round((\$newcount / \$vCount),3);             if (\$x == \$n) {                 \$avg = 1 - \$t;             }             \$graphWidth = \$maxWidth * \$avg;             \$txtAvg = \$avg * 100 . "%";             print \$txt . ": (\$txtAvg)<br /><div id=\"graph\$x\" style=\"height:7px; width:{\$maxWidth}px; align:left; background-color:#" . \$this->bbg . "; float: left; \"><img src=\"/includes/graph.php?color=" . \$this->bc . "\" height=\"7\" width=\"\$graphWidth\" align=\"middle\" alt=\"\$txtAvg\" /></div><br />\r\n";             \$x++;             \$t = \$t + \$avg;         } //while         } else { print("There are no votes yet"); }  ```
I've never been big on group by for SQL either, so I took the less efficient route of just doing nested DB calls. Poll can be viewed in action at http://ww2.boatusangler.com/. If you need clarification on something, just ask, I'll do my best.

 trmbne2000 11-30-2007 04:37 PM

It also uses MSSQL, so its slightly different from mysql.

 CMellor 11-30-2007 09:53 PM

Hey trmbne2000, thanks for the response, it's helped a bit.

Could I show you my function I've wrote? Perhaps someone may want to work off that? I'm not asking "Hey, do this for me" because that's the last thing I care for, as how else am I to learn, but, in this case, I've had an hectic two weeks in trying to find a job, and I always seem to have plans, so... if anyone could use my code and let me know what I could do to get the results I want, I'd appreciate it a lot!

PHP Code:

``` //--------------------// Poll//--------------------function poll() {    // Query    \$queryPoll = mysql_query(sprintf("        SELECT poll_id, question, who_voted FROM poll        WHERE creator_id = '%d'",            getIdByUsername(\$_GET['uid'])    )) or die(mysql_error());        // Display content    if(\$q = mysql_fetch_array(\$queryPoll)) {        \$output = '        <form action="" method="post">        <div class="sub-header">'.\$q['question'].'</div>          <div class="content-box">        ';        // Query for the options        \$queryOptions = mysql_query(sprintf("            SELECT poll_options_id, choice FROM poll_options            WHERE from_poll_id = '%d'",                \$q['poll_id']        )) or die(mysql_error());                \$voted = unserialize(\$q['who_voted']);        // Loop over options        while(\$o = mysql_fetch_array(\$queryOptions)) {            if(@in_array(\$_COOKIE['userID'], \$voted)) {                \$queryVotes = mysql_query(sprintf("                    SELECT COUNT(vote_id) AS total FROM poll_vote                    WHERE option_id = '%d'",                        \$o['poll_options_id']                )) or die(mysql_error());                // Fetch                \$v = mysql_fetch_array(\$queryVotes);                                \$output .= '                <div class="poll-option">                  '.\$o['choice']. ' - ' .\$v['total'].' - ' . round(100 * \$v['total'] / 3, 2) .'                </div>                ';            }            else {                \$output .= '                <div class="poll-option">                  <input name="poll_choice" type="radio" value="'.\$o['poll_options_id'].'" />&nbsp;'.\$o['choice'].'                </div>                ';            }        }                \$output .= '        </div>        <div align="center">        ';                if(!@in_array(\$_COOKIE['userID'], \$voted)) {            \$output .= '            <input type="submit" value="Vote!" />            ';        }                \$output .= '        </div>        </form>        ';    }        echo \$output;}  ```
Thanks, really!

Off topic: I got the PM about the "award" not sure if I was given this personally by Wildhoney, or if you get it after the post count reaches the limit... either way, thanks!

 Wildhoney 11-30-2007 09:57 PM

Remaining off-topic for the moment. All of them are personally handed out :-)

 trmbne2000 12-03-2007 05:23 AM

Ok, the one thing I see is this line:
PHP Code:

``` '.\$o['choice']. ' - ' .\$v['total'].' - ' . round(100 * \$v['total'] / 3, 2) .'  ```
I may not be following your logic right, but it looks like you are dividing the number of votes for a particular option (\$v['total']) by 3. I think what you want to do is divide the number of people who voted for a particular option by the total number of votes in that poll.

 All times are GMT. The time now is 01:00 PM.