PHP 操作 PostgreSQL数据库
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文件,内容如下:
<?php
$conn = pg_connect("host=localhost port=5432 dbname=classdb user=postgresql password=postgresql");
if($conn){
print "OK! Has connected" . "<br>";
}else{
print "Error! Connect failure" . "<br>";
}
?>
注意,需要修改pg_connect的相关参数!(5432是pgsql的默认端口,就像mysql的3306端口)
显示OK! Has connected. 表示已连接上pgsql。
5.
然后我们在php中插入记录到pgsql中,修改index.php如下:
<?php
$conn = pg_connect("host=localhost port=5432 dbname=classdb user=postgresql password=postgresql");
if($conn)
{
print "OK! Has connected" . "<br>";
}
else
{
print "Error! Connect failure" . "<br>";
}
?>
</br>
<form action="index.php" method="post">
<table>
<caption><strong>Insert</strong></caption>
<tr>
<td><strong>id:</strong></td>
<td><input type="text" name="id"></input></td>
<tr>
<td><strong>name:</strong></td>
<td><input type="text" name="name"></input></td>
<tr>
<td><strong>email:</strong></td>
<td><input type="text" name="email"></input></td>
<tr>
<tr>
<td><input type="submit" value="INSERT"></input></td>
</tr>
</table>
</form>
<?php
// 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);
?>
<table border="1">
<tr><th>id</th><th>name</th><th>email</th></tr>
<?php
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo "<tr>";
foreach ($line as $col_value)
{
echo "<td>$col_value</td>";
}
echo "</tr>";
}
echo "</table>";
// 释放结果集
pg_free_result($result);
// 关闭连接
pg_close($conn);
?>
在浏览器中:http://localhost/index.php 即可看到效果。