University of Virginia, Department of Computer Science
CS200: Computer Science, Spring 2004

Notes: Wednesday 31 March 2004
Schedule

HTML/PHP/SQL Example
View generated page: presidents.php3
<html>
<head><title>Presidents of the United States</title></head>
<body>
<h1>Presidents of the United States</h1>
<p>
<?
  // connection information 
  $hostName =  "dbm1.itc.virginia.edu"; 
  $userName =  "dee2b"; 
  $password =  "quist"; // Not my real password!
  $dbName =  "dee2b_presidents"; 
  
  // make connection to database 
  mysql_connect($hostName, $userName, $password) 
    or exit("Unable to connect to host $hostName"); 
  
  mysql_select_db($dbName) 
    or exit("Database $dbName does not exist on $hostName");  
  
  // Run a SQL Query 
  $result = mysql_query("SELECT lastname, firstname FROM presidents " .
			"WHERE college='William and Mary' ORDER BY lastname");
  
  // Determine the number of rows 
  $numrows = mysql_num_rows($result); 
  $numcols = mysql_num_fields($result); 
  
  // print the results 
  print "<table border=0 cellpadding=5><tr>";

  for ($k = 0; $k < $numcols; $k = $k + 1) 
    { 
      print "<th>" . mysql_field_name ($result, $k) . "</th>"; 
    } 
  print "</tr>";

  for ($i = 0; $i < $numrows; $i++)  // $i++ is short for $i = $i + 1
    { 
      for ($j = 0; $j < $numcols; $j++) { 
        print "<td>" . mysql_result ($result, $i, $j) . "</td>"; 
      } 
      print "</tr>"; 
    } 
  print "</table>"; 
  mysql_close();   // Close the database connection 
?> 
<p><hr>
<a href="mailto:evans@virginia.edu"><em>evans@virginia.edu</em></a>
</body>
</html>
cs200-staff@cs.virginia.edu
Using these Materials