Just somewhere to keep my notes while I'm playing.

Friday, June 5, 2009

My first form in PHP

This form checks to see if it has been past a parameter. If not it displays a pull-down list of the artists on file. If it has been passed a value, it uses that value to pull out the CDs on file for an artist. That way the same piece of code is used twice.

I've tried to put things in functions to make it a little more tidy.


<?php
function writeHead()
{
echo "<html>\n<head>\n<title>CDs By Artists</title>\n</head>\n";
echo "<body>\n";
echo "<h1>CDs By Artists</h1>\n";
}

function writeTail()
{
echo "</body>\n</html>";
}


function writeMenu()
{
echo "<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">\n";
echo "<select name=\"artid\">\n";

$result = mysql_query("SELECT id, name FROM artist order by name");
while ($row = mysql_fetch_array($result)) {
echo "<option value=\"";
echo $row['id'] . "\">".$row['name'];
echo "</option>\n";
}
mysql_free_result($result);
echo "</select>\n";
echo "<input type=\"submit\" value=\"Submit\">";
echo "</form>\n";
}

function writeDetails($artid)
{
$result = mysql_query("SELECT name FROM artist where id = " . $artid . ";");
$row = mysql_fetch_array($result);
echo "<h3>" . $row['name'] . "</h3>\n";
mysql_free_result($result);
$result = mysql_query("SELECT title, yearpublished from cdtable where artid = " . $artid . ";");
echo "<table>\n<tr><th>Year Published</th><th>Title</th></tr>\n";
while ($row = mysql_fetch_array($result)) {
echo "<tr><td>" . $row['yearpublished'] . "</td>";
echo "<td>" . $row[title] . "</td></tr>\n";
}
mysql_free_result($result);
echo "</table>\n";
}


#
## Main Body
#
$con = mysql_connect("localhost","timj","xxxxxx");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cddb", $con);

writehead();
if ($_POST['artid']=="") writeMenu();
else writeDetails($_POST['artid']);

writetail();

mysql_close($con);
?>

No comments: