php畢業(yè)設計外文翻譯_第1頁
php畢業(yè)設計外文翻譯_第2頁
php畢業(yè)設計外文翻譯_第3頁
php畢業(yè)設計外文翻譯_第4頁
php畢業(yè)設計外文翻譯_第5頁
已閱讀5頁,還剩9頁未讀 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

1、原文:  Getting PHP to Talk to MySQlNow that youre 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, were going to discuss PHPs buil

2、t-in database functions. Well also show you how to use the The PHP Extension and Application Repository (PEAR) databasefunctions 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 inter

3、faces, abstraction simplifies a complex interaction. It works byremoving any nonessential parts of the interaction, allowing you to concentrate on the important parts. PEARs DB classes are one such database interface abstraction. The information you need to log into a database is reduced to the bare

4、 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($

5、db_host, $db_username, $db_password);versus PEARs DB connect function:$connection = DB:connect("mysql:/$db_username:$db_password$db_host/$db_database");The same basic information is present in both commands, but the PEAR function also specifies the type of databases to which to connect. Yo

6、u can connect to MySQL or other supported databases. Well discuss both connection methods in detail.In this chapter, youll 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 ProcessThe basic step

7、s 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.Well walk through each of these steps for both plain PHP and PEAR functions.ResourcesWhen con

8、necting 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

9、active database querys result set. Youll be creating and assigning both resources in this chapter.Querying the Database with PHP FunctionsIn this section, we introduce how to connect to a MySQL database with PHP. Its quite simple, and well begin shortly with examples, but we should talk briefly abou

10、t what actually happens. When you try connecting to a MySQL database, the MySQL server authenticates you based on your username and password. PHP handles connectingto the database for you, and it allows you to start performing queries and gathering data immediately.As in Chapter 8, well need the sam

11、e pieces of information to connect to the database: The IP address of the database server The name of the database The username The passwordBefore 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

12、 to the two types of resources. Building the SELECT statement happens before the third function call, but it is not shown. Its done with plain PHP code, not a MySQL-specific PHP function. Figure 9-1. The interaction between functions and resources when using the databaseIncluding Database Login

13、 DetailsYoure 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 manyPHP files you have that access the databa

14、se.You dont 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 errorsOne error you may get is:Fatal error: Call to undefined functio

15、n mysql_connect( ) in C:Program FilesApacheSoftware FoundationApache2.2htdocsdb_test.php on line 4This 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

16、 C:php, and then C:WINDOWSphp.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 = "c:/PHP/ext/"extension=php_mysql.dllThis will change the extension to include the directory to C:/php and include the

17、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. Youll need to restart Apache, and then MySQL support will be enabled.Selecting the Databa

18、seNow that youre 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 dont specify the database connection, the default is the connection from the last mysql_connect:/

19、 Select the database$db_select=mysql_select_db($db_database);if (!$db_select)die ("Could not select the database: <br />". mysql_error( );Again, its good practice to check for an error and display it every time you access the database. Now that youve got a good database connecti

20、on, youre ready to execute your SQL query. Building the SQL SELECT QueryBuilding a SQL query is as easy as setting a variable to the string that is your SQL query. Of course, youll need to use a valid SQL query, or MySQL returns with an error when you execute the query. The variable name $query

21、 is used since the name reflects its purpose, but you can choose anything youd like for a variable name. The SQL query in this example is SELECT * FROM books. You can build up your query in parts using the string concatenate (.) operator: Executing the QueryTo have the database execute the

22、 query, use the mysql_query function. It takes two parametersthe query and, optionally, the database linkand 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

23、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 pr

24、ocess each row, one at a time.Fetching and DisplayingUse 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

25、 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_row2 accesses the second attribute (as defined in th

26、e querys column order or the column order of the table if SELECT * is used) in the result row.Fetch typesThis 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 resu

27、lts 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

28、 mysql_fetch_assoc is an alternative to supplying the MYSQL_ASSOC argument.Closing the ConnectionAs a rule of thumb, you always want to close a connection to a database when youredone using it. Closing a database with mysql_close will tell PHP and MySQL that you no longer will be using the connectio

29、n, and will free any resources and memory allocated to it:mysql_close($connection) InstallingPEAR 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 youre running PHP 4.3.0 or new

30、er, its already installed. If yourerunning PHP 5.0, PEAR has been split out into a separate package. The DB package that youre interested in is optional but installed by default with the Package Manager. So if you have the Package Manager, youre all set.UnixYou can install the Package Manager on a U

31、nix systemby executing the followingfrom the shell (command-line) prompt:lynx -source / | phpThis takes the output of the site (which is actually the source PHP code) to install PEAR and passes it along to the php command for execution.WindowsThe PHP 5 installation inclu

32、des the PEAR installation script as C:phpgo-pear.bat. In case you didnt 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 instanceThe DB.php file defines a class of type DB. Refer to Chapter 5 fo

33、r more information on working with classes and objects. Well principally be calling the methods in the class. The DB class has a connect method, which well use instead of our old connect function, mysql_connect. The double colons (:) indicate that were calling that function from the class in line 4:

34、$connection = DB:connect("mysql:/$db_username:$db_password$db_host/$db_database");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 pa

35、ssed to it.Connect stringThe connect string uses this new format to represent the login information that you already supplied in separate fields:dbtype:/username:passwordhost/databaseThis format may look familiar to you, as its very similar to the connect string for a Windows file share. The first p

36、art 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 thats required for your PHP page to work with a different type of d

37、atabase is changing the phptype! The username, password, host, and database should be familiar from the basic PHP connect. Only the type of connection is required. However, youll usually want to specify all fields. After the values from db_login.php are included, the connect string looks l

38、ike the following:"mysql:/test:testlocalhost/test"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.QueryingOne of the methods it contains is c

39、alled query. The query method works just like PHPs 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 = "SELECT * FROM books"$result

40、 = $connection->query($query);Based on the SQL query, this code calls the query function fromthe connectionobject and returns a result object named $result.FetchingLine 22 uses the result object to call the fetchRow method. It returns the rows one at a time, similar to mysql_fetch_row:while ($res

41、ult_row = $result->fetchRow( ) echo 'Title: '.$result_row1 . '<br />'echo 'Author: '.$result_row4 . '<br /> 'echo 'Pages: '.$result_row2 . '<br /><br />'Use another while loop to go through each row from fetchRow until it ret

42、urns FALSE. The code in the loop hasnt changed from the non-PEAR example.ClosingYoure finished with the database connection, so close it using the object method disconnect:$connection->disconnect( );PEAR error reportingThe function DB:isError will check to see whether the result thats been return

43、ed 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:<?phpif ( DB:isError

44、( $demoResult = $db->query( $sql)echo DB:errorMessage($demoResult); elsewhile ($demoRow = $demoResult->fetchRow( )echo $demoRow2 . '<br />'?>Theres also a new version of the PEAR database interface called PEAR:MDB2. The same results display, but there are more functions availa

45、ble 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現(xiàn)在你已經可以熟練地使用MySQL客戶端軟件來操作數(shù)據庫里的數(shù)據,我們也可以開始學習如何使用PHP來顯示和修改數(shù)據庫里的數(shù)據了。PHP有標準的函數(shù)用來操作數(shù)據庫。 我們首先學習PHP內建的數(shù)據庫函數(shù),然后會學習PHP擴展和應用程序庫(PE

46、AR,PHP Extension and Application Repository )中的數(shù)據庫函數(shù),我們可以使用這些函數(shù)操作所有支持的數(shù)據庫。這種靈活性源自于抽象。對于編程接口而言,抽象簡化了復雜的交互過程。它將交互過程中無關緊要的部分屏蔽起來,讓你關注于重要的部分。PEAR的DB類就是這樣一種數(shù)據庫接口的抽象。你登錄一個數(shù)據庫所需要提供的信息被減少到最少。這種標準的格式可以通過同一個函數(shù)來訪問MySQL以及其他的數(shù)據庫。同樣,一些MySQL特定的函數(shù)被更一般的、可以用在很多數(shù)據庫上的函數(shù)所替代。比如,MySQL特定的連接函數(shù)是:   mysql_connect($d

47、b_host, $db_username, $db_password);而PEAR的DB提供的連接函數(shù)是:$connection = DB:connect("mysql:/$db_username:$db_password$db_host/$db_database");兩個命令都提供了同樣的基本信息,但是PEAR的函數(shù)中還指定了要連接的數(shù)據庫的類型。你可以連接到MySQL或者其他支持的數(shù)據庫。我們會詳細討論這兩種連接方式。 本章中,我們會學習如何從PHP連接到MySQL的服務器,如何使用PHP訪問數(shù)據庫中存儲的數(shù)據,以及如何正確的向用戶顯示信息。步驟無論是通過My

48、SQL命令行工具,還是通過PHP,執(zhí)行一個查詢的基本步驟都是一樣的: 連接到數(shù)據庫 選擇要使用的數(shù)據庫 創(chuàng)建SELECT語句 執(zhí)行查詢 顯示結果我們將逐一介紹如何用PHP和PEAR的函數(shù)完成上面的每一步。資源當連接到MySQL數(shù)據庫的時候,你會使用到兩個新的資源。第一個是連接的標識符,它記錄了一個活動連接用來連接到數(shù)據庫所必需的所有信息。另外一個資源是結果資源,它包含了用來從一個有效的數(shù)據庫查詢結果中取出結果所需要的所有信息。本章中我們會創(chuàng)建并使用這兩種資源。使用PHP函數(shù)查詢數(shù)據庫本節(jié)我們會介紹如何使用PHP連接MySQL數(shù)據庫。這非常簡單,我們會用一些例子說明。但是之前我們應該稍微了解一下

49、幕后發(fā)生的事情。當你試圖連接一個MySQL數(shù)據庫的時候,MySQL服務器會根據你的用戶名和密碼進行身份認證。PHP為你建立數(shù)據庫的連接,你可以立即開始查詢并得到結果。我們需要同樣的信息來連接數(shù)據庫: 數(shù)據庫服務器的IP地址 數(shù)據庫的名字 用戶名 密碼在開始之前,首先使用MySQL的命令行客戶端確認你登錄到數(shù)據庫。圖9-1顯示了數(shù)據庫交互過程的各個步驟和兩種類型資源之間的關系。創(chuàng)建SELECT語句發(fā)生在第三個函數(shù)調用之前,但是在圖中沒有顯示出來。它是通過普通的PHP代碼,而不是MySQL特定的PHP函數(shù)完成的。圖9-1:使用數(shù)據庫時函數(shù)和資源之間的交互包含數(shù)據庫登錄細節(jié)我們先創(chuàng)建一個文件,用來保

50、存登錄MySQL所用到的信息。我們建議你把這些信息放在單獨的文件里然后通過include來使用這個文件。這樣一來如果你修改了數(shù)據庫的密碼。無論有多少個PHP文件訪問數(shù)據庫,你只需要修改這一個文件。連接到數(shù)據庫我們需要做的頭一件事情是連接數(shù)據庫,并且檢查連接是否確實建立起來。通過include包含連接信息的文件,我們可以在調用mysql_connect函數(shù)的時候使用這些變量而不是將這些值寫死在代碼中。我們使用一個叫做db_test.php的文件,往其中增加這些代碼段。診斷連接錯誤你可能遇到的一個錯誤是:Fatal error: Call to undefined function mysql_c

51、onnect( ) in C:Program FilesApacheSoftware FoundationApache2.2htdocsdb_test.php on line 4這個錯誤發(fā)生的原因是下載安裝的PHP5.x默認沒有包括對MySQL的支持。解決這個問題需要將php_mysql.dll文件從PHP壓縮包例的ext/目錄復制到C:/php,并修改C:WINDOWSphp.ini文件,確保下面兩行沒有被注釋掉(注釋的方法在行首使用分號)。extension_dir = "c:/PHP/ext/"extension=php_mysql.dll這樣PHP擴展的目錄就被設為

52、C:PHP,MySQL的擴展也會被使用。在編輯php.ini文件的時候,你可以使用編輯器的搜索功能來檢查這兩行是否已經存在,只是需要去掉注釋,并且需要重新輸入。重新啟動Apache,這樣MySQL的支持就會被打開了。選擇數(shù)據庫建立連接之后,下一步就是使用mysql_select_db來選擇我們要用的數(shù)據庫。它的參數(shù)有兩個:數(shù)據庫名和可選的數(shù)據庫連接。如果不指定數(shù)據庫連接,默認使用上一條mysql_connect所建立的連接。/ Select the database$db_select=mysql_select_db($db_database);if (!$db_select)die (&qu

53、ot;Could not select the database: <br />". mysql_error( );同樣的,每次訪問數(shù)據庫的時候最好能檢查可能的錯誤并且進行顯示。現(xiàn)在我們做好了一切準備工作,可以開始執(zhí)行SQL查詢了。構建SQL SELECT查詢構建SQL查詢非常容易就是將一個字符串賦值給變量。這個字符串就是我們的SQL查詢,當然我們要給出有效的SQL查詢,否則執(zhí)行這個查詢的時候MySQL會返回錯誤。我們使用$query作為變量名,這個名字對應其目的,你也可以選擇任何你喜歡的變量名。這個例子中的SQL查詢是”SELECT * FROM books”。你可以使

54、用字符串連接操作符(.)來構建查詢:執(zhí)行查詢使用mysql_query函數(shù)來告訴數(shù)據庫執(zhí)行查詢。它有兩個參數(shù):查詢和可選的數(shù)據庫連接,返回值是查詢結果。我們將查詢結果保存在一個變量里,也許你已經猜到我們要用變量名就是$result。這里同樣有必要檢查mysql_query的返回值不是FALSE來確保查詢字符串和數(shù)據庫連接都沒有問題。當數(shù)據庫查詢的時候,所有的結果構成一個結果集。這些結果跟使用mysql命令行客戶端執(zhí)行同樣查詢所得到的行一致。要顯示這些結果,你需要依次處理這些行。取結果并顯示使用mysql_fetch_row從結果集中取出一行,它的用法如下:array mysql_fetch_r

55、ow ( resource $result);它的參數(shù)是SQL查詢返回的結果,我們將結果保存在$result中。每次調用它返回一行數(shù)據,直到沒有數(shù)據為止,這時候它返回FALSE。這樣,我們可以使用一個循環(huán),在循環(huán)內調用mysql_fetch_row并使用一些代碼來顯示每一行。結果行的所有列都保存在一個數(shù)組里,可以方便地進行訪問。變量$result_row2訪問結果行的第二個屬性(數(shù)組的順序是查詢是定義的列的順序,如果使用SELECE * ,那么數(shù)組順序就是表的列的順序)。取結果的方式去結果的方式不止一種。使用mysql_fetch_arrry可以一次性將所有結果放在一個數(shù)組里。它的參數(shù)是查詢結

56、果和一個可選的結果綁定方式。如果綁定方式指定為MYSQL_ASSOC,數(shù)組中的結果則使用查詢中列的名字進行訪問。如果指定了MYSQL_NUM,那么就使用從0開始的數(shù)字來訪問結果。默認使用的方式是MYSQL_BOTH,這樣返回的數(shù)組支持兩種類型的訪問。Mysql_fetch_assoc是使用MYSQL_ASSOC取結果的另外一種方式。關閉連接絕大部分情況下,我們在使用完一個數(shù)據庫之后要關閉到它的連接。使用mysql_close來關閉一個數(shù)據庫,它會告訴PHP和MySQL這個數(shù)據庫連接已經不再使用,所使用的所有資源和內存都可以釋放。mysql_close($connection)安裝PEAR使用包

57、管理器來管理安裝PEAR模塊。是否需要安裝包管理取決于你所使用的PHP版本。如果你使用的版本是PHP4.4.0或者更新的版本,那么就已經安裝了包管理器。如果你使用的是PHP5.0,則PEAR是一個單獨的包。我們要用到的DB包是可選的,但是它會被包管理器默認安裝。所以,如果你有包管理器,那么就全搞定了。UNIX在UNIX系統(tǒng)下,可以通過在shell(命令行)下執(zhí)行下面的命令來安裝包管理器:lynx -source / | php這個命令使用的輸出(實際就是PHP源代碼)來安裝PEAR,的輸出被傳給php命令執(zhí)行。Windows安裝完PHP5后,會有一個PEAR安裝腳本C:phpgo-pe

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論