PostgreSQL是以加州大学伯克利分校计算机系开发的 POSTGRES,现在已经更名为PostgreSQL,版本 4.2为基础的对象关系型数据库管理系统(ORDBMS)。PostgreSQL支持大部分 SQL标准并且提供了许多其他现代特性:复杂查询、外键、触发器、视图、事务完整性、MVCC。同样,PostgreSQL 可以用许多方法扩展,比如, 通过增加新的数据类型、函数、操作符、聚集函数、索引。免费使用、修改、和分发 PostgreSQL,不管是私用、商用、还是学术研究使用。
下面我们来看看php如何来连接操作postgresql数据库,首先我们还是需要开启支持postgresql数据库的扩展,他的名字叫php_pgsql,扩展的开启这里咱不讲解,我们直接来看看php操作实例
数据库连接配置conn.php
<?php $host = "host=127.0.0.1"; $port = "port=5432"; $dbname = "dbname=testdb"; $credentials = "user=postgres password=pass123"; $db = pg_connect( "$host $port $dbname $credentials" ); if(!$db){ echo "Error : Unable to open database\n"; } else { echo "Opened database successfully\n"; } ?>
插入数据操作
<?php include 'conn.php' $sql =<<<EOF INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 ); INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 ); EOF; $ret = pg_query($db, $sql); if(!$ret){ echo pg_last_error($db); } else { echo "Records created successfully\n"; } pg_close($db); ?>
查询数据操作
<?php include 'conn.php' $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = pg_query($db, $sql); if(!$ret){ echo pg_last_error($db); exit; } while($row = pg_fetch_row($ret)){ echo "ID = ". $row[0] . "\n"; echo "NAME = ". $row[1] ."\n"; echo "ADDRESS = ". $row[2] ."\n"; echo "SALARY = ".$row[4] ."\n\n"; } echo "Operation done successfully\n"; pg_close($db); ?>
更新数据操作
<?php include 'conn.php' $sql =<<<EOF UPDATE COMPANY set SALARY = 25000.00 where ID=1; EOF; $ret = pg_query($db, $sql); if(!$ret){ echo pg_last_error($db); exit; } else { echo "Record updated successfully\n"; } $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = pg_query($db, $sql); if(!$ret){ echo pg_last_error($db); exit; } while($row = pg_fetch_row($ret)){ echo "ID = ". $row[0] . "\n"; echo "NAME = ". $row[1] ."\n"; echo "ADDRESS = ". $row[2] ."\n"; echo "SALARY = ".$row[4] ."\n\n"; } echo "Operation done successfully\n"; pg_close($db); ?>
删除数据操作
<?php include 'conn.php' $sql =<<<EOF DELETE from COMPANY where ID=2; EOF; $ret = pg_query($db, $sql); if(!$ret){ echo pg_last_error($db); exit; } else { echo "Record deleted successfully\n"; } $sql =<<<EOF SELECT * from COMPANY; EOF; $ret = pg_query($db, $sql); if(!$ret){ echo pg_last_error($db); exit; } while($row = pg_fetch_row($ret)){ echo "ID = ". $row[0] . "\n"; echo "NAME = ". $row[1] ."\n"; echo "ADDRESS = ". $row[2] ."\n"; echo "SALARY = ".$row[4] ."\n\n"; } echo "Operation done successfully\n"; pg_close($db); ?>