2023年全國碩士研究生考試考研英語一試題真題(含答案詳解+作文范文)_第1頁
已閱讀1頁,還剩20頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

1、<p><b>  科技外文文獻(xiàn)</b></p><p>  Getting PHP to Talk to MySQL</p><p>  Now that you’re comfortable using the MySQL client tools to manipulate data in the database, you can begin usi

2、ng 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 Ex

3、tension and Application Repository (PEAR) database</p><p>  functions that provide the ability to use the same functions to access any supported database. This type of flexibility comes from a process called

4、 abstraction. In programming interfaces, abstraction simplifies a complex interaction. It works by</p><p>  removing any nonessential parts of the interaction, allowing you to concentrate on the important pa

5、rts. 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

6、 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-specifi</p><p>  mysql_connect($d

7、b_host, $db_username, $db_password);</p><p>  versus PEAR’s DB connect function:</p><p>  $connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");</p>

8、;<p>  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 b

9、oth connection methods in detail.</p><p>  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

10、to the user.</p><p>  The Process</p><p>  The basic steps of performing a query, whether using the mysql command-line tool or PHP, are the same:</p><p>  ? Connect to the database.

11、</p><p>  ? Select the database to use.</p><p>  ? Build a SELECT statement.</p><p>  ? Perform the query.</p><p>  ? Display the results.</p><p>  We’ll w

12、alk through each of these steps for both plain PHP and PEAR functions.</p><p><b>  Resources</b></p><p>  When connecting to a MySQL database, you will use two new resources. The fir

13、st 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 resu

14、lts from an active database query’s result set. You’ll be creating and assigning both resources in this chapter.</p><p>  Querying the Database with PHP Functions</p><p>  In this section, we in

15、troduce 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 MySQ

16、L server authenticates you based on your username and password. PHP handles connecting</p><p>  to the database for you, and it allows you to start performing queries and gathering data immediately.</p>

17、;<p>  As in Chapter 8, we’ll need the same pieces of information to connect to the database:</p><p>  ? The IP address of the database server</p><p>  ? The name of the database</p>

18、;<p>  ? The username</p><p>  ? The password</p><p>  Before moving on, make sure you can log into your database using the MySQL command-line client.</p><p>  Figure 9-1 sho

19、ws 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-spe

20、cific PHP function.</p><p>  Figure 9-1. The interaction between functions and resources when using the database</p><p>  Including Database Login Details</p><p>  You’re going to c

21、reate 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, regardl

22、ess of how many</p><p>  PHP files you have that access the database.</p><p>  You don’t have to worry about anyone directly viewing the file and getting your database login details. The file, i

23、f requested by itself, is processed as a PHP file and returns a blank page.</p><p>  Let’s call this file db_login.php and place it in the same directory as your other PHP files. The file is represented in E

24、xample 9-1.</p><p>  Example 9-1. A template for setting database login settings</p><p><b>  <?php</b></p><p>  $db_host='hostname of database server';</p&

25、gt;<p>  $db_database='database name';</p><p>  $db_username='username';</p><p>  $db_password='password';</p><p><b>  ?></b></p>

26、<p>  In Example 9-2, we create this file to use a database on the same machine as the web server. We assign it a database name, username, and password.</p><p><b>  <?php</b></p>

27、<p>  $db_host='localhost';</p><p>  $db_database='test';</p><p>  $db_username='test';</p><p>  $db_password='yourpass';</p><p>&

28、lt;b>  ?></b></p><p>  Figure 9-2 illustrates how you’re going to use this file with other PHP files. You’regoing to continue using the database that you started to set up in Chapter 7.</p>

29、<p>  Figure 9-2. Reusing the login details in multiple files</p><p>  Example 9-3. The SQL to recreate the test objects (continued)</p><p>  DROP TABLE IF EXISTS books;</p><p&

30、gt;  CREATE TABLE books (</p><p>  title_id int(11) NOT NULL auto_increment,</p><p>  title varchar(150) default NULL,</p><p>  pages int(11) default NULL,</p><p>  PRI

31、MARY KEY (title_id)</p><p>  ) ENGINE=MyISAM DEFAULT CHARSET=latin1;</p><p><b>  --</b></p><p>  -- Dumping data for table books</p><p><b>  --</b&

32、gt;</p><p>  INSERT INTO books VALUES (1,'Linux in a Nutshell',476),(2,'Classic Shell Scripting',256);</p><p><b>  --</b></p><p>  -- Table structure for

33、 table purchases</p><p><b>  --</b></p><p>  DROP TABLE IF EXISTS purchases;</p><p>  CREATE TABLE purchases ( </p><p>  id int(11) NOT NULL auto_increment,

34、 </p><p>  user varchar(10) default NULL, </p><p>  title varchar(150) default NULL, </p><p>  day date default NULL,</p><p>  PRIMARY KEY (id)</p><p>  )

35、ENGINE=MyISAM DEFAULT CHARSET=latin1;</p><p><b>  --</b></p><p>  -- Dumping data for table purchases</p><p><b>  --</b></p><p>  LOCK TABLES pu

36、rchases WRITE;</p><p>  INSERT INTO purchases VALUES (1,'Mdavis','Regular Expression Pocket Reference','2005-02-15'),(2,'Mdavis','JavaScript & DHTML Cookbook','

37、;2005-02-10');</p><p>  If you didn’t create the tables in Chapter 8, the code in Example 9-3 can be saved as backup.sql and run from the command prompt with the following syntax:</p><p>  m

38、ysql -u username -ppassword -D database_name < backup_file_name.sql</p><p>  Using the values from the examples, it becomes:</p><p>  mysql -u test -pyourpass -D test < backup.sql</p>

39、;<p>  The database is called test, and it consists of three tables called books, authors, and purchases. Each table has a few sample rows. That’s enough to get us started querying from PHP.</p><p>  

40、Connecting to the Database</p><p>  The first thing you need to do is connect to the database and check to make sure there’s a connection. Including the file that you set up to store your connection informat

41、ion allows you to use the variables instead of hardcoded values when you call the mysql_connect function, as shown in Example 9-4. We’re assembling one file, db_test.php, by adding these code snippets.</p><p&g

42、t;  Example 9-4. Including the connection values and calling mysql_connect in db_test.php</p><p>  // Include our login information</p><p>  include('db_login.php');</p><p>

43、  // Connect</p><p>  $connection = mysql_connect($db_host, $db_username, $db_password);</p><p>  if (!$connection){</p><p>  die ("Could not connect to the database: <br /&

44、gt;". mysql_error( ));</p><p><b>  }</b></p><p>  The mysql_connect function takes the database host, username, and password as parameters. If the connection is successful, a li

45、nk to a database is returned. FALSE is returned if a connection can’t be made. Check the return value from the function to make sure there’s a connection. If there’s a problem, such as an incorrect password, print out a

46、polite warning and the reason for the error using mysql_error.</p><p>  Instead of simply echoing an error message, die( ) displays the error and stops the program. Not being able to access the database make

47、s most database-driven pages fairly useless and prevents the user from seeing numerous errors.</p><p>  Notice that we didn’t specify the database name yet.</p><p>  Troubleshooting connection e

48、rrors</p><p>  One error you may get is:</p><p>  Fatal error: Call to undefined function mysql_connect( ) in C:\Program Files\Apache</p><p>  Software Foundation\Apache2.2\htdocs\d

49、b_test.php on line 4</p><p>  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/ directo

50、ry of the PHP ZIP file to C:\php, and then C:\WINDOWS\php.ini.</p><p>  Make sure there are two lines that are not commented out by a semicolon (;) at the beginning of the line like these:</p><p&g

51、t;  extension_dir = "c:/PHP/ext/"</p><p>  extension=php_mysql.dll</p><p>  This will change the extension to include the directory to C:/php and include the MySQL extension, respectiv

52、ely. 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.</p><p>  You’ll need to res

53、tart Apache, and then MySQL support will be enabled.</p><p>  Selecting the Database</p><p>  Now that you’re connected, the next step is to select which database to use with the mysql_select_db

54、 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:</p><p>

55、  // Select the database</p><p>  $db_select=mysql_select_db($db_database);</p><p>  if (!$db_select)</p><p><b>  {</b></p><p>  die ("Could not select

56、 the database: <br />". mysql_error( ));</p><p><b>  }</b></p><p>  Again, it’s good practice to check for an error and display it every time you access the database.</

57、p><p>  While it’s possible to call mysql_select_db multiple times within the same script, it’s not considered good practice.</p><p>  Now that you’ve got a good database connection, you’re ready t

58、o execute your SQL query.</p><p>  Building the SQL SELECT Query</p><p>  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 us

59、e 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 qu

60、ery in this example is SELECT * FROM books.</p><p>  Unlike when you used the mysql command-line client, the query does</p><p>  not have a semicolon at the end.</p><p>  You can bu

61、ild up your query in parts using the string concatenate (.) operator:</p><p>  // Assign the query</p><p>  $select = ' SELECT ';</p><p>  $column = ' * ';</p>

62、<p>  $from = ' FROM ';</p><p>  $tables = ' books ';</p><p>  $where = ' NATURAL JOIN authors';</p><p>  $query = $select.$column.$from.$tables.$wher

63、e;</p><p>  This code is a more flexible version of the following:</p><p>  // Assign the query</p><p>  $query = "SELECT * FROM books NATURAL JOIN authors";</p>&l

64、t;p>  The query string could also use a variable in the WHERE clause to limit which rows are returned based on user information or another query.</p><p>  Now that you have your query assigned to a variab

65、le, you can execute it.</p><p>  Executing the Query</p><p>  To have the database execute the query, use the mysql_query function. It takes two parameters—the query and, optionally, the databas

66、e 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 q

67、uery string or the database connection by verifying that $result is not FALSE:</p><p>  // Execute the query</p><p>  $result = mysql_query( $query );</p><p>  if (!$result){</p&

68、gt;<p>  die ("Could not query the database: <br />". mysql_error( ));</p><p><b>  }</b></p><p>  When the database executes the query, all of the results form

69、a 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.</p><p>  Fetching and Displaying&

70、lt;/p><p>  Use mysql_fetch_row to get the rows from the result set. Its syntax is:</p><p>  array mysql_fetch_row ( resource $result);</p><p>  It takes the result you stored in $resu

71、lt 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 disp

72、lay each row:</p><p>  // Fetch and display the results</p><p>  while ($result_row = mysql_fetch_row(($result))){</p><p>  echo 'Title: '.$result_row[1] . '<br />

73、';</p><p>  echo 'Author: '.$result_row[4] . '<br /> ';</p><p>  echo 'Pages: '.$result_row[2] . '<br /><br />';</p><p><b&g

74、t;  }</b></p><p>  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 o

75、rder or the column order of the table if SELECT * is used) in the result row.</p><p>  Fetch types</p><p>  This is not the only way to fetch the results. Using mysql_fetch_array, PHP can place

76、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

77、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 mysq</p><p>  ass

78、oc is an alternative to supplying the MYSQL_ASSOC argument.</p><p>  If you rewrote the code shown previously to use mysql_fetch_array with an associative indexed array, it would look like this:</p>&

79、lt;p>  // Fetch and display the results</p><p>  while ($result_row = mysql_fetch_array($result, MYSQL_ASSOC)){</p><p>  echo 'Title: '.$result_row['title'] . '<br />

80、;';</p><p>  echo 'Author: '.$result_row['author'] . '<br /> ';</p><p>  echo 'Pages: '.$result_row['pages'] . '<br /><br />'

81、;;</p><p><b>  }</b></p><p>  Closing the Connection</p><p>  As a rule of thumb, you always want to close a connection to a database when you’redone using it. Closing a

82、 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:</p><p>  mysql_close($connection)</p><p&

83、gt;  Using PEAR</p><p>  PEAR is a framework and distribution system for reusable PHP components, creating a collection of add-on functionalities for PHP development. There are many modules available to hand

84、le everything fromsession management to shopping cart functionality. Categories of modules that are currently available are listed in Table 9-1.</p><p>  Table 9-1. PEAR modules categories</p><p&g

85、t;  Authentication        HTML                    Processing</p><p>  Benchma

86、rking          HTTP                    Science</p><p>  Caching 

87、60;             Images                  Semantic Web</p><p&

88、gt;  Configuration         Internationalization    Streams</p><p>  Console             

89、0; Logging                 Structures</p><p>  Database            

90、  Mail                    System</p><p>  Date/Time         &#

91、160;   Math                    Test</p><p>  Encryption        

92、;    Networking              Tools and utilities</p><p>  Event          

93、0;      Numbers                 Validate</p><p>  File formats      

94、0;   Payment                 Web services</p><p>  File system         &

95、#160; PEAR                    XML</p><p>  GTK components        PHP<

96、/p><p>  Our list is not complete. Visit http://pear.php.net to find out all of the modules thatare available for download.</p><p>  Installing</p><p>  PEAR uses a Package Manager tha

97、t oversees which PEAR features you install.</p><p>  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 installe

98、d. 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, yo

99、u’re all set.</p><p><b>  Unix</b></p><p>  You can install the Package Manager on a Unix systemby executing the following</p><p>  from the shell (command-line) prompt:

100、</p><p>  lynx -source http://go-pear.org/ | php</p><p>  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 com

101、mand for execution.</p><p><b>  Windows</b></p><p>  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 C

102、hapter 2, go ahead and extract all the PHP files to C:/php from the command prompt, and execute the .bat file.</p><p>  If you installed PHP fromthe MSI installer, you may need to execute</p><p>

103、;  the following instead of the go-pear.bat file:</p><p>  php go-pear.phar</p><p>  If the PEAR directory does not exists at all you’ll need to re-run the</p><p>  PHP MSI installe

104、r, select the Change option, and set Extensions and</p><p>  Extras to “Will be installed on local drive” before running go-pear.phar.</p><p>  Figure 9-5 shows the initial screen after executin

105、g the PEAR installer.</p><p>  Figure 9-5. The go-pear.bat install script</p><p>  You’ll be asked a set of questions about paths. You can accept the defaults for all of them. The base path shou

106、ld be C:\php.</p><p>  The php.exe file must be in your path. Verify by typing php.exe froma</p><p>  command prompt. If it is not found, you’ll need to add it to your PATH</p><p> 

107、 variable. To access your systempath, navigate to Start ?Control Panel ?System ?Environment, and add an entry to the end of the path with C:\php.</p><p>  The PEAR installer creates a file called C:\php\PEAR

108、_ENV.reg. You need to doubleclick to set up the PEAR paths in the registry. This file is contingent on which PEAR version you installed. When the dialog appears to verify your information, you will add this to the regist

109、ry and click OK.</p><p>  You may have to edit the php.ini file after running this .bat file to add the PEAR directory to the include path. Line 447 of php.ini now looks like this:</p><p>  incl

110、ude_path = ".;c:\php\includes;c:\php\PEAR"</p><p>  Apache must be restarted before the DB package can be used.</p><p>  Hosted ISP</p><p>  Most ISPs have PEAR DB install

111、ed. Ask your ISP to install it if they haven’t already. You can tell whether PEAR DB has been installed by trying the PHP code in Example 9-8 to see whether the require_once ('DB.php'); line causes an error when

112、the script is executed. </p><p>  Adding Additional Packages</p><p>  Once that’s complete, you can access the PEAR Package Manager by entering pear at the command prompt. Adding new modules is

113、as easy as executing pear packagename.</p><p>  You won’t need to do anything because the DB package was installed along with the install by default.</p><p>  However, if you’re running Windows

114、XP Home, you’ll need to take these steps to install the PEAR DB:</p><p>  C:\>cd c:\php</p><p>  C:\>pear install DB</p><p>  C:\>pear list</p><p>  To find ou

115、t which versions of PEAR packages are installed, execute pear list. That returns a listing such as the one shown in Figure 9-6.</p><p>  Figure 9-6. A listing of installed PEAR packages and versions</p>

溫馨提示

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

評論

0/150

提交評論