PostgreSQL DB 简单操作类
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><ul> <li>请确认主机支持PostgreSQL?</li><li>请确认用户名和密码正确?</li> <li>请确认主机名正确?(一般为localhost)</li></ul><p>如果你不确定这些情况,请询问你的主机提供商. 如果你还需要帮助你可以随时浏览 <a href='http://www.iiiphp.com'>iPHP 支持论坛</a>.</p>"); //@mysql_select_db(DB_NAME, self::$dbh) OR self::bail(" <h1>链接到<em><strong>".DB_NAME."</strong></em>数据库失败</h1> <p>我们能连接到数据库服务器(即数据库用户名和密码正确) ,但是不能链接到<em><strong>$db</strong></em>数据库.</p> <ul><li>你确定<em><strong>$db</strong></em>存在?</li></ul> <p>如果你不确定这些情况,请询问你的主机提供商.如果你还需要帮助你可以随时浏览 <a href='http://www.iiiphp.com'>iPHP 支持论坛</a>.</p>"); } // ================================================================== // 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("<div id='error'> <p class='iPHPDBerror'><strong>iPHP database error:</strong> [$str]<br /> <code>$query</code></p> </div>"); } 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 < pg_num_fields(self::$result)) { self::$col_info[$i] = pg_field_name(self::$result); $i++; } }else { $num_rows = 0; while ( $row = pg_fetch_object(self::$result) ) { self::$last_result[$num_rows] = $row; $num_rows++; } // Log number of rows the query returned self::$num_rows = $num_rows; // Return number of rows selected $return_val = $num_rows; } pg_free_result(self::$result); } return $return_val; } /** * Insert an array of data into a table * @param string $table WARNING: not sanitized! * @param array $data should not already be SQL-escaped * @return mixed results of self::query() */ function insert($table, $data) { // $data = add_magic_quotes($data); $fields = array_keys($data); return self::query("INSERT INTO ".DB_PREFIX_TAG."{$table} (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')"); } /** * Update a row in the table with an array of data * @param string $table WARNING: not sanitized! * @param array $data should not already be SQL-escaped * @param array $where a named array of WHERE column => 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 < count(self::$last_result); $i++ ) { $new_array[$i] = self::getValue(null, $x, $i); } return $new_array; } /** * Grabs column metadata from the last query * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill * @param int $col_offset 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type * @return mixed results */ function get_col_info($query = null ,$info_type = 'name', $col_offset = -1) { if ( $query ) self::query($query,"field"); if ( self::$col_info ) { if ( $col_offset == -1 ) { $i = 0; foreach(self::$col_info as $col ) { $new_array[$i] = $col->{$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 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head><title>iPHP PostgreSQL Error</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head><body><h1 id="logo"><img alt="iPHP" src="http://www.iiiphp.com/doc/iPHP.logo.gif" /></h1> <p>'.$message.'</p></body></html>'; exit(); } }
以上就是PostgreSQL DB 简单操作类的内容,更多相关内容请关注PHP中文网(www.php.cn)!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Oracle과 DB2는 엔터프라이즈급 애플리케이션에서 널리 사용되는 두 가지 잘 알려진 관계형 데이터베이스 관리 시스템(RDBMS)입니다. 본 글에서는 Oracle과 DB2의 두 가지 데이터베이스 기술을 비교하고, 이들의 특성, 성능, 기능, 활용 사례 분석 등을 자세하게 분석해보겠습니다. 1. 오라클 데이터베이스 기술 개요 오라클은 미국 오라클사가 개발한 관계형 데이터베이스 관리 시스템이다. 엔터프라이즈급 애플리케이션에 널리 사용되며 강력한 성능과 안정성을 갖추고 있습니다.

Oracle과 DB2는 일반적으로 사용되는 관계형 데이터베이스 관리 시스템으로, 각각 고유한 SQL 구문과 특성을 가지고 있습니다. 이 기사에서는 Oracle과 DB2의 SQL 구문을 비교 및 차이점을 설명하고 구체적인 코드 예제를 제공합니다. 데이터베이스 연결 Oracle에서는 다음 문을 사용하여 데이터베이스에 연결합니다. CONNECTusername/password@database DB2에서 데이터베이스에 연결하는 문은 다음과 같습니다. CONNECTTOdataba

Oracle 및 DB2 데이터베이스는 엔터프라이즈 수준 애플리케이션에서 널리 사용되는 두 가지 주요 관계형 데이터베이스 관리 시스템입니다. 실제 응용 프로그램에서 데이터베이스 성능은 데이터베이스 시스템의 품질을 평가하는 중요한 지표 중 하나인 경우가 많습니다. 이 기사에서는 Oracle과 DB2 데이터베이스의 성능을 비교 분석하고 특정 코드 예제를 사용하여 이들 간의 차이점을 보여줍니다. 1. 오라클 데이터베이스 성능 분석 오라클 데이터베이스는 확장성과 안정성이 뛰어난 강력한 데이터베이스 관리 시스템입니다.

db는 "database file"의 형식인 "datebase"의 약어입니다. 소프트웨어에서 데이터를 저장하는 데 사용하는 파일로, 각 소프트웨어마다 고유한 저장 형식이 있습니다. 예를 들어 Win7 시스템의 "Thumbs.db"는 썸네일 데이터 파일이므로 db 파일은 특정 파일 형식이 아닙니다.

MySQL 및 PostgreSQL: 성능 비교 및 최적화 팁 웹 애플리케이션을 개발할 때 데이터베이스는 필수적인 구성 요소입니다. 데이터베이스 관리 시스템을 선택할 때 MySQL과 PostgreSQL은 두 가지 일반적인 선택입니다. 둘 다 오픈 소스 관계형 데이터베이스 관리 시스템(RDBMS)이지만 성능과 최적화에는 약간의 차이가 있습니다. 이 기사에서는 MySQL과 PostgreSQL의 성능을 비교하고 몇 가지 최적화 팁을 제공합니다. 두 데이터베이스 관리를 비교한 성능 비교

MySQL 및 PostgreSQL: 웹 개발 모범 사례 소개: 현대 웹 개발 세계에서 데이터베이스는 필수 구성 요소입니다. 데이터베이스를 선택할 때 일반적인 선택은 MySQL과 PostgreSQL입니다. 이 문서에서는 웹 개발에 MySQL 및 PostgreSQL을 사용하는 모범 사례를 다루고 몇 가지 코드 예제를 제공합니다. 1. 적용 가능한 시나리오 MySQL은 대부분의 웹 애플리케이션, 특히 고성능, 확장성 및 사용 용이성을 요구하는 애플리케이션에 적합합니다.

db는 소프트웨어에서 데이터를 저장하는 데 사용되는 파일인 데이터베이스 파일 형식입니다. 각 소프트웨어에는 고유한 저장 형식이 있습니다. 즉, 일부 소프트웨어 데이터 파일의 접미사는 DB입니다. 예를 들어 Win7 시스템의 Thumbs.db는 썸네일 데이터 파일이므로 db 파일은 특정 파일 형식이 아닙니다.

Oracle과 DB2는 두 가지 일반적인 관계형 데이터베이스 관리 시스템으로, 각각 고유한 특성과 장점을 가지고 있습니다. 이 기사에서는 Oracle과 DB2의 특성을 비교하고 이들 간의 차이점을 설명하는 구체적인 코드 예제를 제공합니다. 1. 오라클 데이터베이스 관리 시스템의 특징: 스토리지 엔진: 오라클 데이터베이스는 대규모 데이터 스토리지를 처리할 수 있는 오라클 데이터베이스 엔진(OracleDatabaseEngine)이라는 고유한 스토리지 엔진을 사용합니다.
