Phplib access to multiple databases

Source: Internet
Author: User
Tags empty extend functions connect odbc mysql variables system log
Access | data | database

"Summary" If you want to use more than one database, it seems to be powerless, this article describes the expansion of phplib, so that you have the cake and eat, while using Phplib can use multiple databases, and from which you can also learn about object-oriented programming and how to expand the library knowledge.
Phplib is PHP's some extensions, using it we can easily do a variety of database operations, but if you want to use more than one database, it appears to be powerless, this article describes the expansion of the phplib, so that you have the fish and bear cake, You can use multiple databases while using Phplib, and you can also learn about object-oriented programming and how to extend the library's knowledge, which is worth reading.

Database management

You can put any table in a large database. But for a long time, the database will become larger, the server may not be able to keep up with IO work, or not enough memory to meet all the access? It's very difficult to separate existing data. It is advisable to start with a separate database and to manage the database effectively. If you have a book-selling website, you may have a list of authors, a list of book prices, and a list of current inventory and orders. As your business grows, orders will grow, and many disk accesses are required to process each order. It is likely that one day you will put all your orders in an accounting system.

Now put the order in a separate database. Because inventory is also updated by order, inventory is also placed in the same database.

The list of authors and lists of books are static information that is often read, but rarely updated. In fact, updating an author's record may only take place once every 5 years, only when the author writes a new book (or dies). The configuration of the server where the data is placed can be completely different from the server placing the order database.

Contains Phplib

Phplib accesses the SQL database through a class called Db_sql. Depending on the type of database you need to use, include different inc files in your code. In this example, I use the version of MySQL.

To use Db_sql in your code, install the Phplib files in their own directory. Then, locate your Cgi-bin directory and create the Phplib directory next to the Cgi-bin directory. Next, copy all Phplib. inc files to the Phplib directory. Finally, to modify the Php.inc file, simply change the "include_path=" line to the Phplib directory.

Include_path is the directory that PHP looks for when using include () or require (), and in my NT Workstation, the path to include is:

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

On a Linux system

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

Join at the top of each PHP page
? Php

Require (common.php);

? >
COMMON.PHP3 is placed in the includes directory and contains all the data and functions you want to use for each page. The common.php in this example are:
? Php

Require (DB_MYSQL.INC);
Require (CT_SQL.INC);
Require (SESSION.INC);
Require (AUTH.INC);
Require (PERM.INC);
Require (USER.INC);
Require (PAGE.INC);

? >

If you want to know the usefulness of each inc file, read the Phplib documentation on Http://phplib.netuse.de. Db_mysql.inc contains the definitions for all Db_sql classes. If you want to use PostgreSQL instead of MySQL, just use db_pgsql.inc instead of db_mysql.inc. There are 10 other. inc files that can use Ms SQL, Oracle, Sybase, or other databases.

Note that in this example, the require () and include () are exactly the same. However, if placed in code, or used in an if statement, the use of Require () and include is completely different and has different running results.

Extended Phplib

Phplib access to the database through an object generated by a Db_sql class. Db_mysql.inc contains db_sql classes that have been modified for MySQL. We will extend the db_sql by adding code to the common.php, which will be added after the line containing Db_mysql.inc.

Db_sql contains a number of functions used as queries, and we want to make changes to:

? Php

/* Public: Connection Management */
Function Connect ($Database = "", $Host = "", $User = "", $Password = "") {
/* Handle DEFAULT connection * *
if ("" = $Database)
$Database = $this->database;
if ("" = $Host)
$Host = $this->host;
if ("" = $User)
$User = $this->user;
if ("" = $Password)
$Password = $this->password;

/* Establish a connection, select the database * *

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 (! @mysql_select_db ($Database, $this->link_id)) {
$this->halt ("Cannot use database" $this->database);
return 0;
}
}

return $this->link_id;
}

? >

Find the Connect () function in your db_mysql.inc (or other database related. inc files) and copy it to common.php, put it behind the Db_mysql.inc code, and encapsulate it as a class definition.

I find this code a little bit hard to read, so it makes the copied code more readable first:

? Php

/* Public: Connection Management */

Function Connect ($Database = "", $Host = "", $User = "", $Password = "") {
/* Handle DEFAULT connection * *
if ("" = $Database) {
$Database = $this->database;
}
if ("" = $Host) {
$Host = $this->host;
}
if ("" = $User) {
$User = $this->user;
}
if ("" = $Password) {
$Password = $this->password;
}
/* Establish a connection, select the database * *
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 (! @mysql_select_db ($Database, $this->link_id)) {
$this->halt ("Cannot use database" $this->database);
return 0;
}
}
return $this->link_id;
}

? >

I adjusted the brackets and added a brace around the line. In the IF statement in PHP, if there is only one code, you can use the parentheses, but if you add more lines of code, you'll get a quick error. So I suggest you add a bracket to avoid an error when you add the code later.

Before changing the code for connect, you need to know how connect () works, check if there is a connection, and create a connection if there is no connection. Before each database query, run the Connect () function first. Unfortunately, it only selects the database at the first connection, and if your PHP page uses more than one database, connect () does not choose another database.

There are several different ways to change the code. We want to choose a minimal impact on phplib and allow us to display the database connection state when we need to analyze the problem. We need to save the connection ID and the name of the database outside the Phplib. Just add in common.php:

? Php

$db _connection = 0; ID of the database connection
$db _database = ""; Status of the current database

? >

Next, we will modify the Phplib to store the connection ID and the name of the database in these variables. In other code, you can set and use the same variable name. When analyzing a problem, if you need to know which database to use now, just insert the following code into the page:

? Php

Print ("

Db_database: ". $db _database. "

");

? >

How can we get connect () to use these new variables? We can join a line at the top:

? Php

{
Globals $db _connect, $db _database;
/* Handle Defaults * *

? >

With this code, the new variable can be accessed by connect () to

After defining the $db_database, add:
? Php

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);
}

? >

Once you have defined these public functions once, you can use these public variables in different places without having to join the global declaration. Here is a common function that uses the DB function above:

? Php

Function Connect ($Database = "", $Host = "", $User = "", $Password = "") {
/* Handle DEFAULT connection * *
if ("" = $Database) {
$Database = $this->database;
}
if ("" = $Host) {
$Host = $this->host;
}
if ("" = $User) {
$User = $this->user;
}
if ("" = $Password) {
$Password = $this->password;
}
/* Establish a connection, select the database * *
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;
}

? >

Notice the following changes:

The test of the database is detached from the test of the connection, so that even if connect () has a current connection, you can check whether you want to replace it with another database. This means that Db_connect () and 0 compare more times than before, but this extra processing is necessary.

We put the database connection and database selection outside of Phplib, so you can use the same database selection function anywhere in the PHP code.

However, there is a limit to the processing now, and here we assume that the same host, user, and password are used for all databases. If your database has different permissions for different users, you must create a special connection to access it. What do you do? As long as you define the following variables:

? Php

$db _host = "";
$db _user = "";
$db _pass = "";

? >

By extending the Db_database () function, you can compare the current user and host to a user and host. You can also join:

? Php

$db _type = "";

? >

This variable is used to store the type of database, MySQL, or Oracle. This allows you to access multiple databases.

However, it is quite complicated to change the code to handle multiple different types of databases. You must also change the query function, as well as the connection and selection functions. You may be able to connect through PHP ODBC and then use the Phplib ODBC option to handle it. ODBC handles multiple databases in a common way, so it will be a bit slower. ODBC allows you to use the same code to handle several different types of databases. But when you need a date with different processing formats, there will be problems, and there will be some strange differences between the databases. ODBC simply simplifies the connection, but does not modify the way the database interprets data and SQL.

Now let's learn how to redefine an object class. The Connect () function is encapsulated in the definition of a class:
? Php

Class Db_sql {

}

? >

When we copy the function to common.php, we have to redefine the Db_sql class so we can encapsulate connect ():
? Php

Class Db_db_sql extends Db_sql {

}

? >

To learn more about the work of "extends," we can look at the parts of the PHP documentation about objects and classes. Simply put: Any definition of the extension part replaces and overrides all previous definitions.

You can now use Db_db_sql. When you configure Phplib, you should make the following statement:

? Php

$x = new Db_sql;

? > Change it to: Php

$x = new Db_db_sql;

? >

You can then use the modified class instead of the previous one.

When connecting to a database, you can output the current connection state in an external function. If there is an error in the SQL statement, you can also copy the query () function in Db_sql to common. PHP db_db_sql, and then insert an output statement to see what the current SQL statement is.

You can also write error or diagnostic information to a disk file. By defining

$db _log_file = "T:/diag.txt";

or a similar text file. If you use Windows, you want to make sure that the directory exists, or you will get a wrong message.

Then define a function:

? Php

function db_LOG ($db _log_message) {
Globals $db _log_file;
$db _log_f = fopen ($db _log_file, "a");
Fwrite ($db _log_f, date ("Y m D h:i:s"). " ". $db _log_message." \ r \ n ");
Fclose ($db _log_f);
}

? >

Where you need to log the information, add the following code:

? Php

db_LOG ("Current database:".) Db_database ());

? >

In fact, you can use the built-in or system log files. But then you have to find a small piece of information in a lot of files. So this independent log file can help you with the test. I recommend that you write the following code before and after the record:

? Php

db_LOG ("Current database:".) Db_database ());
Db_database ("Bookcatalogue");
db_LOG ("Current database:".) Db_database ());

? >

In the case of data access, remember to use the correct database instead of the database defined in Phplib. You can create an encapsulated function for the database, or change the function you use. If you use mysql_query (), you can use Db_database (), you can use

? Php

$result = Mysql_db_query (Db_database ("Bookcatalogue"), "select * from?" ",
Db_connect ());

? > which suggests the function: Php

function Db_query ($db _query_database, $db _query_sql) {
Return (Mysql_db_query db_database ($db _query_database), $db _query_sql,
Db_connect ());
}

? >

To replace

? Php

Db_database ("Bookcatalogue");
$result = mysql_query ("SELECT * from"? ", Db_connect ());

? >

Now you can do it.

. Use Phplib (or similar software) to access multiple databases
. Extend Class/Object
. Insert Diagnostic Check
. creating a log file

Through this article, I believe that for how to expand a class, you also have some ideas, practice it yourself.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.