13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

500 Chapter 22 Generating Images<br />

In this example, you run a poll on your website to test whom users will vote for in a<br />

fictitious election.You store the results of the poll in a <strong>MySQL</strong> database <strong>and</strong> draw a bar<br />

chart of the results using the image functions.<br />

Graphing is the other thing these functions are primarily used for.You can chart any<br />

data you want—sales, web hits, or whatever takes your fancy.<br />

For this example, we spent a few minutes setting up a <strong>MySQL</strong> database called poll.<br />

It contains one table called poll_results, which holds the c<strong>and</strong>idates’ names in the<br />

c<strong>and</strong>idate column <strong>and</strong> the number of votes they received in the num_votes column.<br />

We also created a user for this database called poll, with password poll.This table is<br />

straightforward to set up, <strong>and</strong> you can create it by running the SQL script shown in<br />

Listing 22.3.You can do this piping the script through a root login using<br />

mysql -u root -p < pollsetup.sql<br />

Of course, you could also use the login of any user with the appropriate <strong>MySQL</strong><br />

privileges.<br />

Listing 22.3<br />

pollsetup.sql—Sets Up the Poll Database<br />

create database poll;<br />

use poll;<br />

create table poll_results (<br />

c<strong>and</strong>idate varchar(30),<br />

num_votes int<br />

);<br />

insert into poll_results values<br />

(‘John Smith’, 0),<br />

(‘Mary Jones’, 0),<br />

(‘Fred Bloggs’, 0)<br />

;<br />

grant all privileges<br />

on poll.*<br />

to poll@localhost<br />

identified by ‘poll’;<br />

This database contains three c<strong>and</strong>idates.You provide a voting interface via a page called<br />

vote.html.The code for this page is shown in Listing 22.4.<br />

Listing 22.4 vote.html—Allows Users to Cast Their Votes Here<br />

<br />

<br />

Polling<br />

<br />

<br />

Pop Poll<br />

Who will you vote for in the election?<br />

<br />

John Smith

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!