PHP database example

Click here to see it in action.
<?php
$db = "webprogramming";
$passwd = "csci4608f04";

//open a persistent connection to the database
$link = mysql_pconnect("localhost", $db, $passwd)
     or die("Could not connect : " . mysql_error());

mysql_select_db("$db") or die("Could not select database");
//table can equal any of our 3 tables (Country, Medals, Sports)

// EXPLORING THE DATABASE

// LISTING ALL TABLES:

$alltables = mysql_list_tables($db);

if (!$alltables) die("Error listing tables: " . mysql_error());

echo "List all tables:<BR>";
$i = 1;
while($thetable = mysql_fetch_row($alltables)) {
    echo "Table $i: ".$thetable[0]."<BR>\n";
    $i++;
}

// LISTING ALL FIELD NAMES IN A TABLE:

$table = "Country";

echo "<P>List all fields in table $table<BR>\n";

// query that table:
$query = "SHOW COLUMNS FROM $table";
$res = mysql_query($query);
if (!res) die("Error in the query " . mysql_error());

while ($row = mysql_fetch_assoc($res)) {
    print_r($row); // print the row in a readable way
    echo "<BR>\n";
}

//the * can be replaced by certain column names
//(ie "SELECT country_name, noc FROM $table"), but then only
// country_name and noc can be accessed

// DISPLAYING THE CONTENTS OF THE TABLE

echo "<P>The contents of the table $table<BR>\n";

$query = "SELECT * FROM $table";

$result = mysql_query($query);
if(! $result) die("Error in the query " . mysql_error());

while($row=mysql_fetch_assoc($result)){
  $country_name = $row["country_name"];
  $noc = $row["noc"];
  $flag = $row["flag"];
  echo $country_name." ".$graphic_name." ".$noc." ".$flag."<BR>\n";
}

// DISPLAYING AN IMAGE

$pictures = "http://epoxy2.morris.umn.edu/~webprogramming/graphics/";
$image = "RUS.gif";

echo "<IMG SRC=$pictures".$image.">";

mysql_close($link); // doesn't close a persistent connection

?>