Home php教程 php手册 使用PHPLIB访问多个数据库

使用PHPLIB访问多个数据库

Jun 13, 2016 am 10:35 AM
php use Can land Multiple it Library us Expand database yes of access

PHPLIB是PHP的一些扩展库,使用它我们可以很方便地对数据库进行各种操作,不过,如果你要使用多个数据库的话,它就显得力不从心了,本文介绍了通过扩展PHPLIB,让你鱼和熊掌兼得,在使用PHPLIB的同时可以使用多个数据库,而且从中你也可以了解到面向对象编程和如何扩展库的知识,值得一读。

数据库管理

   你可以在一个大型的数据库中放入任何表。不过时间长了,将会令数据库变得越来越大,服务器可能会跟不上IO的工作,或者没有足够的内存应付所有的访问?要分开现有的数据又非常难。明智的办法是开始时就使用分开的数据库,并且进行有效的数据库管理。 如果你有一个卖书的网站,你可能有作者的列表,书价的列表,还有当前的库存和订单的列表。当你的业务不断增长时,订单将会不断地增长,而且处理每个订单都需要进行很多的磁盘访问。很可能你将在某一天将所有的订单都放到一个会计系统中。

  现在就将订单放到一个独立的数据库吧。由于库存也是通过订单更新的,因此库存量也放到同样的数据库中。

  作者的列表和书的列表都是一些静态的信息,要经常读取,但很少更新。实际上,更新一个作者的记录可能只需要每5年一次,只在作者写了一本新书(或者去世)时进行。放这些数据的服务器的配置可与放订单数据库的服务器完全不同。

包含PHPLIB

  PHPLIB通过一个称为DB_Sql的类访问SQL数据库。根据你需要使用的数据库类型,将不同的inc文件包含在你的代码中。在这个例子中,我使用MySQL的版本。

  为了在你的代码中使用DB_Sql,要将PHPLIB文件安装在它们自己的目录中。然后,找到你的cgi-bin目录,并且在cgi-bin的目录旁创建phplib目录。下一步,拷贝所有的PHPLIB .inc文件到phplib目录。最后,修改php.inc文件,只要将“include_path=”的行改为该phplib目录就可以了。

include_path是PHP使用include()或者require()时查找的目录,在我的NT workstation中,include的路径是:

include_path = ".;i:/project52/includes;i:/project52/phplib";

在Linux的系统上

include_path = ".;/home/httpd/includes;/home/httpd/phplib";

在每个PHP页面的顶部加入
require(common.php);
?>
common.php3放在includes目录中,包含了每个页面要用到的所有数据和函数。在这个例子中的common.php是:
require(db_mysql.inc);
require(ct_sql.inc);
require(session.inc);
require(auth.inc);
require(perm.inc);
require(user.inc);
require(page.inc);
?>

  如果你想知道每个inc文件的用处,可阅读http://phplib.netuse.de上的PHPLIB文档。Db_mysql.inc包含了所有DB_SQL类的定义。如果你想使用PostGreSQL代替MySQL,只要用db_pgsql.inc代替db_mysql.inc就可以了。还有10个其它的.inc文件,可以使用MS SQL、Oracle、Sybase或者其它的数据库。

  要注意的是,在这个例子中,require()和include()是完全一样的。不过,如果放在代码中,或者在if语句中使用时,Require()和include的使用是完全不同的,并且有不同的运行结果。

扩展PHPLIB

  PHPLIB通过一个DB_Sql类产生的对象来访问数据库。Db_mysql.inc包含了为MySQL修改过的DB_Sql类。我们将通过在common.php中加入代码来扩展DB_sql,这些代码将加在包含db_mysql.inc的行后。

DB_Sql包含了很多用作查询的函数,我们要作修改的是:

/* public: 连接管理 */
function connect($Database = "", $Host = "", $User = "", $Password = "") {
/* 处理默认连接 */
if ("" == $Database)
$Database = $this->Database;
if ("" == $Host)
$Host = $this->Host;
if ("" == $User)
$User = $this->User;
if ("" == $Password)
$Password = $this->Password;

/* 建立连接,选择数据库 */
if ( 0 == $this->Link_ID ) {
$this->Link_ID=mysql_pconnect($Host, $User, $Password);
if (!$this->Link_ID) {
$this->halt("pconnect($Host, $User, $Password) failed.");
return 0;
}
if (Link_ID">!@mysql_select_db($Database,$this->Link_ID)) {
$this->halt("cannot use database ".$this->Database);
return 0;
}
}

return $this->Link_ID;
}
?>

  在你的db_mysql.inc(或者其它数据库的相关.inc文件)中找到connect()函数,然后将它拷贝到common.php,放到包含db_mysql.inc代码的后面,在后面,还要将它封装为一个类的定义。

我发现这些代码有些难读,因此,首先令拷贝来的代码的可读性更好:

/* public: 连接管理*/
function connect($Database = "", $Host = "", $User = "", $Password = "") {
/* 处理默认连接 */
if ("" == $Database) {
$Database = $this->Database;
}
if ("" == $Host) {
$Host = $this->Host;
}
if ("" == $User) {
$User = $this->User;
}
if ("" == $Password) {
$Password = $this->Password;
}
/* 建立连接,选择数据库 */
if ( 0 == $this->Link_ID ) {
$this->Link_ID=mysql_pconnect($Host, $User, $Password);
if (!$this->Link_ID) {
$this->halt("pconnect($Host, $User, $Password) failed.");
return 0;
}
if (Link_ID">!@mysql_select_db($Database,$this->Link_ID)) {
$this->halt("cannot use database ".$this->Database);
return 0;
}
}
return $this->Link_ID;
}
?>

  我调整了一下括号的位置,并且在单行的前后也加入了一个大括号。在PHP的if语句中,如果只有一句代码的话你可以不用括号,但是,如果你增加多一行代码,就会马上出错。因此我建议你加入一个括号,以免后来加入代码时出错。

  在改变connect的代码之前,先要了解一下connect()是如何工作的,它检查当前是否存在一个连接,如果不存在连接的话,就创建一个连接。在每次的数据库查询之前,首先运行这个connect()函数。可惜的是,它只在首次连接的时候选择数据库,如果你的PHP页面使用超过一个数据库,connect()并不会选择另外的数据库。

  要改变代码的话,有几种不同的方法。我们要选择一种对PHPLIB的影响最小,而且可让我们在需要分析问题的时候,能够显示数据库连接状态的方法。我们需要在PHPLIB外保存连接id和数据库的名字。只要在common.php加入:

$db_connection = 0; // 数据库连接的id
$db_database = ""; // 当前数据库的状态
?>

  下一步,我们要对PHPLIB作修改,以便在这些变量中存储连接id和数据库的名字。在其它的代码中,你可以设置和使用同样的变量名。在分析问题时,如果你需要知道现在使用哪个数据库,只要在页面中插入以下的代码:

Print(" db_database: " . $db_database . "");
?>

我们怎样才能让connect()使用这些新变量呢?我们可以在顶部加入一行:

{
globals $db_connect, $db_database;
/* Handle defaults */
?>

通过这些代码,新变量就可被connect()访问到

在定义了$db_database后,加入:
function db_connect($db_connect_host="", $db_connect_user="",$db_connect_pass="") {
globals $db_connect;
if(!empty($db_connect_host)) {
$db_connect = mysql_pconnect($db_connect_host,
$db_connect_user, $db_connect_pass);
}
return($db_connect);
}
function db_database($db_database_new="") {
globals $db_database;
if(!empty($db_database_new)) {
$db_database = @mysql_select_db($db_database_new, db_connect());
}
return($db_database);
}
?>

  只要定义这些公共的函数一次,你就可以在不同的地方使用这些公共的变量,而不需要加入global申明。以下就是使用上面db函数的公共函数:

function connect($Database = "", $Host = "", $User = "", $Password = "") {
/* 处理默认连接 */
if ("" == $Database) {
$Database = $this->Database;
}
if ("" == $Host) {
$Host = $this->Host;
}
if ("" == $User) {
$User = $this->User;
}
if ("" == $Password) {
$Password = $this->Password;
}
/* 建立连接,选择数据库 */
if ( 0 == db_connect()) {
$this->Link_ID = db_connect($Host, $User, $Password);
if (!$this->Link_ID) {
$this->halt("pconnect($Host, $User, $Password) failed.");
return 0;
}
}
if (0 != db_connect()) {
if($Database != db_database()) {
$this->Database = db_database($Database))
if(empty($this->Database)) {
$this->halt("cannot use database " . $this->Database);
return 0;
}
}
}
return $this->Link_ID;
}
?>

留意以下改变:

  对数据库的测试从连接的测试中分离出来,这样即使connect()有一个当前连接时,还可以检查是否要换成另外的数据库。这意味着与以前相比,db_connect()和0作比较的次数多了一倍,

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles