Specifications

// get current results of poll, regardless of whether they voted
$query = “select * from poll_results”;
if(!($result = @mysql_query($query, $db_conn)))
{
echo “Could not connect to db<br>”;
exit;
}
$num_candidates = mysql_num_rows($result);
// calculate total number of votes so far
$total_votes=0;
while ($row = mysql_fetch_object ($result))
{
$total_votes += $row->num_votes;
}
mysql_data_seek($result, 0); // reset result pointer
Part 1, shown in Listing 19.5.1, connects to the MySQL database, updates the votes according
to what the user typed, and gets the new votes. After we have that information, we can begin
making calculations in order to draw the graph. Part 2 is shown in Listing 19.5.2.
LISTING 19.5.2 showpoll.phpPart 2 Sets Up All the Variables for Drawing
/*******************************************
Initial calculations for graph
*******************************************/
// set up constants
$width=500; // width of image in pixels - this will fit in 640x480
$left_margin = 50; // space to leave on left of image
$right_margin= 50; // ditto right
$bar_height = 40;
$bar_spacing = $bar_height/2;
$font = “arial.ttf”;
$title_size= 16; // point
$main_size= 12; // point
$small_size= 12; // point
$text_indent = 10; // position for text labels on left
// set up initial point to draw from
$x = $left_margin + 60; // place to draw baseline of the graph
$y = 50; // ditto
$bar_unit = ($width-($x+$right_margin)) / 100; // one “point” on the graph
// calculate height of graph - bars plus gaps plus some margin
$height = $num_candidates * ($bar_height + $bar_spacing) + 50;
Generating Images
C
HAPTER 19
19
G
ENERATING
IMAGES
423
LISTING 19.5.1 Continued
24 7842 CH19 3/6/01 3:42 PM Page 423