PHPLIB and multi-database connection _ MySQL

Source: Internet
Author: User
Tags odbc connection pconnect
You may have a website where some pages need to process databases. You may want to use PHPLIB, but do not want to change the existing database to adapt to it. Here is the answer to your dream. PHPLIB and multiple databases. To implement it, you need to expand PHPLIB. This article explains how to create an extension. You will find that this article will help you expand your PHPLIB in other ways. you may have a site where some pages need to process databases. You may want to use PHPLIB, but do not want to change the existing database to adapt to it. Here is the answer to your dream. PHPLIB and multiple databases.

To implement it, you need to expand PHPLIB. This article explains how to create an extension. You will find that this article will help you expand PHPLIB in other aspects. After reading this article, let's take a look at how PHPLIB can complete 98% of what you want.

The PHPLIB expansion suggestions mentioned in this article have been submitted to the PHPLIB development team. Therefore, these extensions may appear in future versions. Other code on your webpage will help you organize your database management.

Database management

You can place each table in a huge database. However, it will hurt you one day. Database management can minimize the trauma. What happens when your database is too large for a server? What if a server cannot process I/O throughput or does not have enough memory for processing? It is difficult to split the existing database, but it is much easier to split the database from the beginning, and good database management will be very helpful.

If you operate a bookstore, you may have a list of authors, a list of bibliography with price, the current inventory list, and an order list. As your business grows, the order list will increase and each order will occupy a lot of disk space. One possibility is that one day you will put orders directly into the financial system.

Now, place the order in a separate database. Because the inventory quantity changes with the order, the inventory data is stored in the same database.

The author list and bibliography list are static information that is frequently read but rarely changed. In fact, the only change may be that the author's record is recorded every five years. This may be when the author writes a new book (or dies ). The data may use a different configuration from the order database.

Including PHPLIB

PHPLIB uses a class named DB_ SQL to operate the SQL database. Include the appropriate version of your database in your code. In this example, I use MySQL.

To get DB_ SQL in your code, install the PHPLIB file in the directory required by PHPLIB. Then, find your cgi-bin directory and create the phplib directory under the cgi-bin directory. Copy all the. inc files in PHPLIB to the phplib directory. Finally, put the phplib directory on the line where export de_path = in the php. ini file.

Include_path is the place where PHP references the file name in include () or require. On my NT Workstation, the included path is

Include_path = ".; I:/project52/includes; I:/project52/phplib ";

On a Linux machine

Include_path = ".;/home/httpd/shortdes;/home/httpd/phplib ";

At the top of each PHP page




Require (common. php3 );



?>



The common. php3 directory contains all the data and functions that are common to each page. In common. php3


Require (db_mysql.inc );

Require (ct_ SQL .inc );

Require (session. inc );

Require (auth. inc );

Require (perm. inc );

Require (user. inc );

Require (page. inc );



?>



Read the PHPLIB documentation (http://phplib.netuse.de) and find some good articles in the http://www.phpbuilder.com to learn what you need to include. Db_mysql.inc contains the definition of the DB_ SQL class. If you want to change MySQL to a PostGreSQL database, change db_mysql.inc to include db_pgsql.inc. There are 10. inc files covering ms SQL, Oracle, Sybase and other databases.

In this example, require () and include () are identical. Require () and include () work in different ways. when used in the middle of the code or in the if () statement, the results are different.

Expand PHPLIB

PHPLIB processes the database through an object created from the DB_ SQL class. Db_mysql.inc contains the DB_ SQL class, which is modified for MySQL. We will add code to common. php3 to expand DB_ SQL, following the rows containing db_mysql.inc.

DB_ SQL contains many query functions. One thing we want to change is:


/* Public: connection management */

Function connect ($ Database = "", $ Host = "", $ User = "", $ Password = ""){

/* Default processing */

If ("" = $ Database)

$ Database = $ this-> Database;

If ("" = $ Host)

$ Host = $ this-> Host;

If ("" = $ User)

$ User = $ this-> User;

If ("" = $ Password)

$ Password = $ this-> Password;



/* Create a connection and select a 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 connnect () function in your db_mysql.inc (or the. inc file for your database), copy it to common. php3, somewhere after db_mysql.inc is included. You should encapsulate it in the class definition, as described at the end of this article.

I found that the code is hard to understand. Therefore, the first thing to do is to make the copied code readable:


/* Public: connection management */

Function connect ($ Database = "", $ Host = "", $ User = "", $ Password = ""){

/* Default processing */

If ("" = $ Database ){

$ Database = $ this-> Database;

}

If ("" = $ Host ){

$ Host = $ this-> Host;

}

If ("" = $ User ){

$ User = $ this-> User;

}

If ("" = $ Password ){

$ Password = $ this-> Password;

}

/* Create a connection and select a 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 sort the code in a near-order manner. in this way, for the included code, hierarchies allow me to match parentheses. This avoids errors caused by the loss of parentheses. I also added brackets for separate rows. PHP allows you not to use parentheses when the if statement is followed by a single line of code. Once you have added additional code, this abbreviation fails. We recommend that you always add parentheses to avoid errors when adding code later.


Now it is time to modify the connect code. Note how the connect () code detects the existence of a connection and creates a connection when the connection does not exist. This connect () function is called before each database query. Unfortunately, the database is selected only once when a connection is created. If the PHP page uses more than one database, the connect () code will not see database changes.

You can modify the code in several ways. We are looking for ways to minimize the impact on PHPLIB, and we can display the status of the active database when we need to diagnose a problem. The two variables that need to exceed PHPLIB are the connection id and database name. Therefore, make these two variables externally visible to PHPLIB. In common. php3:


$ Db_connection = 0; // normal Database Connection id

$ Db_database = ""; // Current database name

?>


Next, modify PHPLIB to save the connection id and database name in these fields. You can set and use the same field for other codes. If you need to know which database is in use when diagnosing the problem, insert the code in your page:


Print ("

Db_database: ". $ db_database ."

");

?>

(There are some more concise methods to write print statements. This method can highlight the variable name in the color code editor. This method also works stably for the array and other compound variable names .)

How can we make connect () use new variables? We can add additional lines to the item department, so you can:


{

Globals $ db_connect, $ db_database;

/* Default processing */



?>

This exercise is valid in connect.

The following are more traditional methods. Add the following directly after $ 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 );

}



?>


By defining these common functions once, you can get common variables in various places without adding global rows in all places. Here we use the general functions of our db functions:


Function connect ($ Database = "", $ Host = "", $ User = "", $ Password = ""){

/* Default processing */

If ("" = $ Database ){

$ Database = $ this-> Database;

}

If ("" = $ Host ){

$ Host = $ this-> Host;

}

If ("" = $ User ){

$ User = $ this-> User;

}

If ("" = $ Password ){

$ Password = $ this-> Password;

}

/* Create a connection and select a 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;

}



?>


Note the following changes:



The database test is outside the connection test so that connect () can detect a new database, or even when a current connection already exists. That is to say, we compare db_connect () with 0 twice. This result is worth making some minor changes.



We put the database connection and database selection out of PHPLIB, so that we can use the same function where the database needs to be selected in the code.



In this case, there is only one bad thing: we assume that the same host, user, and password are used for all database operations. If you use a user to log on and use special permissions to process the specified database, you will have to create a special connection for the processing. What should we do? Define variables:






$ Db_host = "";

$ Db_user = "";

$ Db_pass = "";



?>



Expand the db_database () function to compare the current user and host name with the special user and host name. You can also add:






$ Db_type = "";



?>



Then use it to save the database type, MySQL, Oracle, and so on, so that you can process multiple databases.



It is more complicated to modify the code so that you can process multiple databases. You need to modify the query function, including the connection and selection function. You may want to read about the ODBC Connection in PHP and use the ODBC option in PHPLIB. ODBC can process many databases in a common way, but it may be slow. ODBC allows you to use the same code on multiple types of databases. If you use multiple database types, you may encounter different data format requirements and differences between different databases. ODBC simplifies the connection, but does not improve the database interpretation methods for data and SQL.



Now we will start a short tutorial on the derived object classes. The connect () function is encapsulated in the class definition:






Class DB_ SQL {



}



?>



When we copy this function to common. php3, we need to derive the DB_ SQL class. We implement the following by encapsulating connect:






Class db_DB_ SQL extends DB_ SQL {



}



?>



For more information about objects and classes in PHP, see what "extends" has done. In the least sense, everything defined in the derivation replaces or overwrites the original definition.



You can now use db_DB_ SQL. When you install PHPLIB, you will have a statement written:






$ X = new DB_ SQL;



?>



Change it:






$ X = new db_DB_ SQL;



?>



In this way, the modified class is used instead of the original class.



Now you have become an object, class, and OOP expert. you can ask for an annual salary of 100. (Foreigners are brave enough)



We have made an effective modification and have the least impact on the PHPLIB code. Record the modification trace so that you can reuse it in the new version of PHPLIB. If an error occurs during database processing, you can insert a print statement in an external function to see what happens during the connection. Now you can do more things without modifying the PHPLIB code.



If the SQL seems to have failed, you can copy the qurey () function from DB_ SQL in db_mysql.inc to db_DB_ SQL in common. PHP3, and insert the print statement to view the SQL usage.



PHPLIB records cookies. An print statement in the middle of PHPLIB may produce an error message, which is about the output of HTTP header information. You can ignore errors or write diagnostic information to a disk file.



Start:



$ Db_log_file = "t:/diag.txt ";



Or similar statement, used to point to a file somewhere on the disk. In Windows, be sure to use an existing directory. Otherwise, you will get a strange error.

Definition:


Function db_log ($ db_log_message ){

Globals $ db_log_file;

$ Db_log_f = fopen ($ db_log_file, "");

Fwrite ($ db_log_f, date ("Y m d H: I: s"). "". $ db_log_message. "rn ");

Fclose ($ db_log_f );

}



?>

You need to check what happened at any time, such as adding log information:


Db_log ("current database:". db_database ());

?>

You can use some built-in logging technologies and system logs. When using system logs, you may need to search a large number of files, but only a little bit of information, because the directory is not properly processed. This separation log can provide you with some control during the test process. We recommend that you add logs before and after the operation, such:


Db_log ("current database:". db_database ());

Db_database ("bookcatalogue ");

Db_log ("current database:". db_database ());

?>

Remember to use the correct database in your database processing so that you do not need to query the PHPLIB database. You may like to create an encapsulation function for a database function or modify the function you are using. If you use mysql_query (), you can use db_database () first (). You can also replace:


Db_database ("bookcatalogue ");

$ Result = mysql_query ("select * from? ", Db_connect ());



?>

Cheng


$ Result = mysql_db_query (db_database ("bookcatalogue"), "select * from? ",

Db_connect ());



?>

Recommended functions:



Function db_query ($ db_query_database, $ db_query_ SQL ){

Return (mysql_db_query (db_database ($ db_query_database), $ db_query_ SQL,

Db_connect ());

}



?>

Now you can implement

Use PHPLIB (and any similar software) to process multiple databases

Extended Class/object

Insert diagnosis check

Write log information to a file

Practice them in reverse order. After the log file can work, it is followed by a diagnosis check, a class extension, and then multiple databases.

Author: Peter Moulding
Source: code lab

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.