diff -r 52fb6408b86a -r 2d22262da8e0 php/class.Address_Book_DB.php --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/php/class.Address_Book_DB.php Thu Oct 27 16:56:26 2011 +0200 @@ -0,0 +1,99 @@ +dbh = new PDO($dsn, $user, $pass, + array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); + + $this->dbh->exec("CREATE TABLE IF NOT EXISTS data + (name TEXT, tel TEXT, mail TEXT)"); + + $this->dbh->beginTransaction(); + + $sth = $this->dbh->prepare("SELECT COUNT(*) AS COUNT FROM data"); + $sth->execute(); + $r = $sth->fetch(); + + if ($r['COUNT'] == 0) + $this->insert(array("Hans Hanson", "0815", "hans@hanson.de")); + $this->dbh->commit(); + } + + private function insert($entry) { + static $sth = null; + + if ($sth === null) + $sth = $this->dbh->prepare(self::INSERT_ENTRY); + + $sth->execute(array("name" => $entry[0], + "tel" => $entry[1], + "mail" => $entry[2])); + } + + public function get_all_entries() { + $entries = array(); + fseek($this->fh, 0, SEEK_SET); + while($line = stream_get_line($this->fh, 0, self::RS)) { + if ($line === FALSE) break; + $entries[] = explode(self::FS, $line); + } + return $entries; + } + + public function add_entry($entry) { + $fields = array('name', 'tel', 'mail'); + $new = array(); + foreach($fields as $key) { + if (!isset($entry[$key])) return; + $new[$key] = $entry[$key]; + trim($new[$key]); + preg_replace('/['.self::RS.self::FS.' ]+/', ' ', $new[$key]); + if (empty($new[$key])) return; + } + + flock($this->fh, LOCK_EX); + fputs($this->fh, join(self::FS, $new) . self::RS); + flock($this->fh, LOCK_UN); + header("Location: $_SERVER[PHP_SELF]?action=add"); + exit; + } + + public function search_entries($pattern) { + static $sth = null; + + if ($sth === null) + $sth = $this->dbh->prepare(self::SELECT_ENTRY); + + $pattern = trim($pattern); + if (empty($pattern)) return; + + $pattern = trim($pattern, '%'); + $pattern = "%$pattern%"; + + $sth->execute(array("name" => $pattern, + "tel" => $pattern, + "mail" => $pattern)); + $entries = array(); + while ($r = $sth->fetch()) { + $entries[] = array('name' => $r['NAME'], + 'tel' => $r['TEL'], + 'mail' => $r['MAIL']); + } + return $entries; + } + + public function delete_entries($ids) { } +} + +?>