1.
要让PHP支持PostgreSQL,就需要重新编译PHP;
./configure --prefix=/usr/local/php5 --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql=/usr/local/mysql --with-config-file-path=/usr/local/php5 --with-zlib --enable-mbstring=all --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql=/usr/local/mysql--with-pgsql=/usr/local/pgsql
最后一个参数指明pgsql的路径(注意,这是你自己的pgsql路径!)
然后:
make
sudo make install
2.
如果已经启动了Apache,需要重启Apache:
sudo apachectl restart
3.
为了测试,我们先建一个测试数据库:
在终端输入以下命令:
createdb classdb
psql classdb
create table class(id int, name varchar(20), email varchar(20));
4.
在Apache的Web根目录下新建一个index.php文件,内容如下:
$conn = pg_connect("host=localhost port=5432 dbname=classdb user=postgresql password=postgresql");
if($conn){
print "OK! Has connected" . "
";
}else{
print "Error! Connect failure" . "
";
}
?>
注意,需要修改pg_connect的相关参数!(5432是pgsql的默认端口,就像mysql的3306端口)
显示OK! Has connected. 表示已连接上pgsql。
5.
然后我们在php中插入记录到pgsql中,修改index.php如下:
$conn = pg_connect("host=localhost port=5432 dbname=classdb user=postgresql password=postgresql");
if($conn)
{
print "OK! Has connected" . "
";
}
else
{
print "Error! Connect failure" . "
";
}
?>
id: | |
name: | |
email: | |
// insert
$id = $_POST["id"];
$name = $_POST["name"];
$email = $_POST["email"];
if($id && $name && $email)
{
$query = "INSERT INTO class VALUES($id, '$name', '$email')";
$result = pg_query($query);
}
// select
$query = 'SELECT * FROM class';
$result = pg_query($query);
?>
id | name |
---|
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo "
";foreach ($line as $col_value)
{
echo "
$col_value";}
echo "
";}
echo "
";// 释放结果集
pg_free_result($result);
// 关闭连接
pg_close($conn);
?>
在浏览器中:http://localhost/index.php 即可看到效果。