aboutsummaryrefslogtreecommitdiffstats
path: root/public/system/library/db/postgre.php
blob: 9d86b1e05f9db2eae6de246d84fa191a06830f36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
namespace DB;
final class Postgre {
	private $link;

	public function __construct($hostname, $username, $password, $database, $port = '5432') {
		if (!$this->link = pg_connect('hostname=' . $hostname . ' port=' . $port .  ' username=' . $username . ' password='	. $password . ' database=' . $database)) {
			throw new \Exception('Error: Could not make a database link using ' . $username . '@' . $hostname);
		}

		if (!mysql_select_db($database, $this->link)) {
			throw new \Exception('Error: Could not connect to database ' . $database);
		}

		pg_query($this->link, "SET CLIENT_ENCODING TO 'UTF8'");
	}

	public function query($sql) {
		$resource = pg_query($this->link, $sql);

		if ($resource) {
			if (is_resource($resource)) {
				$i = 0;

				$data = array();

				while ($result = pg_fetch_assoc($resource)) {
					$data[$i] = $result;

					$i++;
				}

				pg_free_result($resource);

				$query = new \stdClass();
				$query->row = isset($data[0]) ? $data[0] : array();
				$query->rows = $data;
				$query->num_rows = $i;

				unset($data);

				return $query;
			} else {
				return true;
			}
		} else {
			throw new \Exception('Error: ' . pg_result_error($this->link) . '<br />' . $sql);
		}
	}

	public function escape($value) {
		return pg_escape_string($this->link, $value);
	}

	public function countAffected() {
		return pg_affected_rows($this->link);
	}

	public function getLastId() {
		$query = $this->query("SELECT LASTVAL() AS `id`");

		return $query->row['id'];
	}

	public function __destruct() {
		pg_close($this->link);
	}
}