PHP tutorial. Database Connection (1)

Source: Internet
Author: User
Tags php3 file how to use sql

Introduction: This is a PHP tutorial. Database Connection (1) Details page, introduced and PHP, related knowledge, skills, experience, and some PHP source code.

Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 326957 'rolling = 'no'>

Midfield 1: Database Connection

The first two chapters focus on the PHP language. Now stop and start creating an application.Program. In this chapter, we will create an application to connect to the MySQL database.

After learning the previous two chapters, you must have learned how to process internal PHP Data and how to write statements and functions. Logically speaking, the next step is to learn how to use SQL (structured query statement) to process PHP's external data. However, before learning this part, let's temporarily stop learning the basic principles and relax.

Let me take you through the development process of PHP applications. Literally, every application should be unique, but every application can also be built on the basis of previous work, that is, a series of common functions. I suggest combining these two technologies. Blind use of previously compiled functions will deprive the program of adding new features and prevent the modification of old functions to improve function efficiency. On the other hand, using existing functions means faster application development. Therefore, you must grasp yourself in these two extremes to become a good programmer.

Note: If you are not familiar with HTML, it is time to start learning. This book assumes that you are familiar with HTML. If you are not familiar with HTML tables and forms, you will soon be confused.

Start 5.1

Whenever I start a new project, I like to start with a new empty directory. Here, let's call this directory phpbook/ch05. Of course, this directory must be in the root directory of the Web server. If you install PHP according to the instructions in Chapter 1, the root directory of the Web server should be/usr/local/Apache/htdocs. Next, we will create a file named menu. php3, which contains a background management task menu, as shown in listing 5.1.

Configuration 5.1 menu. php3

<? PHP require ('common. inc');?>

<? PHP affy_header ('administrative menu ')?>

<H1> Administrative menu

<Li> <a href = "Connect. php3"> creat Database

Connection </a> </LI>


<? PHP affy_footer ()?>

The file common. inc contains the definitions of the functions affy_header and affy_footer. These functions will appear later in this chapter.

5.2 create a connection

When you click Create Database connect to create a database connection, the connect. php3 file is executed. This file attempts to connect to the MySQL database server installed in Chapter 2.

Listing 5.2 shows that the connect. php3 file uses the username codebits and password codebits to connect to the database. Because this username is not created during MySQL installation, the connection will certainly fail. However, failure-at least in this example-is a good thing, because we can look at how to solve this problem. Figure 5.1 shows the error message and form displayed when the connection fails.

Configuration 5.2 connect. php3

Page 107-108 listing 5.2

Page 108 figure 5.1

Figure 5.1 error message displayed when connection fails

When the database connection fails, the program will provide an error message and a form in which the user can enter the password of the root user. As described later in this chapter, with the root password, you can create a user named codebits. Skip the section about the $ arr_request array first.

When the mysql_connect function is called and the connection fails, the function usually displays the following information:

Warnint: MySQL Connection Failed: Access Denied

For User: 'codebits @ localhost' (using password: Yes)

Most applications require precise control of displayed content, especially highly graphical applications. Adding the (@) symbol before the function mysql_connect will suppress the display of error messages.

Note that when you click the submit button in the Action attribute of a form statement, the connect. php3 file is executed. This is an example of a recursive program, that is, to allow the PHP file to call itself.

Apply recursive programming technologyCodeCompiled in the same file. It depends on experience to combine functions into a file or program into several files. My first principle is: when the program code compiled by implementing a specific function exceeds 100 lines, it is necessary to create an independent file.

5.3 obtain HTML form information

Even if you enter a password and click Connect to the database, the connection still fails because CONNECT. php3 has not used the input value in the form to establish a database connection.

The PHP engine places each form field in an array called $ http_post_vars. In the example given above, the array has two elements: username and password. In this program, you can use $ http_post_vars ['username'] and $ http_post_vars ['Password'] to access the form information.

Using $ http_post_vars ['Password'] to obtain information in the form looks simple. But there are still some hidden problems. First, check whether the form field name (password in this example) is in uppercase, lowercase, or upper case.

The content of the second question is not relevant to this example. In addition to the form method, you can also use URLs to run php scripts, such:

Http: //.../connect. php3? Username = root & Password = Password

We can see that the user name and password are passed through the URL, and the question mark "?" It indicates the beginning of the domain information, and "&" indicates the domain identifier. Fortunately, the PHP engine automatically analyzes URL rows and saves the results to the $ http_get_vars array.

The problem (if you think it is) is that the program can get information from more than one place -- array $ http_get_vars and array $ http_post_vars.

To deal with these (or other) problems, my solution is to create an array named $ arr_request, which obtains initialization information from two $ HTTP arrays. In common. Inc, you can use the following encoding line to initialize the value of $ arr_repuest.

// Declare the request array which holds both

// URL-based (get) and form-based (post) parameters.

$ Arr_request = array ();

// move the URL and form parameters into the
// request array. form parameters supercede URL
// parameters. additionally, all keys are vonverted
// to lower-case.
If (count ($ HTTP_GET-VARS) {
while (List ($ key, $ value) = each ($ http_get_vars )) {
$ arr_request [strtolower ($ key)] = $ value;

}< br>
If (count ($ http_post_vars )) {
while (List ($ key, $ value) = each ($ http_post_vars) {
$ arr_request [strtolower ($ key)] = $ value;


If all PHP scripts contain the common. inc file, you don't have to worry about how the script runs. All information transmitted in the past is saved in the array $ arr_request in lower case, which means you can use $ arr_request ['username'] to obtain the username information.

PHP provides an alternative to arrays $ http_get_vars and arrays $ http_post_vars. html forms and URL-based information can be accessed directly as PHP variables. For example, in a PHP script, a domain defined as <input type = "input" name = "last_name"> can be accessed directly using $ last_name in a PHP program, the same URL-based information, for example, Last_name = join, which can be obtained by $ last_name. However, I prefer to use the array $ arr_request, because it is very useful for all the information to be passed to the program cyclically. If the information is a scalar, it is not suitable for recycling. For example, change the names of all parameters to uppercase to ensure that the program is not destroyed by the shift key. Or, during error detection, all input parameters must be displayed.

Note: This section only gives a brief introduction to the CGI (Universal Gateway Interface) protocol. For more information, see Appendix A of this book, "Internet resources.

5.4 use HTML form information

Since form information can be easily accessed from the PHP script program, it is time to connect to the database using this information. The first step is to check the database connection code:

$ Id_link = @ mysql_connect ('localhost', 'affy', 'affy ');

In this line of code, both the user name and password are strings. In order to take advantage of the information in the form, this line of code needs to be changed, and the variable replaces the value:

$ Id_link = @ mysql_connect (

'Localhost ',

$ Username,

$ Password );

If a variable is used, the variable must be initialized. The following code executes this initialization:

If (count ($ arr_request )){

$ Username = $ arr_request ['username'];

$ Password = $ arr_request ['Password'];


Else {

$ Username = 'phpuser ';

$ Password = 'phpuser ';


When the form information is available, the result of the function count is greater than 1, so that the if statement executes the true condition clause, which extracts the username and password information from the $ arr_request array in turn.

If no form information exists, the user name and password can still be initialized using string values.

The third possibility is that a form has these two fields but no form information. What happens if the form that calls connect. php3 does not have the username and password fields? In this case, the above Code will fail. By directly checking form fields, instead of relying only on the number of elements in the $ arr_request array, this code can be stronger (that is, it can handle failures in this environment ). For example:

$ Username = $ arr_request ['username'];

$ Password = $ arr_request ['Password'];

If (empty ($ username) $ username = 'phpuser ';

If (empty ($ password) $ Password = 'phpuser ';

Because PHP returns an empty string for an array element without initialization, the above Code is more adaptable. Using scalar is easier to understand and more efficient than using arrays. If one of the two variables is null, this means that the form does not provide any value, the default value is used.

Listing 5.3 shows the connect. php3 file with the above changes. You can see the descriptions of these two changes in the context.

Listing 5.3 connect. php3 Revision

Page 112-113 listing 5.3

When the correct Root Password 5.2 is entered into the form, the database connection is established successfully.

Page 113, figure 5.2

Figure 5.2 database connection established successfully

5.5 common. inc file

Listing 5.4 shows the version of the Common. inc file required in this chapter.

Listing 5.4 common. inc-a set of routines used by multiple applications.

<? PHP

Function affy_footer (){

Echo '</body>

Function affy_header ($ title ){

Echo '<HTML>
Echo "$ title ";

Echo '</title>

Function affy_message ($ MSG ){

Echo '<Table> ';

Echo '<tr> <TD> ';

Echo "$ MSG ";

Echo '</TD> </tr> ';

Echo '</table> ';



5.6 conclusion

This chapter describes how to use PHP to connect to the database. The first step is to create a web menu page, which can be used to run the database connection script, and then create the connect. php3 file that can connect to the database.

When the connect. php3 file tries to connect to the database using the affy user name, a form requiring the root user password is displayed.

Information in the form is stored in the $ arr_request array through the common. inc file. The connect. php3 file is modified to connect to the database using the username and password in the variable $ arr_request.

"Php tutorial. Database Connection (1)" more articles

Love J2EE follow Java Michael Jackson video station JSON online tools

Http:// pageno: 13.

Related Article

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: 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.