1. This website uses cookies. By continuing to use this website you are giving consent to cookies being used.
    For information on cookies and how you can disable them visit our Cookie Usage page.
    Dismiss Notice

PHP [PHP] Create a simple poll on your website

Discussion in 'Web Development' started by Gonzoide, Jul 30, 2014.

  1. Gonzoide

    Gonzoide New Member

    This small tutorial explains how you can easily create polls on your website :

    - manage polls : creation / deletion
    - expose polls to visitors : visitor can vote once, etc

    1 - Prerequisites

    - a MySQL / PHP website
    - as usual, it is assumed that $_SESSION['user_id'] contains the id of currently connected user
    - my tuto code will make use of "executeSQL" and "getData" fake methods to interact with MySQL. Generally speaking code is simplified to be educational :)
    - on the MySQL database, the following tables must exist :

    The POLL table will contain the "questions", and the poll status

    CREATE TABLE IF NOT EXISTS `poll` (
    `poll_id` int(4) NOT NULL AUTO_INCREMENT,
    `text` mediumtext,
    `votes` int(4) NOT NULL DEFAULT '0',
    `closed` char(1) NOT NULL DEFAULT 'N',
    PRIMARY KEY (`poll_id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;



    The POLL_ITEM table will contain the different answers per poll, and counters

    CREATE TABLE IF NOT EXISTS `poll_item` (
    `poll_id` int(4) DEFAULT NULL,
    `poll_item_id` int(4) DEFAULT NULL,
    `text` mediumtext,
    `votes` int(4) DEFAULT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;


    The POLL_USER table will stores the users who have voted for a poll, to prevent multiple votes

    CREATE TABLE IF NOT EXISTS `poll_user` (
    `poll_id` int(4) NOT NULL DEFAULT '0',
    `user_id` int(4) NOT NULL DEFAULT '0',
    `poll_item_id` int(4) NOT NULL DEFAULT '0',
    `date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;



    2 - Create the poll (PHP page accessible to admins only) :

    2-1 Handle creation and deletion. See usage of both POST and GET to make code simpler

    <?php

    // Request to delete a poll

    if (isset($_GET) && isset($_GET['delete'])) {
    $sql = "update poll set closed='Y' where poll_id=".$_GET['delete'];
    $req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
    }
    // Request to create a poll

    if (isset($_POST) && isset($_POST['create'])) {
    $text = $_POST['text'];

    $sql = "insert into poll (text, votes, closed) values ('".mysql_real_escape_string($text)."', 0, 'N')";
    $req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());

    $sql = "select max(poll_id) as poll_id from poll";
    $req = mysql_query($sql) or die('SQL Error !<br>'.$sql.'<br>'.mysql_error());
    $data = mysql_fetch_assoc($req);

    $poll_id = $data['poll_id'];

    for ($i = 1; $i <= 5; $i++) {
    if (isset($_POST['item'.$i]) && (strlen($_POST['item'.$i]) > 0)) {
    $sql = "insert into poll_item (poll_id, poll_item_id, text, votes) values (".$poll_id.", ".$i.", '".mysql_real_escape_string($_POST['item'.$i])."', 0)";
    $req = mysql_query($sql) or die('SQL Error!<br>'.$sql.'<br>'.mysql_error());
    }
    }
    }

    ?>


    2-2 Display form to create a new poll :

    <h1>Create a new poll</h1>
    <form action='polls.php' method='post'>
    <input type="hidden" name="create" value="Y" />
    <p><label for="text">Question</label> <input type="text" size="70" name="text" id="text"/></p>
    <p><label for="item1">Choice 1</label> <input type="text" size="70" name="item1" id="item1"/></p>
    <p><label for="item2">Choice 2</label> <input type="text" size="70" name="item2" id="item2"/></p>
    <p><label for="item3">Choice 3</label> <input type="text" size="70" name="item3" id="item3"/></p>
    <p><label for="item4">Choice 4</label> <input type="text" size="70" name="item4" id="item4"/></p>
    <p><label for="item5">Choice 5</label> <input type="text" size="70" name="item5" id="item5"/></p>
    <input type="submit" value="Sauver" />
    </form>


    2-3 Display all existing polls, with possibility to delete each

    <h1>Current live polls</h1>
    <?php
    $sql = "select * from poll where closed = 'N' order by poll_id";
    $req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());

    while ($data = mysql_fetch_assoc($req)) {
    echo "<h2>".$data["text"]." (".$data["votes"]." voters) <a href='polls.php?delete=".$data["poll_id"]."'>[Delete]</a></h2>\n";

    $sql2 = "select * from poll_item where poll_id=".$data["poll_id"]." order by poll_item_id";
    $req2 = mysql_query($sql2) or die('SQL Error !<br>'.$sql2.'<br>'.mysql_error());

    echo "<ul>\n";
    while ($data2 = mysql_fetch_assoc($req2)) {
    echo "<li>".stripslashes($data2["text"])."</li>\n";
    }
    echo "</ul>\n";

    }

    ?>


    3 - Present the poll to visitors (public PHP page) :

    3-1 - Handle vote requests


    <?php

    if (isset($_POST) && isset($_POST['poll_id']) && isset($_POST['poll_item_id'])) {
    // add one vote to the total

    executeSQL("update poll set votes=votes+1 where poll_id=".$_POST['poll_id']);

    // add one vote to the item

    executeSQL("update poll_item set votes=votes+1 where poll_id=".$_POST['poll_id']." and poll_item_id=".$_POST['poll_item_id']);

    // mark user has voted

    executeSQL("insert into poll_user (poll_id, user_id, poll_item_id, date) values (".$_POST['poll_id'].", ".$_SESSION['user_id'].", ".$_POST['poll_item_id'].", now())");
    }

    ?>



    3-2 Display poll(s).

    Code will inspect if user has already voted. If so, the results are presented, otherwise the user can vote

    <?php
    $rs = executeSQL("select * from poll where closed = 'N' order by poll_id");

    $first = 0;

    while ($data = getData($rs)) {

    echo "<h1>[Poll] ".stripslashes($data["text"])."</h1>\n";

    $rs2 = executeSQL("select * from poll_user where poll_id=".$data["poll_id"]." and user_id=".$_SESSION['user_id']);

    $voted = 0;

    if ($data2 = getData($rs2)) {
    $voted = 1;
    }

    $rs2 = executeSQL("select * from poll_item where poll_id=".$data["poll_id"]." order by poll_item_id");

    echo "<form action='index.php' method='post'>\n";
    echo "<input type='hidden' name='poll_id' value='".$data['poll_id']."' />\n";

    if ($voted == 1) {
    echo "<ul>\n";
    }

    while ($data2 = getData($rs2)) {
    if ($voted == 1) {
    echo "<li>".stripslashes($data2["text"])." : <b>".$data2["votes"]." vote(s)</b></li>\n";
    } else {
    echo "<input type='radio' name='poll_item_id' value='".$data2['poll_item_id']."'/>".stripslashes($data2["text"])."<br/>\n";
    }
    }

    if ($voted == 1) {
    echo "</ul>\n";
    }

    if ($voted == 0) {
    echo "<p><input type='submit' value='Vote' /></p>\n";
    }
    echo "</form>";
    }
    ?>
     
    kamini_123 and Dawn like this.
  2. Dawn

    Dawn Community Manager

    I'm stickying this because it looks like it would be really useful for everyone. Great job, Stéphane! (y)
     
  3. daviddakarai

    daviddakarai Member

    It would be really useful for everyone. Thank you, Stéphane!
     
  4. Hello Dear

    Polls are almost omnipresent on the web today, and there are a lot of administrations that will give a drop-in survey to you. In any case, imagine a scenario where you need to compose one yourself. This instructional exercise will find a way to make a basic PHP based survey, including database setup, vote preparing, and showing the survey.
    More information Click here