database = $database; $this->username = $username; $this->password = $password; $this->hostname = $hostname; } private function connect() { if (null !== $this->dbh) { return; } $this->dbh = mysql_connect($this->hostname, $this->username, $this->password); if (false === $this->dbh) { throw new \RuntimeException('Cannot connect to MySQL server.'); } if (false === mysql_select_db($this->database, $this->dbh)) { throw new \RuntimeException('Cannot select database.'); } } private function query($query) { $this->connect(); $result = mysql_query($query, $this->dbh); if (false === $result) { throw new \RuntimeException('SQL query execution failed: '.$query); } return $result; } private function quote($data) { $this->connect(); return mysql_real_escape_string($data, $this->dbh); } public function deleteTask($id) { $this->query('DELETE FROM todo WHERE id = '. (int) $id); if (!mysql_affected_rows($this->dbh)) { throw new \RuntimeException('Unable to delete task #'.$id); } } public function closeTask($id) { $this->query('UPDATE todo SET is_done = 1 WHERE id = '. (int) $id); if (!mysql_affected_rows($this->dbh)) { throw new \RuntimeException('Unable to close task #'.$id); } } public function createTask($title) { if (empty($title)) { throw new \InvalidArgumentException('Title must be filled.'); } $this->query(sprintf( "INSERT INTO todo (title) VALUES ('%s');", $this->quote($title) )); if (!mysql_affected_rows($this->dbh)) { throw new \RuntimeException(sprintf('Unable to create new task "%s".', $title)); } } public function countTasks() { $result = $this->query('SELECT COUNT(*) FROM todo'); return (int) current(mysql_fetch_row($result)); } public function getTask($id) { $result = $this->query('SELECT * FROM todo WHERE id = '. (int) $id); return mysql_fetch_assoc($result); } public function getAllTasks() { $tasks = array(); $result = $this->query('SELECT * FROM todo'); while ($todo = mysql_fetch_assoc($result)) { $tasks[] = $todo; } return $tasks; } }