通过PHP访问MySQL.doc_第1页
通过PHP访问MySQL.doc_第2页
通过PHP访问MySQL.doc_第3页
通过PHP访问MySQL.doc_第4页
通过PHP访问MySQL.doc_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

原文:Getting PHP to Talk to MySQl Now 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 built-in database functions. Well 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 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 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 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. You 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.1 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. Well walk through each of these steps for both plain PHP and PEAR functions.2 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 querys result set. Youll be creating and assigning both resources in this chapter.3 Querying the Database with PHP Functions In 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 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, well 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 passwordBefore moving on, make sure you can log into your database using the MySQL command-line client.4 Including Database Login Details Youre 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 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.5 Troubleshooting connection errors One error you may get is:Fatal error: Call to undefined function 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 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.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.Youll need to restart Apache, and then MySQL support will be enabled.6 Selecting the Database Now 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:/ Select the database$db_select=mysql_select_db($db_database);if (!$db_select)die (Could not select the database: . 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 connection, youre ready to execute your SQL query.7 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, youll 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 youd like for a variable name. The SQL query in this example is SELECT * FROM books.8 Executing the QueryTo have the database execute the 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 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.9 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 accesses the second attribute (as defined in the querys column order or the column order of the table if SELECT * is used) in the result row.10 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.11 Closing the Connection As 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 connection, and will free any resources and memory allocated to it:mysql_close($connection)12 Installing 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 youre running PHP 4.3.0 or newer, 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.译文:通过PHP访问MySQL 现在你已经可以熟练地使用MySQL客户端软件来操作数据库里的数据,我们也可以开始学习如何使用PHP来显示和修改数据库里的数据了。PHP有标准的函数用来操作数据库。 我们首先学习PHP内建的数据库函数,然后会学习PHP扩展和应用程序库(PEAR,PHP Extension and Application Repository )中的数据库函数,我们可以使用这些函数操作所有支持的数据库。这种灵活性源自于抽象。对于编程接口而言,抽象简化了复杂的交互过程。它将交互过程中无关紧要的部分屏蔽起来,让你关注于重要的部分。PEAR的DB类就是这样一种数据库接口的抽象。你登录一个数据库所需要提供的信息被减少到最少。这种标准的格式可以通过同一个函数来访问MySQL以及其他的数据库。同样,一些MySQL特定的函数被更一般的、可以用在很多数据库上的函数所替代。比如,MySQL特定的连接函数是: mysql_connect($db_host, $db_username, $db_password);而PEAR的DB提供的连接函数是: $connection= DB:connect(mysql:/$db_username:$db_password$db_host/$db_database); 两个命令都提供了同样的基本信息,但是PEAR的函数中还指定了要连接的数据库的类型。你可以连接到MySQL或者其他支持的数据库。我们会详细讨论这两种连接方式。1 步骤 无论是通过MySQL命令行工具,还是通过PHP,执行一个查询的基本步骤都是一样的: 连接到数据库 选择要使用的数据库 创建SELECT语句 执行查询 显示结果我们将逐一介绍如何用PHP和PEAR的函数完成上面的每一步。2 资源 当连接到MySQL数据库的时候,你会使用到两个新的资源。第一个是连接的标识符,它记录了一个活动连接用来连接到数据库所必需的所有信息。另外一个资源是结果资源,它包含了用来从一个有效的数据库查询结果中取出结果所需要的所有信息。本章中我们会创建并使用这两种资源。3 使用PHP函数查询数据库 我们会介绍如何使用PHP连接MySQL数据库。这非常简单,我们会用一些例子说明。但是之前我们应该稍微了解一下幕后发生的事情。当你试图连接一个MySQL数据库的时候,MySQL服务器会根据你的用户名和密码进行身份认证。PHP为你建立数据库的连接,你可以立即开始查询并得到结果。我们需要同样的信息来连接数据库: 数据库服务器的IP地址 数据库的名字 用户名 密码 在开始之前,首先使用MySQL的命令行客户端确认你登录到数据库。显示了数据库交互过程的各个步骤和两种类型资源之间的关系。创建SELECT语句发生在第三个函数调用之前,但是在图中没有显示出来。它是通过普通的PHP代码,而不是MySQL特定的PHP函数完成的。4 包含数据库登录细节 我们先创建一个文件,用来保存登录MySQL所用到的信息。我们建议你把这些信息放在单独的文件里然后通过include来使用这个文件。这样一来如果你修改了数据库的密码。无论有多少个PHP文件访问数据库,你只需要修改这一个文件。5 连接到数据库 我们需要做的头一件事情是连接数据库,并且检查连接是否确实建立起来。通过include包含连接信息的文件,我们可以在调用mysql_connect函数的时候使用这些变量而不是将这些值写死在代码中。我们使用一个叫做db_test.php的文件,往其中增加这些代码段。6 诊断连接错误 你可能遇到的一个错误是: Fatal error: Call to undefined function mysql_connect( ) in C:Program FilesApacheSoftware FoundationApache2.2htdocsdb_test.php on line 4这个错误发生的原因是下载安装的PHP5.x默认没有包括对MySQL的支持。解决这个问题需要将php_mysql.dll文件从PHP压缩包例的ext/目录复制到C:/php,并修改C:WINDOWSphp.ini文件,确保下面两行没有被注释掉(注释的方法在行首使用分号)。 extension_dir = c:/PHP/ext/ extension=php_mysql.dll 这样PHP扩展的目录就被设为C:PHP,MySQL的扩展也会被使用。在编辑php.ini文件的时候,你可以使用编辑器的搜索功能来检查这两行是否已经存在,只是需要去掉注释,并且需要重新输入。 重新启动Apache,这样MySQL的支持就会被打开了。7 选择数据库 建立连接之后,下一步就是使用mysql_select_db来选择我们要用的数据库。它的参数有两个:数据库名和可选的数据库连接。如果不指定数据库连接,默认使用上一条mysql_connect所建立的连接。 / Select the database $db_select=mysql_select_db($db_database); if (!$db_select) die (Could not select the database: . mysql_error( ); 同样的,每次访问数据库的时候最好能检查可能的错误并且进行显示。现在我们做好了一切准备工作,可以开始执行SQL查询了。8 构建SQL SELECT查询 构建SQL查询非常容易就是将一个字符串赋值给变量。这个字符串就是我们的S

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论