\n"); print ("\n"); if ($title) print ("$title\n"); print ("\n"); print ("\n"); if ($header) print ("

$header

\n"); } # put out final HTML tags for page. function html_end () { print ("\n"); } # print hidden field in form function hidden_field ($name, $value) { printf ("\n", $name, $value); } # pres_quiz.php - script to quiz user on presidential birthplaces # DISPLAY_FORM function display_form ($name, $place, $choice) { global $PHP_SELF; printf ("
\n", $PHP_SELF); hidden_field ("name", $name); hidden_field ("place", $place); hidden_field ("choice", implode ("#", $choice)); printf ("Where was %s born ?

\n", $name); $choicemax = 4; for ($i = 0; $i <= $choicemax; $i++) { print ("%s
\n", $choice[$i], $choice [$i]); } print ("
\n"); print ("
\n"); } # DISPLAY_FORM # SETUP_QUIZ function setup_quiz () { # issue query to pick a president and get birthplace $query = "SELECT CONCAT(first_name, ' ', last_name) AS name," . " CONCAT(city, ', ', state) AS place," . " YEAR(birth) * 0 + RAND() AS rand_col" . " FROM president ORDER BY rand_col LIMIT 1"; $result = mysql_query ($query) or die ("Cannot execute query"); $row = mysql_fetch_array ($result) or die ("Cannot fetch result"); $name = $row["name"]; $place = $row["place"]; # Construct the set of birthplace choices to present. # Set up the $choice array containing five birthplaces, one # of which is the correct response. $query = "SELECT DISTINCT CONCAT(city, ', ', state) AS place," . " YEAR(birth) * 0 + RAND() AS rand_col" . " FROM president ORDER BY rand_col"; $result = mysql_query ($query) or die ("Cannot execute query"); $choice[] = $place; # initialize array with correct choice $choicemax = 4; while (count ($choice) <= $choicemax && $row = mysql_fetch_array ($result)) { if ($row["place"] == $place) continue; $choice[] = $row["place"]; # add another choice } # randomize choices, then display form srand(time()); $randindex = rand(0,4); $temp = $choice[0]; $choice[0] = $choice[$randindex]; $choice[$randindex] = $temp; display_form ($name, $place, $choice); } # SETUP_QUIZ # CHECK_RESPONSE function check_response () { global $name, $place, $choice; global $response; if ($place == $response) { print("
\n"); print("This is correct !
\n"); printf("%s was born in %s.
\n", $name, $place); print("Try the next question :


\n"); setup_quiz(); } else { print("
\n"); print("That is not correct. "); print("Please try again.

\n"); $choice = explode ("#", $choice); display_form ($name, $place, $choice); } } # CHECK_RESPONSE # MAIN $title = "US President Database Quiz"; html_begin ($title, $title); print("
\n"); if (!samp_db_connect ()) print ("Sorry, could not connect to database server.
\n"); else { if (!$name) # called for first time setup_quiz (); else # user submitted response to form check_response (); } print("
\n"); print('Program Source
'); html_end (); # MAIN ?>