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
<input type="radio" name="option" value="Second" /> Second
<input type="radio" name="option" value="Third" /> Third
<input type="radio" name="option" value="Fourth" /> Fourth
<input type="submit" />
</form>
<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>";
}
?>