data = $data; $this->table = $table; } function connect($user = 'user', $pwd = 'pwd', $db = 'myDB', $server = '') { if (!mysql_connect($server, $user, $pwd)) { trigger_error('Could not connect to mysqld.'); return false; } if (!mysql_select_db($db)) { trigger_error(mysql_error()); return false; } return true; } function getID() { return $this->id; } function read($key) { $query = 'SELECT `'.$this->table.'_id`'; foreach ($this->data as $name => $value) { $query .= ', `'.$name.'`'; } $query .= ' FROM `'.$this->table.'` WHERE `'.$key.'`="'.$this->data[$key].'"'; if (!$result = mysql_query($query)) { trigger_error(mysql_error()); return false; } if (mysql_num_rows($result) != 1) { return false; } $result = mysql_fetch_assoc($result); $this->id = $result[$this->table.'_id']; unset($result[$this->table.'_id']); return $result; } function getSetString() { $set = 'SET'; foreach ($this->data as $name => $value) { $set .= "\n`".$name.'`="'.$value.'",'; } return substr($set, 0, -1); } function insert() { $query = 'INSERT into `'.$this->table.'` '.$this->getSetString(); $return = mysql_query($query); if ($return && mysql_affected_rows() == 1) { $this->id = mysql_insert_id(); } return $return; } function update() { $query = 'UPDATE `'.$this->table.'` '.$this->getSetString().' WHERE `'.$this->table.'_id`='.$this->id; return mysql_query($query); } function delete() { $query = 'DELETE FROM `'.$this->table.'` WHERE `'.$this->table.'_id`='.$this->id; return mysql_query($query); } function save($key) { $read = $this->read($key); if ($read) { if ($read != $this->data) { return $this->update(); } return true; } return $this->insert(); } } ?>