PostgreSQL DB 简单操作类

老敏君_6181

老敏君_6181

2016-05-25

1339人浏览

原创

postgresql db 简单操作类 

只用来执行sql的 其它的不懂 

//使用 

define('db_name', 'aaaa');// 数据库名 
define('db_user', 'root');// 数据库用户 
define('db_password', '123456');//数据库密码 
define('db_host', 'localhost');// 服务器名或服务器ip,一般为localhost 
define('db_charset', 'utf8');//postgresql编码设置.如果您的程序出现乱码现象,需要设置此项来修复. 请不要随意更改此项,否则将可能导致系统出现乱码现象 
define('db_prefix', 'icms_');// 表名前缀, 同一数据库安装多个请修改此处 
define('db_prefix_tag', '#icms@__');// sql表名前缀替换 


idb::query(sql); 
idb::getvalue(sql); 
idb::getrow(sql); 
idb::getarray(sql); 

1.iPgsql.class.php

<?php /**
* iPHP - i PHP Framework
* Copyright (c) 2012 iiiphp.com. All rights reserved.
*
* @author coolmoo <iiiphp@qq.com>
* @site http://www.iiiphp.com
* @licence http://www.iiiphp.com/license
* @version 1.0.1
* @package iDB
* @$Id: iPgsql.class.php 44 2012-03-30 04:02:10Z coolmoo $
*/
define('DB_PORT', 5432);
define('OBJECT', 'OBJECT', true);
define('ARRAY_A', 'ARRAY_A', false);
define('ARRAY_N', 'ARRAY_N', false);
 
defined('SAVEQUERIES') OR define('SAVEQUERIES', true);
 
class iDB{
    public static $show_errors = false;
    public static $num_queries = 0;
    public static $last_query;
    public static $col_info;
    public static $queries;
    public static $func_call;
    public static $last_result;
    public static $num_rows;
    public static $insert_id;
 
    private static $collate;
    private static $time_start;
    private static $last_error ;
    private static $dbh;
    private static $result;
 
    function __construct() {
        if (!self::$dbh)
            self::connect();
    }
    function connect() {
        extension_loaded('pgsql') OR die('您的 PHP 安装看起来缺少 PostgreSQL 数据库部分,
        这对 iPHP 来说是必须的。');
         
        defined('DB_COLLATE') && self::$collate = DB_COLLATE;
 
        self::$dbh = pg_connect("host=".DB_HOST." port=".DB_PORT." dbname=".DB_NAME.
        " user=".DB_USER." password=".DB_PASSWORD);
 
        defined('DB_CHARSET') && self::query("set client_encoding to '".DB_CHARSET."'");
 
        self::$dbh OR self::bail("<h1>数据库链接失败</h1>
        <p>请检查 <em><strong>config.php</strong></em> 的配置是否正确!</p>
            
  • 请确认主机支持PostgreSQL?
  • 请确认用户名和密码正确?
  •         
  • 请确认主机名正确?(一般为localhost)

如果你不确定这些情况,请询问你的主机提供商.         如果你还需要帮助你可以随时浏览 iPHP 支持论坛.

");         //@mysql_select_db(DB_NAME, self::$dbh) OR self::bail("         

链接到".DB_NAME."数据库失败

我们能连接到数据库服务器(即数据库用户名和密码正确) ,但是不能链接到$db数据库.

  • 你确定$db存在?

如果你不确定这些情况,请询问你的主机提供商.如果你还需要帮助你可以随时浏览  iPHP 支持论坛.

");       }     // ==================================================================     //  Print SQL/DB error.       function print_error($str = '') {         if (!$str)             $str = pg_result_error(self::$dbh);           $EZSQL_ERROR[]  = array ('query' => self::$last_query, 'error_str' => $str);           $str    = htmlspecialchars($str, ENT_QUOTES);         $query  = htmlspecialchars(self::$last_query, ENT_QUOTES);         // Is error output turned on or not..         if ( self::$show_errors ) {             // If there is an error then take note of it             die("
            

iPHP database error: [$str]
            $query

            
");         } else {             return false;         }     }     // ==================================================================     //  Kill cached query results       function flush() {         self::$last_result  = array();         self::$col_info     = null;         self::$last_query   = null;     }       // ==================================================================     //  Basic Query - see docs for more detail       function query($query,$QT=NULL) {         if (!self::$dbh) {             self::connect();         }         // filter the query, if filters are available         // NOTE: some queries are made before the plugins have been loaded,          and thus cannot be filtered with this method         $query=str_replace(DB_PREFIX_TAG,DB_PREFIX, $query);           // initialise return         $return_val = 0;         self::flush();           // Log how the function was called         self::$func_call = __CLASS__."::query(\"$query\")";           // Keep track of the last query for debug..         self::$last_query = $query;           // Perform the query via std pgsql_query function..         if (SAVEQUERIES) self::timer_start();           self::$result = pg_query(self::$dbh,$query);                     self::$num_queries++;           if (SAVEQUERIES) self::$queries[] = array( $query, self::timer_stop());           // If there is an error then take note of it..         if ( self::$last_error = pg_result_error(self::$result) ) {             self::print_error();             return false;         }         $QH = strtoupper(substr($query,0,strpos($query, ' ')));         if (in_array($QH,array("INSERT","DELETE","UPDATE","REPLACE"))) {             $rows_affected = pg_affected_rows (self::$result);             // Take note of the insert_id             if (in_array($QH,array("INSERT","REPLACE"))) {                 self::$insert_id = pg_last_oid(self::$result);             }             // Return number of rows affected             $return_val = $rows_affected;         } else {             if($QT=="field") {                 $i = 0;                 while ($i  value relationships.        Multiple member pairs will be joined with ANDs.         WARNING: the column names are not currently sanitized!      * @return mixed results of self::query()      */     function update($table, $data, $where) { //      $data = add_magic_quotes($data);         $bits = $wheres = array();         foreach ( array_keys($data) as $k )             $bits[] = "`$k` = '$data[$k]'";           if ( is_array( $where ) )             foreach ( $where as $c => $v )                 $wheres[] = "$c = '" . addslashes( $v ) . "'";         else             return false;         return self::query("UPDATE ".DB_PREFIX_TAG."{$table} SET "          . implode( ', ', $bits ) . ' WHERE ' .          implode( ' AND ', $wheres ) . ' LIMIT 1' );     }     /**      * Get one variable from the database      * @param string $query (can be null as well, for caching, see codex)      * @param int $x = 0 row num to return      * @param int $y = 0 col num to return      * @return mixed results      */     function getValue($query=null, $x = 0, $y = 0) {         self::$func_call = __CLASS__."::getValue(\"$query\",$x,$y)";         if ( $query )             self::query($query);           // Extract var out of cached results based x,y vals         if ( !empty( self::$last_result[$y] ) ) {             $values = array_values(get_object_vars(self::$last_result[$y]));         }         // If there is a value return it else return null         return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;     }       /**      * Get one row from the database      * @param string $query      * @param string $output ARRAY_A | ARRAY_N | OBJECT      * @param int $y row num to return      * @return mixed results      */     function getRow($query = null, $output = OBJECT, $y = 0) {         self::$func_call = __CLASS__."::getRow(\"$query\",$output,$y)";         if ( $query )             self::query($query);           if ( !isset(self::$last_result[$y]) )             return null;           if ( $output == OBJECT ) {             return self::$last_result[$y] ? self::$last_result[$y] : null;         } elseif ( $output == ARRAY_A ) {             return self::$last_result[$y] ? get_object_vars(self::$last_result[$y]) : null;         } elseif ( $output == ARRAY_N ) {             return self::$last_result[$y]              ? array_values(get_object_vars(self::$last_result[$y])) : null;         } else {             self::print_error(__CLASS__."::getRow(string query, output type, int offset)              -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");         }     }       /**      * Return an entire result set from the database      * @param string $query (can also be null to pull from the cache)      * @param string $output ARRAY_A | ARRAY_N | OBJECT      * @return mixed results      */     function getArray($query = null, $output = ARRAY_A) {         self::$func_call = __CLASS__."::getArray(\"$query\", $output)";           if ( $query )             self::query($query);           // Send back array of objects. Each row is an object         if ( $output == OBJECT ) {             return self::$last_result;         } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {             if ( self::$last_result ) {                 $i = 0;                 foreach( (array) self::$last_result as $row ) {                     if ( $output == ARRAY_N ) {                         // ...integer-keyed row arrays                         $new_array[$i] = array_values( get_object_vars( $row ) );                     } else {                         // ...column name-keyed row arrays                         $new_array[$i] = get_object_vars( $row );                     }                     ++$i;                 }                 return $new_array;             } else {                 return null;             }         }     }       /**      * Gets one column from the database      * @param string $query (can be null as well, for caching, see codex)      * @param int $x col num to return      * @return array results      */     function getCol($query = null , $x = 0) {         if ( $query )             self::query($query);           $new_array = array();         // Extract the column values         for ( $i=0; $i {$info_type};                     $i++;                 }                 return $new_array;             } else {                 return self::$col_info[$col_offset]->{$info_type};             }         }     }     function version() {         // Make sure the server has PostgreSQL 4.0         $v = pg_version(self::$dbh);         return $v['client'];     }       /**      * Starts the timer, for debugging purposes      */     function timer_start() {         $mtime = microtime();         $mtime = explode(' ', $mtime);         self::$time_start = $mtime[1] + $mtime[0];         return true;     }       /**      * Stops the debugging timer      * @return int total time spent on the query, in milliseconds      */     function timer_stop() {         $mtime = microtime();         $mtime = explode(' ', $mtime);         $time_end = $mtime[1] + $mtime[0];         $time_total = $time_end - self::$time_start;         return $time_total;     }       /**      * Wraps fatal errors in a nice header and footer and dies.      * @param string $message      */     function bail($message){ // Just wraps errors in a nice header and footer         if ( !self::$show_errors ) {             return false;         }         header('Content-Type: text/html; charset=utf8');         echo 'html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional         //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">         iPHP PostgreSQL Error               

        

'.$message.'

PostgreSQL 18.4 ubuntu
PostgreSQL 18.4 ubuntu

PostgreSQL 18.4 官方 Ubuntu 安装包现已发布,这是目前最新的稳定版本。推荐通过官方 APT 仓库安装:先执行 sudo apt update 更新索引,再运行 sudo apt install postgresql-18 即可完成部署。新版本引入了异步 I/O 子系统,在顺序扫描与 VACUUM 场景下性能提升显著,同时支持 UUID v7 原生生成函数与虚拟生成列。

下载
';         exit();     } }


 以上就是PostgreSQL DB 简单操作类的内容,更多相关内容请关注PHP中文网(www.php.cn)!


相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

postgresql

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Navicat创建数据库教程
Navicat创建数据库教程

本专题整理Navicat创建数据库相关教程,介绍新建前的准备、基础设置和创建后的检查方法。内容兼顾入门学习及实际使用需求,帮助用户了解不同数据库类型下的操作差异,为后续建表、保存数据和日常管理提供参考。

2026.11.20

0

7

Navicat入门教程大全
Navicat入门教程大全

本专题整理Navicat入门教程,从认识软件界面到开展数据库操作,介绍初次使用需要了解的知识和方法。内容兼顾连接配置、数据管理及日常使用中的疑问,方便用户按学习进度查阅,为后续实践和独立操作打好基础。

2026.11.20

0

17

Navicat数据库连接配置指南
Navicat数据库连接配置指南

从确认数据库信息到建立可用连接,本专题串联Navicat连接数据库的相关知识和操作方法。既有初次配置时需要了解的基础内容,也有连接后的检查思路,方便用户按实际需求查阅教程,逐步熟悉数据库连接的设置流程。

2026.11.20

0

10

PHP8.6数组与数据处理教程
PHP8.6数组与数据处理教程

本专题汇总PHP8.6数组与数据处理教程,涵盖CSV读取和导出、引用遍历删除、array_filter回调模式、配置键名冲突、pathinfo文件名校验、GMP大整数进制转换及UTF-8正则筛选,说明升级兼容变化、输入范围和失败处理方法。

2026.11.20

0

8

PHP8.6升级迁移教程
PHP8.6升级迁移教程

本专题汇总PHP8.6升级迁移与弃用接口改造教程,涵盖反射调用、对象属性赋值、标识符更名、构造函数与__debugInfo调整,以及插件类名检查、常量导出、ArrayIterator排序、SPL和DTO查询参数转换,帮助梳理弃用提示并完成代码兼容改造。

2026.11.20

0

10

PHP8.6安装配置与FPM运维教程
PHP8.6安装配置与FPM运维教程

本专题汇总PHP8.6正式版安装部署与FPM运维教程,涵盖Linux并存安装、独立ini配置、扩展重新编译、Nginx切换与回滚、FPM状态监控和慢日志排查,以及环境变量、请求超时、OPcache刷新和预加载配置。

2026.11.20

0

10

Nginx CVE-2026-123007排查与防护指南
Nginx CVE-2026-123007排查与防护指南

Nginx HTTP/2漏洞该怎么修复?本专题围绕CVE-2026-123007,介绍安全版本升级、模块兼容检查和配置恢复方法,以及日志排查、权限设置等后续加固操作,方便你按实际部署情况查找对应教程。

2026.11.20

20

8

GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

2026.11.17

60

15

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.17

80

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PostgreSQL vs MySQL
PostgreSQL vs MySQL

共1课时 | 201人学习

PostgreSQL 教程
PostgreSQL 教程

共48课时 | 21.1万人学习

PostgreSQL 手册
PostgreSQL 手册

共0课时 | 1万人学习