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.

Drawing Figures <strong>and</strong> Graphing Data<br />

503<br />

Listing 22.5.1<br />

Continued<br />

// calculate total number of votes so far<br />

$total_votes=0;<br />

while ($row = $result->fetch_object())<br />

{<br />

$total_votes += $row->num_votes;<br />

}<br />

$result->data_seek(0); // reset result pointer<br />

Part 1, shown in Listing 22.5.1, connects to the <strong>MySQL</strong> database, updates the votes<br />

according to the user’s selection, <strong>and</strong> gets the stored votes.After you have that information,<br />

you can begin making calculations to draw the graph. Part 2 is shown in Listing 22.5.2.<br />

Listing 22.5.2<br />

show_poll.php—Part 2 Sets Up All the Variables for Drawing<br />

/*******************************************<br />

Initial calculations for graph<br />

*******************************************/<br />

// set up constants<br />

putenv('GDFONTPATH=C:\WINDOWS\Fonts');<br />

$width=500; // width of image in pixels - this will fit in 640x480<br />

$left_margin = 50; // space to leave on left of graph<br />

$right_margin= 50; // ditto right<br />

$bar_height = 40;<br />

$bar_spacing = $bar_height/2;<br />

$font = 'arial';<br />

$title_size= 16; // point<br />

$main_size= 12; // point<br />

$small_size= 12; // point<br />

$text_indent = 10; // position for text labels from edge of image<br />

// set up initial point to draw from<br />

$x = $left_margin + 60; // place to draw baseline of the graph<br />

$y = 50; // ditto<br />

$bar_unit = ($width-($x+$right_margin)) / 100; // one "point" on the graph<br />

// calculate height of graph - bars plus gaps plus some margin<br />

$height = $num_c<strong>and</strong>idates * ($bar_height + $bar_spacing) + 50;<br />

Part 2 sets up some variables that you will use to actually draw the graph.<br />

Working out the values for these sorts of variables can be tedious, but a bit of forethought<br />

about how you want the finished image to look will make the drawing process<br />

much easier.We arrived at the values used here by sketching the desired effect on a piece<br />

of paper <strong>and</strong> estimating the required proportions.

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

Saved successfully!

Ooh no, something went wrong!