<?php

// Document header (doctype -> body tag)
function docheader() {

// If content header has not been sent,
//   send it
if (!headers_sent()) {
  header('Content-type: text/html');
}

print <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1.dtd">
<html>
<head>
  <title>MySQL Query Result</title>
</head>
<body>

HTML;

} // End docheader()


// Connect the DB with the given creds
function connectDB($server,$user,$password,$dbname) {

  $link = mysql_connect($server, $user, $password)
    or die("Could not connect to server!");
  mysql_select_db($dbname)
    or die("Could not select database!");

  return $link;

}  // End connectDB()


// Do the query, return the result
function doquery($link,$query) {

  $result = mysql_query($query,$link)
    or die("Could not perform query!")

  return $result;

} // End doquery()


// Output the results of the query in a table
function dotable($result) {

print <<<HTML
<table border="1" cellpadding="5">
<tr>

HTML;

  $line = mysql_fetch_array($result, MYSQL_ASSOC);
  $headers = array_keys($line);

  for ($i=0; $i <= count($headers) - 1; $i++) {
    print "  <th>".$headers[$i]."</th>\n";
  }

  print "</tr>\n";

  mysql_data_seek($result,0);
  while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    print "<tr>\n";
    foreach ($line as $key => $value) {
      print "  <td>".$value."</td>\n";
    }
    print "</tr>\n";
  }

  print "</table>\n";

} // End dotable()


// Document footer (close tags and end document)
function docfooter() {

print <<<HTML
</body>
</html>

HTML;

} // End docfooter()



// Main function
function main() {

  // Connect the DB
  $link = connectDB("localhost","webuser","password99","mysqlsamp");

// Set up and perform query
$query = <<<HTML
SELECT computers.comp_id as computer_id,
       mice.mouse_model as mouse_model,
       computers.comp_location as location
  FROM computers, mice
  WHERE mice.mouse_type = "USB"
  AND computers.comp_location like "A%"
  AND mice.mouse_comp = computers.comp_id

HTML;

  $result = doquery($link,$query);

  // Do document header
  docheader();

  // Do results in table
  dotable($result);

  // Do document footer
  docfooter();


}  // End main()


// Kick it all off
main();

?>