postgre.php (1629B)
1 <?php 2 namespace DB; 3 final class Postgre { 4 private $link; 5 6 public function __construct($hostname, $username, $password, $database, $port = '5432') { 7 if (!$this->link = pg_connect('hostname=' . $hostname . ' port=' . $port . ' username=' . $username . ' password=' . $password . ' database=' . $database)) { 8 throw new \Exception('Error: Could not make a database link using ' . $username . '@' . $hostname); 9 } 10 11 if (!mysql_select_db($database, $this->link)) { 12 throw new \Exception('Error: Could not connect to database ' . $database); 13 } 14 15 pg_query($this->link, "SET CLIENT_ENCODING TO 'UTF8'"); 16 } 17 18 public function query($sql) { 19 $resource = pg_query($this->link, $sql); 20 21 if ($resource) { 22 if (is_resource($resource)) { 23 $i = 0; 24 25 $data = array(); 26 27 while ($result = pg_fetch_assoc($resource)) { 28 $data[$i] = $result; 29 30 $i++; 31 } 32 33 pg_free_result($resource); 34 35 $query = new \stdClass(); 36 $query->row = isset($data[0]) ? $data[0] : array(); 37 $query->rows = $data; 38 $query->num_rows = $i; 39 40 unset($data); 41 42 return $query; 43 } else { 44 return true; 45 } 46 } else { 47 throw new \Exception('Error: ' . pg_result_error($this->link) . '<br />' . $sql); 48 } 49 } 50 51 public function escape($value) { 52 return pg_escape_string($this->link, $value); 53 } 54 55 public function countAffected() { 56 return pg_affected_rows($this->link); 57 } 58 59 public function getLastId() { 60 $query = $this->query("SELECT LASTVAL() AS `id`"); 61 62 return $query->row['id']; 63 } 64 65 public function __destruct() { 66 pg_close($this->link); 67 } 68 }