PHP Tutorials. Database connection (1) _php

Source: Internet
Author: User
Keywords connection database tutorials information one form use file can P
Tags php3 file how to use sql
Midfield one: Database connection

The first two chapters focus on the PHP language, and now stop to start creating an application. In this chapter, you will create an application that connects to the MySQL database.

After studying the previous two chapters, you must have learned how to handle PHP internal data and how to write statements and functions. The next step logically, should be to learn how to use SQL (Structured query statements) to process the external data of PHP. However, before we begin to learn this part, let's briefly break the fundamentals of learning and relax.
Let me take you through the development process of PHP applications. In a literal sense, each application should be unique, but each application can be built on the basis of previous work, a series of common functions. I propose to mix the two technologies together. blindly using previously written functions will deprive the program of new features, and will prevent the modification of the old function to improve the efficiency of the function. On the other hand, the use of existing functions means that applications can be developed faster. So you have to grasp yourself in these two extremes to be a good programmer.

Note: If you are still unfamiliar with HTML, now is the time to start learning. This book assumes that you are already familiar with HTML. If you are unfamiliar with HTML forms and forms, you will soon get confused.

5.1 Beginnings
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 are installing PHP in accordance with the instructions in chapter one, the root directory of the Web server should be/usr/local/apache/htdocs. Next, we will create a file named Menu.php3 that contains a background management task menu, as shown in Listing 5.1.

List 5.1 menu.php3


Administrative Menu



    1. creat Database
      Connection




Contains definitions for functions Affy_header and Affy_footer in the file common.inc. These functions will also appear later in this chapter.
5.2 Creating a connection
When you click the CREATE database connect join, the Connect.php3 file is executed and the file tries to connect to the MySQL database server installed in the second chapter of learning.
Listing 5.2 shows that the connect.php3 file attempts to connect to the database using the user name codebits and password codebits because the user name was not created when MySQL was installed, so the connection must fail. But failure--at least in this case--is a good thing, because we can see how we should deal with the problem. Figure 5.1 shows the error message and form that will be displayed when the connection fails.

List 5.2 connect.php3

Page 107-108 Listing 5.2


Page 108 Figure 5.1

Figure 5.1 Error message display when a connection fails

When the database connection fails, the program gives an error message and a form in which the user can enter the root user's password. As explained later in this chapter, you can create a user named Codebits with the root password. Now skip the section on the $arr_request array first.
When the function mysql_connect is called and the connection fails, the function typically displays the following information:

Warnint:mysql Connection Failed:access denied
For user: ' Codebits@localhost ' (Using password:yes)

The vast majority of applications require precise control over what is displayed, especially in highly graphical applications. Adding the (@) symbol before the function mysql_connect will suppress the display of the error message.
Note the Action property of the form statement specifies that the connect.php3 file will be executed when the Submit button is clicked. This is an example of a recursive program, which means that PHP files are allowed to call itself.
By applying recursive programming techniques, you can compile all the code for the same topic in the same file. As for when to combine functions into a single file, or to break up a program into several files, this is based on experience. My first principle is to create a separate file when implementing a specific function that is programmed with more than 100 lines of code.

5.3 Getting HTML form information
Even if you enter a password and click Connect to the database, the connection will still fail because CONNECT.PHP3 has not used the input values 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. The form information can be accessed through $http_post_vars[' username ' and $http_post_vars[' password '] in this program.
Using $http_post_vars[' password '] to get the information in the form looks simple. But there are still some hidden problems. First, check that the name of the form field (password in this example) is uppercase, lowercase, or case-sensitive.
The second question contains nothing to do with this example. In addition to form methods, you can use URLs to run PHP scripts, such as:

Http://.../connect.php3?username=root&password=password

You can see that the user name and password are passed through the URL, question mark "? "Marks the beginning of the domain information," & "is the delimiter of the domain. Fortunately, the PHP engine also automatically parses the URL line and stores the result in 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 Arrays $HTTP _post_vars.
To deal with these (or some other) problems, my solution is to create an array named $arr_request that gets initialized information from two $http arrays. The following encoding lines can be used in common.inc for numeric initialization of array $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 is vonverted
To lower-case.
If (Count ($HTTP _get-vars)) {
while (list ($key, $value) = each ($HTTP _get_vars)) {
$arr _request[strtolower ($key)] = $value;
}
}
if (count ($HTTP _post_vars)) {
while (list ($key, $value) = each ($HTTP _post_vars)) {
$arr _request[strtolower ($key)] = $value;
}
}

If you have a common.inc file in all of your PHP scripts, don't worry about how the script works. All the information passed in is kept in lowercase in the array $arr_request, which means that user name information can be obtained using $arr_request[' username '.
PHP provides an alternative to arrays $http_get_vars and Arrays $http_post_vars, and HTML forms and URL-based information can be accessed directly as PHP variables. For example, in a PHP script, one is defined as The domain information can be accessed directly in the PHP program with $last_name, the same URL-based information, for example, Http://www.site.com?last_name=join, can be obtained by $last_name. However, I prefer to use array $arr_request because this is useful for all the information that you want to loop through to the program. If the information is a scalar, it is not intended to be used for recycling. For example: change all parameter names to uppercase to ensure that the program is not broken because of the use of the SHIFT key, or you will need to display all of the input parameters in case of error detection.

Note: This section provides a simple introduction to the CGI (Common Gateway Interface) protocol, and more details can be found in Appendix A of this book, "Internet Resources".

5.4 Using HTML form information
Since it is easy to access the form information from a PHP script, it is time to connect to the database using this information. The first step is to check the code that connects the database:

$id _link = @mysql_connect (' localhost ', ' affy ', ' affy ');

In this line of code, both the user name and password are string values. To make use of the information in the form, this line of code needs to be changed to replace the value with a variable:

$id _link = @mysql_connect (
' localhost ',
$username,
$password);

Now that the variable is used, the variable must be initialized. The following code will perform 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 will be greater than 1, so that the IF statement executes the clause of the true condition, which in turn removes the user name and password information from the $arr_request array.
When no form information exists, the user name and password can still be initialized with a string value.
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 username and password domains? If so, the above code will fail. By examining the form fields directly rather than relying solely on the number of elements of the $arr_request array, this code can be made 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 will return an empty string for an array element that is not initialized, the above code will be more resilient. Using scalars can make your code easier to understand and more efficient in some ways than using arrays. If either of these variables has a null, this means that the form does not provide any values and will use the default values.
Listing 5.3 shows the Connect.php3 file with the above changes, which can be seen in the context of the two changes described.

Checklist 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 will be established successfully.


Page 113, Figure 5.2

Figure 5.2 confirms the successful establishment of a database connection

5.5 Common.inc File
Listing 5.4 shows the version of the Common.inc file that is required in this chapter.

Listing 5.4 common.inc--A set of routines used by multiple applications.
function Affy_footer () {
Echo '';
}

function Affy_header ($title) {
Echo ' <title>'; <br>echo "$title"; <br>echo '</title>';
}

function Affy_message ($msg) {
Echo '

'; Echo ' '; Echo '
';
echo "$msg";
Echo '
';
}
?>

5.6 Summary
This chapter describes how to connect to a database using PHP, and the first step is to create a web menu page that runs a script that connects to the database and then creates a connect.php3 file that can connect to the database.
The Connect.php3 file failed when attempting to connect to the database using the Affy user name, resulting in a form that required a root user password.
The information in the form is placed in the $arr_request array through the Common.inc file. The Connect.php3 file is modified to use the user name and password in the variable $arr_request to connect to the database.
  • 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.