PHP Tutorials. Database connections (1)

Source: Internet
Author: User
Tags array empty functions connect mysql new features variables how to use sql
Tutorials | data | database | Database connection midfield one: database connection

The first two chapters are focused 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, it's time to learn how to use SQL (Structured query statements) to process external data for PHP. But before we begin to learn this part, let's break the basics of learning and relax.
Let me take you through the development process of PHP applications. Each application should be unique in its literal sense, but each application can be built on the basis of previous work, a series of common functions. I propose to mix the two techniques together. Blindly using the features that have been written by predecessors will deprive you of adding new features to your program and prevent you from modifying old functions to improve the efficiency of your functions. On the other hand, using existing functions means faster development of applications. So we must grasp ourselves in these two extremes in order to become a good programmer.

Note: If you're not familiar with HTML now, it's time to start learning. This book assumes you are already familiar with HTML. If you're not familiar with HTML forms and forms, you'll soon get confused.

5.1 Beginning
Whenever I start a new project, I like to start with a new empty directory. Here, let's refer to this directory as 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 the first chapter, then the Web server's root directory should be/usr/local/apache/htdocs. Next, we'll create a file called Menu.php3 that contains a menu of background management tasks, as shown in Listing 5.1.

List 5.1 menu.php3
<?php require (' common.inc ');?>
<?php Affy_header (' Administrative Menu ')?>
<ol>
<li><a href= "Connect.php3" >creat Database
Connection</a></li>
</ol>
<?php Affy_footer ()?>

Contains definitions of 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, which attempts to connect to the MySQL database server installed in chapter II learning.
Listing 5.2 shows that the Connect.php3 file uses username codebits and password codebits to attempt a database connection because the user name was not created when MySQL was installed, so the connection must have failed. But failure--at least in this case--is a good thing, because we can see how to deal with this problem. Figure 5.1 shows the error messages and forms 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 connection fails

When a database connection fails, the program gives an error message and a form in which the user can enter the password for the root user. As I said later in this chapter, with the root password, you can create a user named Codebits. Now skip over the section on the $arr_request array.
When a function mysql_connect is invoked and the connection fails, the function usually displays the following message:

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 suppresses 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 that allows PHP files to invoke itself.
Using recursive programming techniques, you can compile all the code about the same topic in the same file. It's a matter of experience when you should combine functions into a single file, or break a program into several files. My first rule is to create a separate file when the program code that implements a particular feature is more than 100 lines.

5.3 Getting HTML form information
Even if you enter a password and click Connect to the database, the connection still fails because CONNECT.PHP3 has not yet used the input values in the form to establish a database connection.
The PHP engine places each form field in a single array called $http_post_vars. In the example given above, the array has two elements: username and password. 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 simpler. But there are still some hidden problems. First, check the name of the form field (password in this example) in uppercase, lowercase, or case.
The second question does not relate to this case. In addition to the form method, you can use a URL to run a PHP script, such as:

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

As you can see, the username and password are passed through the URL, the question mark "? "Marks the beginning of the domain information, and" & "is the delimiter of the domain. Fortunately, the PHP engine also automatically analyzes the URL rows and stores the results 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.
My solution to these (or some other) problems is to create an array called $arr_request, which obtains initialized information from two $http arrays. In Common.inc, the following encoded rows can be initialized numerically using the 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 are vonverted
To lower-case.
If (Count ($HTTP _get-vars)) {
while (the list ($key, $value) = each ($HTTP _get_vars)) {
$arr _request[strtolower ($key)] = $value;
}
}
if (count ($HTTP _post_vars)) {
while (the list ($key, $value) = each ($HTTP _post_vars)) {
$arr _request[strtolower ($key)] = $value;
}
}

If you have common.inc files in all of your PHP scripts, you don't have to worry about how the script works. All passing messages are stored in lowercase in the array $arr_request, which means that you can use $arr_request[' username ' to get the username information.
PHP provides an alternative to array $http_get_vars and arrays of $http_post_vars, and HTML forms and URL based information can be accessed directly as PHP variables. For example, in a PHP script, a domain information defined as <input type = "Input" name= "last_name" can be accessed directly in a PHP program using $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 looping through all the information passed to the program. If the information is a scalar, then it is not appropriate to be used for recycling. For example, change all parameter names to uppercase to ensure that the program is not destroyed because the SHIFT key is used, or that all input parameters need to be displayed when error detection.

Note: This section contains only a brief description of the CGI (Common Gateway Interface) protocol, as described in Appendix A of this book, Internet resources.

5.4 Using HTML form information
Now that you can easily access form information from a PHP script, it's time to use that information to connect to the database. 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 username 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 you have used a variable, you must initialize the variable. The following code performs 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, which causes the IF statement to execute the clause of the true condition, which in turn extracts 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 string values.
The third possibility is that a form has both fields but no form information. What happens if the form that calls CONNECT.PHP3 has no username and password fields? If so, the above code will fail. By checking the form field directly, rather than relying on the number of elements that depend on the $arr_request array, you can make the code 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 that is not initialized, the above code will be more adaptable. Using a scalar to make your code easier to understand and more efficient in some ways than using an array. If one of these two variables is empty, this means that the form does not provide any value and the default value is used.
Listing 5.3 shows the Connect.php3 file with the above changes, and you can see the descriptions of these two changes in the context.

List 5.3 Connect.php3 revision

Page 112-113 Listing 5.3


When the correct root password is entered into the form as shown in Figure 5.2, the database connection will be successfully established.


Page 113, Figure 5.2

Figure 5.2 confirms that the database connection was successfully established

5.5 Common.inc File
Listing 5.4 shows the version of the Common.inc file required for 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 ' echo "$title";
Echo ' </title>}

function Affy_message ($msg) {
Echo ' <table> ';
Echo ' <tr><td> ';
echo "$msg";
Echo ' </td></tr> ';
Echo ' </table> ';
}
?>

5.6 Summary
This chapter describes how to use PHP to connect to a database, and the first step is to create a web menu page that runs a script to connect to the database, and then creates a connect.php3 file that can connect to the database.
When the Connect.php3 file attempts to connect to the database using the Affy username, it fails, causing the form to appear that requires the root password.
The information in the form is placed in the $arr_request array through the Common.inc file. and modified the connect.php3 file so that it connects to the database using the username and password in the variable $arr_request.



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