[转载]php连接postgreSQL数据库及其操作(php5,postgreSQL9)

数据库连接:
dbconn.php
<?php
$conn = pg_connect("host=localhost port=5432 dbname=myd user=postgres password=postgres");

if($conn){
    print "has connected" . "<br>";
}else{
    print "connect failure" . "<br>";
}
?>
 插入操作:
insert.php
<?php
require_once 'dbconn.php';

//下面是PHP插入postgreSQL数据库使用prepared的方式;
/*
 * 注意一下几点:
 * 1、待设置参数只能是$1起的一次往下类推,而不能是其他的任何东西如:$a是不合法的。
 * 
 * 2、pg_prepare有三个必须的参数,第一个是数据库的链接;第二个是我们预编译语句的名称,
 * 待以后使用,可以指定为"";第三个是我们要执行的SQL语句。
 * 
 * 3、执行语句本列子在for循环中,第一参数是链接,第二参数是要执行的预编译语句,第三参数是一个数组用于
 * 指定我们与预编译语句中的未设置的参数。
 */

$str = 'insert into test values($1,$2)';

pg_prepare($conn, "mypre", $str);

for($i = 0; $i < 3; $i ++) :
    pg_execute ( $conn, "mypre",array($i.'A',$i.'B') );
endfor;
?>

查询及其删除操作:

select.php
<?php
require_once 'dbconn.php';

$str = "select * from test";

$resultSet = pg_query($conn,$str);

while ($row = pg_fetch_row($resultSet)){
    print $row[0].' '.$row[1]."<br>";
}
?>
the next is affter delete;
<br/>
<?php 
/**
 * 以下是删除的一种方法,是用pg_delete完成的,不知道能不能删除多行记录,反正我现在还没有实现。
 * 
 */
$arr = array('id'=>'0A');

pg_delete($conn,'test',$arr);

/**
 * 以下是用预编译的形式实现的,但是当没有未知的参数的时候,要传给pg_execute函数一个空数组否则会报错。
 * 
 */
$remove = 'delete from test where id = $1';

pg_prepare($conn,"remove",$remove);


pg_execute($conn,"remove",array('id'=>'1A'));

?>

<br/>
<?php 
$resultSet = pg_query($conn,$str);

while ($row = pg_fetch_row($resultSet)){
    print $row[0].' '.$row[1]."<br>";
}
?>

更新操作:

update.php
<?php
require_once 'dbconn.php';

$update = 'update test set email = $1 where id = $2';

pg_prepare($conn,'update',$update);

$id = '1A';

pg_execute($conn,'update',array('email'=>'111','id'=>$id));

?>

注意:代码中由于表中字段相关的语句,表结构如下:

create table test (id cahr(8),email char(8));

原文地址:https://www.cnblogs.com/zzyyxxjc/p/4453485.html