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

Tuesday, June 9, 2009

Tidying up the code

I have decided to tidy up the code a little. I have moved the database details in to a file that gets included, and moved the database opening and closing into functions. This bit was (slightly) interesting (in fact almost too interesting to be included in this otherwise boring blog). The database open function has to return a value that points to the open database, and then we have to pass that value to the database close function. There - that was exciting wasn't it!



<?php

function openMyDB()
{
include("DBInfo.inc");
$con = mysql_connect($mydbhost,$mydbuser,$mydbpassword);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cddb", $con);
return $con;
}

function closeMyDB($con)
{
mysql_close($con);
}

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
#

$mycon=openMyDB();
writehead();
if ( empty($_POST['artid']) )
{
writeMenu();
}
else
{
writeDetails($_POST['artid']);
}

writetail();
closeMyDB($mycon);
?>


And the incude file looks like this:

<?php
$mydbhost="localhost";
$mydbuser="timj";
$mydbpassword="xxxxxx";
?>


That's enough excitement for one day!

No comments: