php 使用pdo连接postgresql

有关pdo的使用可以参考:

http://www.cnblogs.com/xiaochaohuashengmi/archive/2010/08/12/1797753.html

1、连接数据库方法

function _conn($t) {
    //static $db;
    if (is_null ( $db )) {
        global $Config;
        $dsn = $Config ['server'] [$t] ['type'] . ":dbname=" . $Config ['server'] [$t] ['dbname'] . ";host=" . $Config ['server'] [$t] ['host'];
        //postgresql 的type为pgsql

     //echo $dsn; try { $db = new PDO ( $dsn, $Config ['server'] [$t] ['user'], $Config ['server'] [$t] ['passwd'] ); } catch ( PDOException $ex ) { print_r ( $ex ); return false; } } return $db; }

2、使用示例

//查询user表用户信息
$sql = sprintf ( "SELECT * FROM %s WHERE passport = '%s' and passwd = '%s';", "user", $passport, sha1 ( $passwd ) );
$info = $db->query ( $sql )->fetch ( PDO::FETCH_ASSOC );
//如果是insert或update语句,不能使用query,可以使用$db->exec($sql);

注意:使用postgresql时,lastInsertId()返回false,无法用

参考解决办法:

function pgsqlLastInsertId($sqlQuery, $pdoObject)
{
// Checks if query is an insert and gets table name
    if( preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $sqlQuery, $tablename) )
    {
// Gets this table's last sequence value
        $query = "SELECT currval('" . $tablename[1] . "_id_seq') AS last_value";
        $temp_q_id = $pdoObject->prepare($query);//$tablename[1]替换为你的表名
        $temp_q_id->execute();
        if($temp_q_id)
        {
            $temp_result = $temp_q_id->fetch(PDO::FETCH_ASSOC);
            return ( $temp_result ) ? $temp_result['last_value'] : false;
        }
    }return false;
}

$pdoObject = new PDO('pgsql:host=localhost;dbname=mydb', 'user', 'pass');
$sql = 'INSERT INTO table (column) VALUES (\'some_value\');';
$result = $pdoObject->prepare($sql);
$result->execute();
//至此,可以成功的取到上一条插入数据的id了。
echo 'Last Insert ID: ' . pgsqlLastInsertId($sql, $pdoObject);                

 

posted @ 2013-01-16 14:57  欧麦噶地  阅读(1604)  评论(0编辑  收藏  举报