PostgreSQL扩展在默认情况下在最新版本的PHP 5.3.x
中是启用的。 可以在编译时使用--without-pgsql
来禁用它。仍然可以使用yum
命令来安装PHP-PostgreSQL
接口:
yum install php-pgsql
Shell
在开始使用PHP连接PostgreSQL接口之前,请先在PostgreSQL安装目录中找到pg_hba.conf
文件,并添加以下行:
# IPv4 local connections:
host all all 127.0.0.1/32 md5
Shell
您可以启动/重新启动postgres服务器,使用以下命令运行:
[root@host]# service postgresql restart
Stopping postgresql service: [ OK ]
Starting postgresql service: [ OK ]
Shell
Windows用户必须启用php_pgsql.dll
才能使用此扩展名。这个DLL包含在最新版本的PHP 5.3.x
中的Windows发行版中。
PHP连接到PostgreSQL数据库
以下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
现在,让我们运行上面的程序打开数据库:testdb
,如果成功打开数据库连接,那么它将给出以下消息:
Opened database successfully
Shell
创建表
以下PHP程序将用于在之前创建的数据库(testdb
)中创建一个表:
<?php
$host = "host=127.0.0.1";
$port &