hi everyone,
im trying to create a little form that would simply keep the count of people that have voted and the score of the votes .
here is my form in static html

<form name = "contestants" method="POST">
<font size = "3" face="Arial" color="#dddddd">
<input type="radio" name ="contestant" value ="MissFrank">MissFrank<br>
<input type="radio" name ="contestant" value ="KandyRain">KandyRain<br>
<input type="radio" name ="contestant" value ="Jhon and Edward">Jhon and Edward<br>
<input type="radio" name ="contestant" value="Lloyd Daniels">Lloyd Daniels<br>
<input type="radio" name ="contestant" value="Joseph McElderry">Joseph McElderry</br>
<input type="radio" name ="contestant" value="Rikki Loney">Rikki Loney<br>
<input type="radio" name="contestant" value="Lucie Jones">Lucie Jones<br>
<input type="radio" name="contestant" value="Stacey Solomon">Stacey Solomon<br>
<input type="radio" name="contestant" value="Rachel Adedeji">Rachel Adedeji<br>
<input type="radio" name="contestant" value="Danyl Jhonson">Danyl Jhonson<br>
<input type="radio" name="contestant" value="Olly Murs ">Olly Murs<br>
<input type="radio" name="contestant" value="Jamie Archer">Jamie Archer<br>
<input type="submit" value="vote">
</font>
</form>

i would be very happy if somebody would tell me how to get this working in php.
thanks

Recommended Answers

All 5 Replies

Hey.

Do you have some sort of a database? Like MySQL?

If not, you could use a CSV file to store the data.
For example, I wrote this a while back. Does pretty much what you were talking about:

data_functions.php

<?php
// Stores the name of the database file.
define('DB_FILE', 'db.csv');

/**
 * A function that retrieves the data from the data file and returns it
 * as an array.
 * @return array The list of options and their current count.
 */
function getVotes()
{
    // Set up an array for the data
    $data = array();

    // Open the file in "read" mode and read through it, counting matches.
    $fh = fopen(DB_FILE, "rb");
    if($fh)
    {
        // Loop through all the lines in the data file.
        while(($row = fgetcsv($fh, 1000, ",")) != FALSE)
        {
            // Add to the count for the option.
            if(!isset($data[$row[0]]))
            {
                $data[$row[0]] = 1;
            }
            else
            {
                $data[$row[0]] += 1;
            }
        }
    }
    fclose($fh);

    return $data;
}

/**
 * Function that adds a vote to the datafile.
 * @param <type> $option The name of the option to be added.
 * @param <type> $ip The IP addresss of the voter. Would be used to limit the amout of votes. (A dirty method)
 * @return void
 */
function addVote($option, $ip)
{
    // Make sure the option isn't empty.
    if(empty($option)) {
        return;
    }

    // If the IP is empty, default to N/A.
    if(empty($ip)) {
        $ip = "N/A";
    }

    // Open the file in "append" mode, so that we can add to the end of it.
    $fh = fopen(DB_FILE, "ab");
    if($fh)
    {
        // Add a line to the datafile.
        $line = array($option, $ip);
        if(!fputcsv($fh, $line, ","))
        {
            // If the add fails, show an error.
            user_error('Failed to add vote!', E_USER_WARNING);
        }
    }
    fclose($fh);
}
?>

index.php

<!DOCTYPE html>
<html>
    <head>
        <title>CSV Database Test</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
    </head>
    <body>
        <h2>Please vote!</h2>
        <form action="add_vote.php" method="post">
            <input type="radio" name="option" value="First" /> First<br />
            <input type="radio" name="option" value="Second" /> Second<br />
            <input type="radio" name="option" value="Third" /> Third<br />
            <input type="radio" name="option" value="Fourth" /> Fourth<br />
            <input type="submit" />
        </form>
        <br />

        <h2>Current Count</h2>
        <pre><?php
        // Include the data functions.
        include('data_functions.php');

        // Print a list of current votes
        $data = getVotes();
        if($data)
        {
            foreach($data as $_name => $_count)
            {
                echo " {$_name} = {$_count}\n";
            }
        }
        ?></pre>
    </body>
</html>

add_vote.php

<?php
// Check to see if there was an option
if(isset($_POST['option']))
{
    // Include the data functions.
    include('data_functions.php');

    // Add the vote, using the addVote function.
    addVote($_POST['option'], $_SERVER['REMOTE_ADDR']);

    // Print success message
    echo "<h3>Thank you for voting!</h3>";
    echo "<p><a href='index.php'>Go back.</a></p>";
}
else
{
    // Print an error message
    echo "<h3>There was no vote passed...</h3>";
    echo "<p><a href='index.php'>Go back.</a></p>";
}
?>

oh this is great it is just what i needed thanks thanks a lot for this it was troubling me for couple of days know.
i also want to ask would you know how to make that the user would be only aloud to vote once?

That's a bit tougher, because it's very hard to keep accurate track of your users, short of requiring that people register and log in before voting.

A popular method is to record the user's IP address and only allow one vote per IP address. I'm not a big fan of this method, because in many cases a single IP address covers a whole bunch of computers. (Think; a school campus or a proxy server.)
Note, that my previous code does record IP addresses, but that was more to allow you to deleting entries retroactively, rather than to block them proactively.

A simpler, yet somewhat less reliable way, is to use cookies to keep users from voting multiple times. This won't keep determined people from voting repeatedly (they can just disable or delete their cookies), but it will keep typical users at bay.

You would have to change the addVote function in the above code, as well as the index and add_vote PHP files, to show different messages.

data_functions.php
Just showing the altered addVote function.

/**
 * Function that adds a vote to the datafile.
 * @param <type> $option The name of the option to be added.
 * @param <type> $ip The IP addresss of the voter. Would be used to limit the amout of votes. (A dirty method)
 * @return bool
 */
function addVote($option, $ip)
{
    // Make sure the option isn't empty.
    if(empty($option)) {
        return;
    }

    // Check if the user has already voted and return if he has.
    if(isset($_COOKIE['has_voted'])) {
        return false;
    }

    // If the IP is empty, default to N/A.
    if(empty($ip)) {
        $ip = "N/A";
    }

    // Open the file in "append" mode, so that we can add to the end of it.
    $fh = fopen(DB_FILE, "ab");
    if($fh)
    {
        // Add a line to the datafile.
        $line = array($option, $ip);
        if(!fputcsv($fh, $line, ","))
        {
            // If the add fails, show an error.
            user_error('Failed to add vote!', E_USER_WARNING);
        }

        // Set a cookie so we know he has already voted next time he tries.
        $duration = time() + (60 * 60 * 24 * 30); // 30 days
        setcookie('has_voted', $option, $duration, "/");
    }
    else
    {
        // Show an error if you fail to open the file.
        user_error('Failed to open the datafile.', E_USER_ERROR);
        return false;
    }
    fclose($fh);

    return true;
}

index.php
Altered to show different messages for users that have already voted.

<!DOCTYPE html>
<html>
    <head>
        <title>CSV Database Test</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
    </head>
    <body>
<?php
// Check if the user has already voted.
if(!isset($_COOKIE['has_voted']))
{
    // He hasn't. Show the form
    echo <<<HTML
    <h2>Please vote!</h2>
    <form action="add_vote.php" method="post">
        <input type="radio" name="option" value="First" /> First<br />
        <input type="radio" name="option" value="Second" /> Second<br />
        <input type="radio" name="option" value="Third" /> Third<br />
        <input type="radio" name="option" value="Fourth" /> Fourth<br />
        <input type="submit" />
    </form>
    <br />
HTML;
}
else
{
    // User has already voted. Show a thank you message.
    echo "<h2>Thank you for your vote!</h2>";
}


// Include the data functions and get the current data.
include('data_functions.php');
$data = getVotes();

// Print a list of current votes
echo '<h2>Current Count</h2><pre>';
if($data)
{
    foreach($data as $_name => $_count)
    {
        echo " {$_name} = {$_count}\n";
    }
}
echo '</pre>';
?>
    </body>
</html>

add_vote.php
Altered to show an error message when users that have already voted try to vote.

<?php
// Check to see if there was an option
if(isset($_POST['option']))
{
    // Include the data functions.
    include('data_functions.php');

    // Add the vote, using the addVote function.
    if(addVote($_POST['option'], $_SERVER['REMOTE_ADDR']))
    {
        // Print success message
        echo "<h3>Thank you for voting!</h3>";
        echo "<p><a href='index.php'>Go back.</a></p>";
    }
    else
    {
        // Print "already voted" message.
        echo "<h3>You have already voted!</h3>";
        echo "<p>You can only vote once.<br /><a href='index.php'>Go back.</a></p>";
    }
}
else
{
    // Print an error message
    echo "<h3>There was no vote passed...</h3>";
    echo "<p><a href='index.php'>Go back.</a></p>";
}
?>

oh i am so glad for your help this just saved me hours of work and trying to work it out my self would of been disasters.
thanks a lot your help is greatly appreciated

Your welcome.
I'm glad I could help :)

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.