<?php

function sendGetPage () {
  
//too many ' and " in heredoc?
  
$serverNamePhpSelf = $_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
  
$ccode = $_POST['ccode'];

echo <<< endOfGetPage
<html>
<head>
<title>PHP MySQL World database</title>
</head>
<body>
<form name="userForm"
action="http://$serverNamePhpSelf";
method="post">
CountryCode
<input type="text" name="ccode" length="3" maxlength="3" value="$ccode">
</form>

endOfGetPage;
}
########################################################

//initial page load.  display form
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  
bail("");   //no error
}

$ccode = $_POST['ccode'];

$dbcnx = @mysql_connect("localhost", "wills", "");
if (!
$dbcnx) {
  
bail( "<p>Unable to connect to the database server at this time.</p>");
}


$db = "world";
if (! @
mysql_select_db($db) ) {
  
bail("<p>Unable to access the ".$db." database.  " .
       
"Go back and try another.</p>");
}


sendGetPage();

if (
strlen($ccode) > 0) {
  
$select = "SELECT * FROM Country WHERE Code='$ccode'";
  
doQuery($select, "Country table entry");
  
$select = "SELECT * FROM CountryLanguage WHERE CountryCode='$ccode'";
  
doQuery($select, "CountryLanguage table entries");
  
$select = "SELECT * FROM City WHERE Countrycode='$ccode'";
  
doQuery($select, "City table entries");
}

echo
"</body>\n</html>";
exit();


function
bail ($message) {
  echo
$message;
  
sendGetPage();
  echo
"</body>\n</html>";
  exit();
}


function
doQuery( $select, $title) {
  
$result = mysql_query($select);
  if (!
$result) {
    
bail("<p>Error performing query: $select <br>" . mysql_error() . "</p>");
  }
  else if (
mysql_num_rows($result) > 0) {     
    echo(
"<table border=1>\n");
    echo
"<caption>$title</caption>\n";    
    echo(
"<tr>");
    for (
$i=0; $i<mysql_num_fields($result); $i++) {
      echo
"<th>".mysql_field_name($result,$i)."</th>";
    }
    echo(
"</tr>\n");

    while (
$row = mysql_fetch_row($result)) {
      
$fields = count($row);
      
      echo(
"<tr>");
      for (
$i=0; $i<$fields; $i++)
    echo
"<td>".$row[$i]."</td>";
      echo(
"</tr>\n");
    }
    echo
"</table>\n";
  }
  else
    echo
"<p>No $title\n";
}


?>