• 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);                
  • 相关阅读:
    K近邻(K Nearest Neighbor-KNN)原理讲解及实现
    Bisecting KMeans (二分K均值)算法讲解及实现
    KMeans (K均值)算法讲解及实现
    NodeJs使用async让代码按顺序串行执行
    NodeJs递归删除非空文件夹
    NodeJs之配置文件管理
    NodeJs针对Express框架配置Mysql进行数据库操作
    在Express中使用Multiparty进行文件上传及POST、GET参数获取
    Linux操作命令
    SftpUtil FTP文件上传
  • 原文地址:https://www.cnblogs.com/wuheping/p/2862782.html
Copyright © 2020-2023  润新知