php毕业设计外文翻译

更新时间:2024-05-08 15:16:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

原文:

Getting PHP to Talk to MySQl

Now that you’re comfortable using the MySQL client tools to manipulate data in the database, you can begin using PHP to display and modify data from the database. PHP has standard functions for working with the database.First, we’re going to discuss PHP’s built-in database functions. We’ll also show you how to use the The PHP Extension and Application Repository (PEAR) database

functions that provide the ability to use the same functions to access any supported database. This type of flexibility comes from a process called abstraction. In programming interfaces, abstraction simplifies a complex interaction. It works by

removing any nonessential parts of the interaction, allowing you to concentrate on the important parts. PEAR’s DB classes are one such database interface abstraction. The information you need to log into a database is reduced to the bare minimum. This standard format allows you to interact with MySQL, as well as other databases using the same functions. Similarly, other MySQL-specific functions are replaced with generic ones that know how to talk to many databases. For example, the MySQL-specific connect function is:

mysql_connect($db_host, $db_username, $db_password); versus PEAR’s DB connect function:

$connection =

DB::connect(\);

The same basic information is present in both commands, but the PEAR function also specifies the type of databases to which to connect. You can connect to MySQL or other supported databases. We’ll discuss both connection methods in detail.

In this chapter, you’ll learn how to connect to a MySQL server fromPHP, how to use PHP to access and retrieve stored data, and how to correctly display information to the user. The Process

The basic steps of performing a query, whether using the mysql command-line tool or PHP, are the same: ? Connect to the database. ? Select the database to use. ? Build a SELECT statement. ? Perform the query. ? Display the results.

We’ll walk through each of these steps for both plain PHP and PEAR functions.

1

Resources

When connecting to a MySQL database, you will use two new resources. The first is the link identifier that holds all of the information necessary to connect to the database for an active connection. The other resource is the results resource. It contains all information required to retrieve results from an active database query’s result set. You’ll be creating and assigning both resources in this chapter. Querying the Database with PHP Functions

In this section, we introduce how to connect to a MySQL database with PHP. It’s quite simple, and we’ll begin shortly with examples, but we should talk briefly about what actually happens. When you try connecting to a MySQL database, the MySQL server authenticates you based on your username and password. PHP handles connecting

to the database for you, and it allows you to start performing queries and gathering data immediately.

As in Chapter 8, we’ll need the same pieces of information to connect to the database:

? The IP address of the database server ? The name of the database ? The username ? The password

Before moving on, make sure you can log into your database using the MySQL command-line client.

Figure 9-1 shows how the steps of the database interaction relate to the two types of resources. Building the SELECT statement happens before the third function call, but it is not shown. It’s done with plain PHP code, not a MySQL-specific PHP function.

Figure 9-1. The interaction between functions and resources when using the database

Including Database Login Details

You’re going to create a file to hold the information for logging into MySQL. Storing this information in a file you include is recommended. If you change the database password, there is only one place that you need to change it, regardless of how many

PHP files you have that access the database. You don’t have to worry about anyone directly viewing the file and getting your database login details. The file, if requested by itself, is processed as a PHP file and returns a blank page.

Troubleshooting connection errors One error you may get is:

2

Fatal error: Call to undefined function mysql_connect( ) in C:\\Program Files\\Apache

Software Foundation\\Apache2.2\\htdocs\\db_test.php on line 4

This error occurs because PHP 5.x for Windows was downloaded, and MySQL support was not included by default. To fix this error, copy the

php_mysql.dll file from the ext/ directory of the PHP ZIP file to C:\\php, and then C:\\WINDOWS\\php.ini.

Make sure there are two lines that are not commented out by a semicolon (;) at the beginning of the line like these:

extension_dir = \extension=php_mysql.dll

This will change the extension to include the directory to C:/php and include the MySQL extension, respectively. You can use the Search function of your text editor to check whether the lines are already there and just need to be uncommented, or whether they need to be added completely.

You’ll need to restart Apache, and then MySQL support will be enabled. Selecting the Database

Now that you’re connected, the next step is to select which database to use with the mysql_select_db command. It takes two parameters: the database name and, optionally, the database connection. If you don’t specify the database connection, the default is the connection from the last mysql_connect:

// Select the database

$db_select=mysql_select_db($db_database); if (!$db_select) {

die (\}

Again, it’s good practice to check for an error and display it every time you access the database.

Now that you’ve got a good database connection, you’re ready to execute your SQL query.

Building the SQL SELECT Query

Building a SQL query is as easy as setting a variable to the string that is your SQL query. Of course, you’ll need to use a valid SQL query, or MySQL returns with an error when you execute the query. The variable name $query is used since the name reflects its purpose, but you can choose anything you’d like for a variable name. The SQL query in this example is SELECT * FROM books.

3

You can build up your query in parts using the string concatenate (.) operator:

Executing the Query

To have the database execute the query, use the mysql_query function. It takes two parameters—the query and, optionally, the database link—and returns the result. Save a link to the results in a variable called, you guessed it, $result! This is also a good place to check the return code from mysql_query to make sure that there were no errors in the query string or the database connection by verifying that $result is not FALSE: When the database executes the query, all of the results forma result set. These results correspond to the rows that you saw upon doing a query using the mysql command-line client. To display them, you process each row, one at a time.

Fetching and Displaying

Use mysql_fetch_row to get the rows from the result set. Its syntax is:

array mysql_fetch_row ( resource $result);

It takes the result you stored in $result fromthe query as a parameter. It returns one row at a time from the query until there are no more rows, and then it returns FALSE. Therefore, you do a loop on the result of mysql_fetch_row and define some code to display each row:

The columns of the result row are stored in the array and can be accessed one at a time. The variable $result_row[2] accesses the second attribute (as defined in the query’s column order or the column order of the table if SELECT * is used) in the result row. Fetch types

This is not the only way to fetch the results. Using mysql_fetch_array, PHP can place the results into an array in one step. It takes a result as its first parameter, and the way to bind the results as an optional second parameter. If MYSQL_ASSOC is specified, the results are indexed in an array based on their column names in the query. If MYSQL_NUM is specified, then the number starting at zero accesses the results. The default value, MYSQL_BOTH, returns a result array with both types. The mysql_fetch_

assoc is an alternative to supplying the MYSQL_ASSOC argument.

Closing the Connection

As a rule of thumb, you always want to close a connection to a database when you’redone using it. Closing a database with mysql_close will tell PHP and MySQL that you no longer will be using the connection, and will free any resources and memory allocated to it:

mysql_close($connection)

Installing

4

PEAR uses a Package Manager that oversees which PEAR features you install. Whether you need to install the Package Manager depends on which version of PHP you installed. If you’re running PHP 4.3.0 or newer, it’s already installed. If you’rerunning PHP 5.0, PEAR has been split out into a separate package. The DB package that you’re interested in is optional but installed by default with the Package Manager. So if you have the Package Manager, you’re all set. Unix

You can install the Package Manager on a Unix systemby executing the following

from the shell (command-line) prompt:

lynx -source http://go-pear.org/ | php This takes the output of the go-pear.org site (which is actually the source PHP code) to install PEAR and passes it along to the php command for execution. Windows

The PHP 5 installation includes the PEAR installation script as

C:\\php\\go-pear.bat. In case you didn’t install all the files in Chapter 2, go ahead and extract all the PHP files to C:/php from the command prompt, and execute the .bat file. Creating a connect instance

The DB.php file defines a class of type DB. Refer to Chapter 5 for more information on working with classes and objects. We’ll principally be calling the methods in the class. The DB class has a connect method, which we’ll use instead of our old connect function, mysql_connect. The double colons (::) indicate that we’re calling that function from the class in line 4:

$connection =

DB::connect(\);

When you call the connect function, it creates a new database connection that is stored in the variable $connection. The connect function attempts to connect to the database based on the connect string you passed to it. Connect string The connect string uses this new format to represent the login information that you already supplied in separate fields:

dbtype://username:password@host/database

This format may look familiar to you, as it’s very similar to the connect string for a Windows file share. The first part of the string is what really sets the PEAR functions apart fromthe plain PHP. The phptype field specifies the type of database to connect. Supported databases include ibase, msql, mssql, mysql, oci8, odbc, pgsql, and sybase. All that’s required for your PHP page to work with a different type of database is changing the phptype!

5

The username, password, host, and database should be familiar from the basic PHP connect. Only the type of connection is required. However, you’ll usually want to specify all fields.

After the values from db_login.php are included, the connect string looks like the following:

\

If the connect method on line 6 was successful, a DB object is created. It contains the methods to access the database as well as all of the information about the state of that database connection. Querying

One of the methods it contains is called query. The query method works just like PHP’s query function in that it takes a SQL statement. The difference is that the arrow syntax (->) is used to call it fromthe object. It also returns the results as another object instead of a result set:

$query = \

$result = $connection->query($query);

Based on the SQL query, this code calls the query function fromthe connection

object and returns a result object named $result. Fetching

Line 22 uses the result object to call the fetchRow method. It returns the rows one at a time, similar to mysql_fetch_row:

while ($result_row = $result->fetchRow( )) {

echo 'Title: '.$result_row[1] . '
'; echo 'Author: '.$result_row[4] . '
'; echo 'Pages: '.$result_row[2] . '

';

}

Use another while loop to go through each row from fetchRow until it returns FALSE. The code in the loop hasn’t changed from the non-PEAR example. Closing

You’re finished with the database connection, so close it using the object method disconnect:

$connection->disconnect( ); PEAR error reporting The function DB::isError will check to see whether the result that’s been returned to you is an error. If it is an error, you can use DB::errorMessage to return a text description of the error that was generated. You need to pass DB::errorMessage, the return value from your function, as an argument.

Here you rewrite the PEAR code to use error checking:

6

if ( DB::isError( $demoResult = $db->query( $sql))) {

echo DB::errorMessage($demoResult); } else {

while ($demoRow = $demoResult->fetchRow( )) {

echo $demoRow[2] . '
'; } } ?>

There’s also a new version of the PEAR database interface called PEAR::MDB2.

The same results display, but there are more functions available in this version of the PEAR database abstraction layer.

Now that you have a good handle on connecting to the database and the various functions of PEAR。

译文:

通过PHP访问MySQL

现在你已经可以熟练地使用MySQL客户端软件来操作数据库里的数据,我们也可以开始学习如何使用PHP来显示和修改数据库里的数据了。PHP有标准的函数用来操作数据库。

我们首先学习PHP内建的数据库函数,然后会学习PHP扩展和应用程序库(PEAR,PHP Extension and Application Repository )中的数据库函数,我们可以使用这些函数操作所有支持的数据库。这种灵活性源自于抽象。对于编程接口而言,

7

抽象简化了复杂的交互过程。它将交互过程中无关紧要的部分屏蔽起来,让你关注于重要的部分。PEAR的DB类就是这样一种数据库接口的抽象。你登录一个数据库所需要提供的信息被减少到最少。这种标准的格式可以通过同一个函数来访问MySQL以及其他的数据库。同样,一些MySQL特定的函数被更一般的、可以用在很多数据库上的函数所替代。比如,MySQL特定的连接函数是:

mysql_connect($db_host, $db_username, $db_password); 而PEAR的DB提供的连接函数是: $connection =

DB::connect(\);

两个命令都提供了同样的基本信息,但是PEAR的函数中还指定了要连接的数据库的类型。你可以连接到MySQL或者其他支持的数据库。我们会详细讨论这两种连接方式。

本章中,我们会学习如何从PHP连接到MySQL的服务器,如何使用PHP访问数据库中存储的数据,以及如何正确的向用户显示信息。 步骤

无论是通过MySQL命令行工具,还是通过PHP,执行一个查询的基本步骤都是一样的:

? 连接到数据库 ? 选择要使用的数据库 ? 创建SELECT语句 ? 执行查询 ? 显示结果

我们将逐一介绍如何用PHP和PEAR的函数完成上面的每一步。 资源

当连接到MySQL数据库的时候,你会使用到两个新的资源。第一个是连接的标识符,它记录了一个活动连接用来连接到数据库所必需的所有信息。另外一个资源是结果资源,它包含了用来从一个有效的数据库查询结果中取出结果所需要的所有信息。本章中我们会创建并使用这两种资源。 使用PHP函数查询数据库

本节我们会介绍如何使用PHP连接MySQL数据库。这非常简单,我们会用一些例子说明。但是之前我们应该稍微了解一下幕后发生的事情。当你试图连接一个

8

MySQL数据库的时候,MySQL服务器会根据你的用户名和密码进行身份认证。PHP为你建立数据库的连接,你可以立即开始查询并得到结果。 我们需要同样的信息来连接数据库: ? 数据库服务器的IP地址 ? 数据库的名字 ? 用户名 ? 密码

在开始之前,首先使用MySQL的命令行客户端确认你登录到数据库。 图9-1显示了数据库交互过程的各个步骤和两种类型资源之间的关系。创建SELECT语句发生在第三个函数调用之前,但是在图中没有显示出来。它是通过普通的PHP代码,而不是MySQL特定的PHP函数完成的。 图9-1:使用数据库时函数和资源之间的交互 包含数据库登录细节

我们先创建一个文件,用来保存登录MySQL所用到的信息。我们建议你把这些信息放在单独的文件里然后通过include来使用这个文件。这样一来如果你修改了数据库的密码。无论有多少个PHP文件访问数据库,你只需要修改这一个文件。 连接到数据库

我们需要做的头一件事情是连接数据库,并且检查连接是否确实建立起来。通过include包含连接信息的文件,我们可以在调用mysql_connect函数的时候使用这些变量而不是将这些值写死在代码中。我们使用一个叫做db_test.php的文件,往其中增加这些代码段。 诊断连接错误

你可能遇到的一个错误是:

Fatal error: Call to undefined function mysql_connect( ) in C:\\Program Files\\Apache

Software Foundation\\Apache2.2\\htdocs\\db_test.php on line 4 这个错误发生的原因是下载安装的PHP5.x默认没有包括对MySQL的支持。解决这个问题需要将php_mysql.dll文件从PHP压缩包例的ext/目录复制到C:/php,并修改C:\\WINDOWS\\php.ini文件,确保下面两行没有被注释掉(注释的方法在行首使用分号)。

extension_dir = \extension=php_mysql.dll

9

这样PHP扩展的目录就被设为C:\\PHP,MySQL的扩展也会被使用。在编辑php.ini文件的时候,你可以使用编辑器的搜索功能来检查这两行是否已经存在,只是需要去掉注释,并且需要重新输入。

重新启动Apache,这样MySQL的支持就会被打开了。 选择数据库

建立连接之后,下一步就是使用mysql_select_db来选择我们要用的数据库。它的参数有两个:数据库名和可选的数据库连接。如果不指定数据库连接,默认使用上一条mysql_connect所建立的连接。

// Select the database

$db_select=mysql_select_db($db_database); if (!$db_select) {

die (\}

同样的,每次访问数据库的时候最好能检查可能的错误并且进行显示。 现在我们做好了一切准备工作,可以开始执行SQL查询了。 构建SQL SELECT查询

构建SQL查询非常容易就是将一个字符串赋值给变量。这个字符串就是我们的SQL查询,当然我们要给出有效的SQL查询,否则执行这个查询的时候MySQL会返回错误。我们使用$query作为变量名,这个名字对应其目的,你也可以选择任何你喜欢的变量名。这个例子中的SQL查询是”SELECT * FROM books”。 你可以使用字符串连接操作符(.)来构建查询: 执行查询

使用mysql_query函数来告诉数据库执行查询。它有两个参数:查询和可选的数据库连接,返回值是查询结果。我们将查询结果保存在一个变量里,也许你已经猜到我们要用变量名就是$result。这里同样有必要检查mysql_query的返回值不是FALSE来确保查询字符串和数据库连接都没有问题。

当数据库查询的时候,所有的结果构成一个结果集。这些结果跟使用mysql命令行客户端执行同样查询所得到的行一致。要显示这些结果,你需要依次处理这些行。

取结果并显示

使用mysql_fetch_row从结果集中取出一行,它的用法如下:

array mysql_fetch_row ( resource $result);

10

它的参数是SQL查询返回的结果,我们将结果保存在$result中。每次调用它返回一行数据,直到没有数据为止,这时候它返回FALSE。这样,我们可以使用一个循环,在循环内调用mysql_fetch_row并使用一些代码来显示每一行。 结果行的所有列都保存在一个数组里,可以方便地进行访问。变量$result_row[2]访问结果行的第二个属性(数组的顺序是查询是定义的列的顺序,如果使用SELECE * ,那么数组顺序就是表的列的顺序)。 取结果的方式

去结果的方式不止一种。使用mysql_fetch_arrry可以一次性将所有结果放在一个数组里。它的参数是查询结果和一个可选的结果绑定方式。如果绑定方式指定为MYSQL_ASSOC,数组中的结果则使用查询中列的名字进行访问。如果指定了MYSQL_NUM,那么就使用从0开始的数字来访问结果。默认使用的方式是MYSQL_BOTH,这样返回的数组支持两种类型的访问。Mysql_fetch_assoc是使用MYSQL_ASSOC取结果的另外一种方式。 关闭连接

绝大部分情况下,我们在使用完一个数据库之后要关闭到它的连接。使用mysql_close来关闭一个数据库,它会告诉PHP和MySQL这个数据库连接已经不再使用,所使用的所有资源和内存都可以释放。

mysql_close($connection) 安装

PEAR使用包管理器来管理安装PEAR模块。是否需要安装包管理取决于你所使用的PHP版本。如果你使用的版本是PHP4.4.0或者更新的版本,那么就已经安装了包管理器。如果你使用的是PHP5.0,则PEAR是一个单独的包。我们要用到的DB包是可选的,但是它会被包管理器默认安装。所以,如果你有包管理器,那么就全搞定了。 UNIX

在UNIX系统下,可以通过在shell(命令行)下执行下面的命令来安装包管理器:lynx -source http://go-pear.org/ | php

这个命令使用go-pear.org的输出(实际就是PHP源代码)来安装PEAR,go-pear.org的输出被传给php命令执行。 Windows

安装完PHP5后,会有一个PEAR安装脚本C:\\php\\go-pear.bat。如果你在第二章没有安装所以文件,那么现在把所有的PHP文件都解压到C:\\php下,然后执行这个批处理文件。

11

创建连接示例

DB.php文件定义了类DB。参考第5章有关使用类和对象的更多信息。我们将会主要使用这个类提供的方法。类DB有一个connect方法,我们会使用它来替换前面使用的connect函数mysql_connect。双冒号(::)表示调用类的函数,如第6行所示。 $connection =

DB::connect(\);

当调用connect函数的时候,它出创建一个新的数据库连接,保存在变量$connection中。Connect函数试图通过传递给它的连接字符串来连接数据库。 连接字符串

连接字符串使用新的格式来表示登录信息,这些信息我们已经通过单独的域提供:

dbtype://username:password@host/database

这个格式看起来也许会有些熟悉,它跟Windows的文件共享所使用的连接字符串非常相似。字符串的第一部分phptype是将PEAR函数与一般PHP函数区分开来的关键部分。Phptype域指定要连接的数据库类型,支持的数据库包括ibase、mysql、mssql、mysql、oci8、odbc、pgsql、和sybase。如果需要使用不同类型的数据库,你的PHP代码只需要修改phptype.

其他的域username、password、host和database跟基本的PHP connect类似。只有连接类型是必需的,不过通常要指定所有的域。 代入了db_login.php中的数值之后,连接字符串如下所示:

\

如果第6行的连接方法调用成功,就会创建一个DB对象。它包含访问数据库的方法和数据库连接的所有状态信息。 查询

DB对象包含的一个方法是query。Query方法跟PHP的query函数非常类似,都接受一个SQL语句作为参数。区别是要使用箭头(->)来通过对象调用函数,并且它返回的结果是另外一个对象而不是结果集。

$query = \$result = $connection->query($query);

这个代码在连接对象上调用query函数,执行SQL查询,返回结果对象$result. 取结果

12

第22行在结果对象上调用方法fetchRow。与mysql_fetch_row类似,这个方法一次返回一行数据:

while ($result_row = $result->fetchRow( )) {

echo 'Title: '.$result_row[1] . '
'; echo 'Author: '.$result_row[4] . '
'; echo 'Pages: '.$result_row[2] . '

';

}

使用一个while循环并调用fetchRow来遍历所有行,直到fetchRow返回FALSE。 循环内的代码跟未使用PEAR的例子中的代码一致。 关闭

结束数据库连接,它使用的是DB对象的disconnect方法:

$connection->disconnect( ); PEAR错误报告

函数DB::isError会检查返回的结果是不是个错误。如果是,可以使用DB::errorMessae得到错误对应的文字描述。你需要将函数的返回值传递给DB::errorMessage作为参数。

下面使用PEAR代码重写错误检查:

if ( DB::isError( $demoResult = $db->query( $sql))) {

echo DB::errorMessage($demoResult); } else {

while ($demoRow = $demoResult->fetchRow( )) {

echo $demoRow[2] . '
'; } } ?>

PEAR数据库接口还提供了一个新版本叫做PEAR::MDB2。

我们得到同样的显示结果。这个版本的PEAR数据库抽象提供了更多的函数。 现在我们掌握了连接数据库的方法以及PEAR提供的各种函数。

13

本文来源:https://www.bwwdw.com/article/3awg.html

Top