guestbook_db.php 1.4 KB
<?php

	require_once (OEDL_DIR . 'libs/guestbookdbexception.php');

	define ('GUESTBOOK_DELIM', '>#/\#<');

	class GuestbookDb
	{
		var $dsn = NULL;  // dsn => data source name
		var $db  = NULL;	// handle to db

		public function __construct ($dsn) 
		{
			$this->dsn = $dsn;
		}

		public function open () 
		{
			$this->db = dba_open ($this->dsn, 'c', 'db4', 0600);
			if ($this->db == FALSE)
				throw (new GuestbookDbException (DB_OPEN_EXC));
		}

		public function close ()
		{
			dba_close ($this->db);
		}

		public function getEntries ()
		{
			$data = array ();

			$key = dba_firstkey ($this->db);

			while ($key)
			{
				$value = dba_fetch ($key, $this->db);

				if ($value == FALSE)
					throw (new GuestbookDbException (DB_GETVAL_EXC));

				$_row = explode (GUESTBOOK_DELIM, $value);
				$row['Name']     = $_row[0];
				$row['Comment']  = $_row[1];
				$row['EntryDate']= $_row[2];

				$data[] = $row;

				$key = dba_nextkey ($this->db);
			}

			rsort ($data);
			return $data;
		}

		public function addEntry ($name, $comment)
		{
			$time  = time ();
			$idx   = 0;
			$key   = implode (':', array ($time, $idx));
			$value = implode (GUESTBOOK_DELIM, array ($name, $comment, $time));

			while (dba_insert ($key, $value, $this->db) == FALSE)
			{
				$idx = $idx + 1;

				if ($idx > 9)
					throw (new GuestbookDbException (DB_INSERT_EXC));

				$key = implode (':', array ($time, $idx));
			}
		}
	}

?>