Here is a very simple poll to ask people what their favorite imaginary character is among a list of four characters: Neo, the Tin Man, the White Rabbit, and the Scarecrow.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Best Imaginary Character</title>
<style>
body {
margin: 10em;
padding: 2em;
border: solid .2em green;
}
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>Imaginary Fight to the Finish</h1>
<form method="post" action="poll.php">
<p>
Please choose your favorite imaginary imaginary character:
<select name="character">
<option value="">Choose:</option>
<option value="rabbit">The White Rabbit</option>
<option value="scarecrow">The Scarecrow</option>
<option value="tinman">The Tin Man</option>
<option value="neo">Neo</option>
</select>
<input type="submit" value="Submit your answer" />
</p>
</form>
</body>
</html>
Save this as poll.php to your server, and try it out to make sure it works. It doesn’t currently do anything except display a pull-down menu and forget your choice as soon as you submit it.
- Save data to a file
- What we want to do is save the data to a simple file. Here’s a very simple vote counter class that only does that. Add it to fields.phpi:
- A Poll: Arrays
- A common thing to do on a poll after someone votes is show them the current results. We can do that, but to do it we need a list of all of the options available. In PHP, a list is called an array. For example, if you want to keep a list of colors, you might have an array that contains “red”, “blue”, “green”, “cyan”, “yellow”, and “magenta”. The simplest arrays are just lists of values.
- Visitor Sessions
- Our ability to answer the poll repeatedly has been very useful while testing, but makes it trivial for anyone to skew our poll by hitting “reload”. We need to track their visits, so that we know when and whether they’ve voted in the past. This is what cookies are for. You set a cookie on the client’s browser, and every time the browser visits you in the future, the browser returns the cookie. You can use that cookie to look up information about…
- Extra credit
- Extra credit in PHP: Hot Pages: A Poll