Return to Snippet

Revision: 54836
at January 14, 2012 00:17 by RobertHegeraad


Initial Code
<?php
/*
 * Requires database(web-poll) with a table(poll) with two fields, votes(int) and language(varchar)
 */
class Vote
{
    public $question;
    public $answers = array();
    private $_db;

    public function __construct($question)
    {
        //Set the question
        $this->question = $question;

        //Connect to the database
        try
        {
            $this->_db = new PDO('mysql:host=localhost;dbname=web-poll', 'root', '');
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }
    
    //Insert the users vote and update the vote count
    public function insertVote($vote)
    {
        $stmt = $this->_db->prepare("UPDATE poll SET votes = votes + 1 WHERE language = ?");
        $stmt->execute(array($vote));
    }

    //Set the answers
    public function setAnswers($answer)
    {
        $this->answers[] = $answer;
    }
    
    //Display the vote field
    public function displayVote()
    {
        echo '<div class="poll">
                  <p>'.$this->question.'</p>
                  <form action="index.php" method="POST">
             ';

        foreach($this->answers as $answer)
        {
            echo '<p><input name="vote" type="radio" value="'.$answer.'" /> '.$answer.'</p>';
        }

        echo '    <input type="submit" value="Vote" />
                  <a href="index.php?results=show"><input type="button" value="Show results" /></a>
                  </form>
              </div>
             ';
    }
    
    private function totalVotes($answers)
    {
        //Select the votes from the database for every answer
        foreach($answers as $answer)
        {
            try
            {
                $stmt = $this->_db->prepare("SELECT votes FROM poll WHERE language = ?");
                $stmt->execute(array($answer));
                $getvotes[] = $stmt->fetch(PDO::FETCH_ASSOC);
            }
            catch(PDOException $e)
            {
                echo $e->getMessage();
            }
        }

        //Add the all the votes together
        for($i=0; $i < count($getvotes); $i++)
        {
            $totalvotes += $getvotes[$i][votes];
        }

        return $totalvotes;
    }

    //Display the vote results
    public function displayResults()
    {
        //Get the total amount of votes
        $totalvotes = $this->totalVotes($this->answers);

        //Get the results
        $stmt = $this->_db->prepare("SELECT * FROM poll");
        $stmt->execute();

        echo '<div class="poll">';

        while($results = $stmt->fetch())
        {
            //calculate the percentage   //replace 45 with total votes
            $percent = floor(100 / $totalvotes * $results['votes']);

            echo '<div class="section">
                      '.$results['language'].': '.$percent.'% with '.$results['votes'].' votes
                      <div class="bar" style="width:'.$percent.'%;"></div>
                  </div>
                 ';
        }

        echo '</div>';
    }
}

?>



<?php

//To set up and use the Vote Class

require_once('Vote.class.php');

//Create a new instance and set a question
$vote = new Vote('What is your favorite scripting language?');

//Set the answers
$vote->setAnswers('PHP');
$vote->setAnswers('JAVA');
$vote->setAnswers('PERL');
$vote->setAnswers('HTML');

//If a user has voted
if(isset($_POST['vote']))
{
    $vote->insertVote($_POST['vote']);
    $vote->displayResults();
}
//If the user has clicked the Show Results button
else if(isset($_GET['results']))
{
    $vote->displayResults();
}
else
{
    $vote->displayVote();
}

?>


The CSS i used.

.poll {
    width:200px;
    padding:10px;
    font-size:15px;
    background:#F9F9F9;
    outline:1px solid #DFDFDF;
    border:1px solid #ffffff;
}
.poll .section {
    margin-top:10px;
}
.poll .bar {
    height:10px;
    background:#FA4343;   /* Fallback IE, Opera */
    background:-moz-linear-gradient(top, #FA4343, #D91111);   /* Mozilla: */
    background:-webkit-gradient(linear, left top, left bottom, from(#FA4343), to(#D91111));   /* Chrome, Safari:*/
    border:1px #D91111 solid;
}

Initial URL


Initial Description
Very simple to use Web Poll Class, simply create a new instance, set the question and set the answers. You still have to set up your database yourself

Initial Title
Easy to implement and adjust Poll Class

Initial Tags
class

Initial Language
PHP