【opencart3源码分析】postgresql类pgsql.php

<?php
namespace DB;
final class PgSQL {
	private $connection;

	// 构造方法
	public function __construct($hostname, $username, $password, $database, $port = '5432') {
		$this->connection = @pg_connect('hostname=' . $hostname . ' port=' . $port .  ' username=' . $username . ' password='	. $password . ' database=' . $database);

		if (!$this->connection) {
			throw new \Exception('Error: Could not make a database link using ' . $username . '@' . $hostname);
		}

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

	// 查询
	public function query($sql) {
		$resource = pg_query($this->connection, $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->connection) . '<br />' . $sql);
		}
	}

	// 过滤
	public function escape($value) {
		return pg_escape_string($this->connection, $value);
	}

	// 受影响行数
	public function countAffected() {
		return pg_affected_rows($this->connection);
	}

	//判断是否已经连接
	public function isConnected() {
		if (pg_connection_status($this->connection) == PGSQL_CONNECTION_OK) {
			return true;
		} else {
			return false;
		}
	}

	// 获取最后一条记录id
	public function getLastId() {
		$query = $this->query("SELECT LASTVAL() AS `id`");

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

	// 关闭连接
	public function __destruct() {
		if ($this->isConnected()) {
			pg_close($this->connection);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq2942713658/article/details/81434379
今日推荐