首頁  >  文章  >  後端開發  >  PHP操作Postgresql封裝類別與應用程式完整實例

PHP操作Postgresql封裝類別與應用程式完整實例

不言
不言原創
2018-04-24 13:47:581711瀏覽

這篇文章主要介紹了PHP操作Postgresql封裝類別,結合實例形式分析了php針對Postgresql資料庫常見的連接、查詢、統計等操作封裝技巧與使用方法,需要的朋友可以參考下

#本文實例講述了PHP操作Postgresql封裝類別與應用。分享給大家供大家參考,具體如下:

這個類別封裝了一些常用的函數,原帖裡面還有事務處理的內容,以後再學習吧。

類別檔案定義:


<?php
class pgsql {
private $linkid; // PostgreSQL连接标识符
private $host; // PostgreSQL服务器主机
private $port; // PostgreSQL服务器主机端口
private $user; // PostgreSQL用户
private $passwd; // PostgreSQL密码
private $db; // Postgresql数据库
private $result; // 查询的结果
private $querycount; // 已执行的查询总数
/* 类构造函数,用来初始化$host、$user、$passwd和$db字段。 */
function __construct($host, $port ,$db, $user, $passwd) {
$this->host = $host;
$this->port = $port;
$this->user = $user;
$this->passwd = $passwd;
$this->db = $db;
}
/* 连接Postgresql数据库 */
function connect(){
try{
$this->linkid = @pg_connect("host=$this->host port=$this->port dbname=$this->db
user=$this->user password=$this->passwd");
if (! $this->linkid)
throw new Exception("Could not connect to PostgreSQL server.");
}
catch (Exception $e) {
die($e->getMessage());
}
}
/* 执行数据库查询。 */
function query($query){
try{
$this->result = @pg_query($this->linkid,$query);
if(! $this->result)
throw new Exception("The database query failed.");
}
catch (Exception $e){
echo $e->getMessage();
}
$this->querycount++;
return $this->result;
}
/* 确定受查询所影响的行的总计。 */
function affectedRows(){
$count = @pg_affected_rows($this->linkid);
return $count;
}
/* 确定查询返回的行的总计。 */
function numRows(){
$count = @pg_num_rows($this->result);
return $count;
}
/* 将查询的结果行作为一个对象返回。 */
function fetchObject(){
$row = @pg_fetch_object($this->result);
return $row;
}
/* 将查询的结果行作为一个索引数组返回。 */
function fetchRow(){
$row = @pg_fetch_row($this->result);
return $row;
}
/* 将查询的结果行作为一个关联数组返回。 */
function fetchArray(){
$row = @pg_fetch_array($this->result);
return $row;
}
/* 返回在这个对象的生存期内执行的查询总数。这不是必须的,但是您也许会感兴趣。 */
function numQueries(){
return $this->querycount;
}
}
?>


#測試的php一並放出,另外測試了下區域網路內的另一台postgresql伺服器,感覺查詢速度還是很快的,查詢postgregis資料也是槓槓滴。


<?php
  include &#39;PGDB.php&#39;;
  $PG = new pgsql("192.168.1.167", "5432", "postgis", "postgres", "post");
  $PG->connect();
  if(!$PG)
  {
    $db_error = "无法连接到PostGreSQL数据库!";
    echo $db_error;
  }
  else
  {
    echo "成功连接!";
    $query = "select name from ex where gid = 2";
    $result = $PG->query($query);
    $row = $PG->fetchRow();
    echo $row[0];
  }
?>

相關推薦:

postgreSQL php及客戶端


以上是PHP操作Postgresql封裝類別與應用程式完整實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn