query("SELECT name FROM sqlite_master WHERE type='table'", SQLITE_NUM); $result = $query->fetchAll(SQLITE_NUM); $tables = array(); foreach ($result as $entry) { $tables[]=$entry[0]; } if (!in_array("watches", $tables)){ $db->queryExec("CREATE TABLE watches (title TEXT, description TEXT, symbol TEXT, tag TEXT, PRIMARY KEY ( symbol )) "); } return $db; } function write() { global $HTTP_RAW_POST_DATA; $db=openDb(); $dom = new DOMDocument(); $dom->loadXML($HTTP_RAW_POST_DATA); if (!$dom->relaxNGValidate ( 'watch.rng')) { die("unvalid document"); } $xml = simplexml_import_dom($dom); foreach ($xml->children() as $element) { $element['escaped'] = sqlite_escape_string(trim($element)); } //echo $xml->asXML(); $query = $db->query( "SELECT symbol from watches where symbol='". $xml->symbol['escaped']. "'", SQLITE_NUM); $req = ""; if ($query->fetch()) { $req="update watches set "; $req .= "tag='".$xml->tag['escaped']."', "; $req .= "title='".$xml->title['escaped']."', "; $req .= "description='".$xml->description['escaped']."' "; $req .= "where symbol='".$xml->symbol['escaped']."'"; } else { $req="insert into watches (symbol, tag, title, description) values ("; $req .= "'".$xml->symbol['escaped']."', "; $req .= "'".$xml->tag['escaped']."', "; $req .= "'".$xml->title['escaped']."', "; $req .= "'".$xml->description['escaped']."')"; } //echo $req; $db->queryExec($req); echo ""; } function displayOne($row) { $xml = simplexml_load_string("<description/></watch>"); $xml->symbol=$row['symbol']; $xml->tag=$row['tag']; $xml->title=$row['title']; $xml->description=$row['description']; $asXML = $xml->asXML(); print substr($asXML, strpos($asXML, '<', 2)); } function readOne() { $db=openDb(); $query = $db->query( "SELECT * from watches where symbol='". sqlite_escape_string(trim($_GET['name']))."'" , SQLITE_ASSOC); if ($row = $query->fetch(SQLITE_ASSOC)) { displayOne($row); } else { $xml = simplexml_load_string("<watch/>"); $asXML = $xml->asXML(); print substr($asXML, strpos($asXML, '<', 2)); } } function listAll() { $db=openDb(); echo "<watches>"; $query = $db->query("SELECT * from watches order by symbol", SQLITE_ASSOC); while ($row = $query->fetch(SQLITE_ASSOC)) { displayOne($row); } echo "</watches>"; } header("Cache-Control: max-age=60"); header("Content-type: application/xml"); echo '<?xml version="1.0" encoding="utf-8"?>'; if (strlen($HTTP_RAW_POST_DATA)>0) { write(); } else if ($_GET['name']) { readOne(); } else { listAll(); } ?>