Development: creating the simplest poll

Starting with the SQL, we can create the table containing poll questions simply by fleshing out the schema already shown. As per usual we will need an ID primary key so that we can work with rows easily, but we should also set the default value of the vote counters to 0.

That is quite a long script, but much of it should be fairly straightforward. The switch/case statement block is there to turn the vote numbers into the name of the relevant field in the table. This could have been done by setting the field name as the answer number in poll.php, but that would basically have allowed malicious users to pass any variable into our script for change in the table - not a smart move. The code above validates that a choice of either 1, 2, or 3 has been passed in, as anything else will make the script exit.

Those scripts work fine - go ahead and test them out.

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!