A Programmer’s Introduction to PHP 4.0 phần 7 pptx

47 307 0
A Programmer’s Introduction to PHP 4.0 phần 7 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Logical enough, right? This command could be generalized as follows: SELECT column name FROM table name [ WHERE some condition] The square brackets around the concluding part of the generalized command mean that it is optional. For example, if you wanted to retrieve all of the customer emails from the customers table, you could query the database using the following command: SELECT cust_email FROM customers Moving onward, assume that you wanted to insert a new row of data into the products table (thus a new product, since it is assumed that each product is unique). A sample insertion command is: INSERT into products VALUES ('1009pr', 'Red Tomatoes', '1.43'); Suppose that you later wanted to delete that data. A sample deletion com- mand is: DELETE FROM products WHERE prod_id = '1009pr'; There are many SQL command variations, a complete introduction of them certainly out of the scope of this book. Entire books are devoted to just this sub- ject! However, I will attempt to keep the SQL commands throughout the remain- der of this book relatively simple, while at the same time attaining a certain level of practicality in the examples. I suggest searching the Web for several of the many SQL resources and primers. I have included a few of my personal favorites at the conclusion of this section. Given the fact that you are reading this book, you are likely already wondering how a database is accessed from the Web environment. Typically, some interfac- ing language such as PHP, Java, or Perl is used to initiate a connection with the database, and then through the use of predefined functionality the database is queried as necessary. You can think of this interface language as the “glue” that melds the database and the Web together. With that said, I turn my attention to my favorite glue language, PHP. Chapter 11 262 NOTE It is not required that you capitalize the SQL commands in a query. This is my personal preference, done so as to more easily distinguish the query’s various components. Gilmore_11 12/5/00 10:24 AM Page 262 Additional Resources Here are a few online resources that the SQL novice and expert alike may find useful. • Various SQL tutorials: http://perl.about.com/compute/perl/cs/beginningsql/index.htm • SQLCourse.com (also offers an onsite practice database): http://www.sqlcourse.com/ • SQL for Web nerds: http://www.arsdigita.com/books/sql/ • SQL introduction (focus on MySQL): http://www.devshed.com/Server_Side/MySQL/Intro/ PHP’s Extensive Database Support If I could name any single most important feature of PHP, it would likely be its database support. PHP offers vast support for practically every prominent db server available today, including those listed below: Adabas D Informix PostgreSQL Dbase Ingres Solid Direct MS-SQL InterBase Sybase Empress mSQL UNIX dbm FilePro (read-only) MySQL Velocis FrontBase ODBC IBM DB2 Oracle (OCI7 and OC18) As you can see from the preceding list, PHP’s database support options are extensive, including compatibility with many databases that you have certainly heard of (Oracle, for example) and likely several that you haven’t. The bottom line is, if you plan on using a competent database to store your Web information, chances are it will be one that PHP supports. PHP supports a database by offering a set of predefined functions capable of connecting to, querying, and closing the connection to a database. Discussing the features of each supported database is certainly out of the scope of this book. However, the MySQL database server sufficiently summarizes the general capabilities of many of PHP’s supported database servers and serves as a base for any SQL-based server. For this reason, MySQL syntax is used Databases 263 Gilmore_11 12/5/00 10:24 AM Page 263 throughout the remainder of this chapter and in any database-related examples in the concluding chapters of this book. Regardless of the database server you decide to implement, you should be able to translate the examples from here on with relative ease. MySQL MySQL (http://www.mysql.com) is a robust SQL database server developed and maintained by T.c.X DataKonsultAB of Stockholm, Sweden. Publically available since 1995, MySQL has risen to become one of the most popular database servers in the world, this popularity due in part to the server’s speed, robustness, and flexible licensing policy. (See note for more information regarding MySQL’s licensing strategy.) Given the merits of MySQL’s characteristics, coupled with a vast and extremely easy-to-use set of predefined interfacing functions, MySQL has arguably become PHP’s most-popular database counterpart. Installation MySQL is so popular among PHP users that support for the db server is automati- cally built into the PHP distribution. Therefore, the only task that you are left to deal with is the proper installation of the MySQL package. MySQL is compatible with practically every major operating system, including, among others, FreeBSD, Solaris, UNIX, Linux, and the various Windows versions. While the licensing pol- icy is considerably more flexible than that of other database servers, I strongly suggest taking some time to read through the licensing information found at the MySQL site (http://www.mysql.com). Chapter 11 264 NOTE MySQL is licensed under the GNU General Public License (GPL). Please read the MySQL license information on the MySQL site (http://www.mysql.com) for a full accounting of the current MySQL licens- ing policy. Gilmore_11 12/5/00 10:24 AM Page 264 You can download the latest version of MySQL from one of the many world- wide mirrors. A complete listing of these mirrors is at http://www.mysql.com/downloads/mirrors.html. At the time of this writing the lat- est stable version of MySQL was 3.22.32, with version 3.23 in beta. It is in your best interest to always download the latest stable version. Go to the mirror closest to you and download the version that corresponds with your operating system plat- form. You’ll see links at the top of the page pointing to the most recent versions. Be sure to read through the entire page, as several OS-specific downloads are at the conclusion. The MySQL development team has done a great job putting together exten- sive documentation regarding the installation process. I recommend taking some time to thoroughly read through all general installation issues in addition to the information that applies to your operating system. Configuring MySQL After a successful installation, it is time to configure the MySQL server. This pro- cess largely consists of creating new databases and configuring the MySQL privi- lege tables. The privilege tables control the MySQL database access permissions. Correct configuration of these tables is pivotal to securing your database system, and therefore it is imperative that you fully understand the details of the privilege system before launching your site into a production environment. Although a chore to learn at first, the MySQL privilege tables are extremely easy to maintain once you understand them. A complete introduction to these tables is certainly out of the scope of this book. However, a number of resources available on the Web are geared toward bringing MySQL users up to speed. Check out the MySQL site (http://www.mysql.com) for further information. Once you have correctly installed and configured the MySQL distribution, it’s time to begin experimenting with Web-based databasing! The next section turns our attention towards exactly this matter, starting with an introduction of PHP’s MySQL functionality. Databases 265 Gilmore_11 12/5/00 10:24 AM Page 265 PHP’s Predefined MySQL Functions Once you have created and successfully tested the necessary permissions, you are ready to begin using the MySQL server. In this section, I introduce the predefined MySQL functions, enabling you to easily interface your PHP scripts with a MySQL server. Here is the general order of events that take place during the MySQL server communications process: 1. Establish a connection with the MySQL server. If the connection attempt fails, display an appropriate message and exit process. 2. Select a database on the MySQL server. If you cannot select the database, display an appropriate message and exit process. It’s possible to simulta- neously have several databases open for querying. 3. Perform necessary queries on selected database(s). 4. Once the querying is complete, close the database server connection. The example tables (products, customers, orders) in Figure 11-1 are used as the basis for the examples in the remainder of this section. If you would like to fol- low along with these examples, I suggest going back and creating them now. Alter- natively, make a copy of the pages so you do not have to continuously flip back and forth. With that said, let’s begin at the beginning, that is, how to connect to the MySQL database server. mysql_connect() The function mysql_connect() is used to establish an initial connection with the MySQL server. Once a successful connection is established, a database residing on that server can be selected. The syntax is: int mysql_connect([string hostname [:port] [:/path/to/socket] [, string username] [, string password]) The hostname is the name of the host as listed in the MySQL server privilege tables. Of course, it is also used to direct the request to the Web server hosting the MySQL server, since it is possible to connect to a remote MySQL server. An optional port number can be included along with the host, in addition to an optional path to a socket when a local host is specified. Both the username and password input parameters should correspond to the username and password, Chapter 11 266 Gilmore_11 12/5/00 10:24 AM Page 266 respectively, as specified in the MySQL server privilege tables. Note that all of the input parameters are optional, since the privilege tables can be loosely configured to accept a nonauthenticated connection. If the hostname parameter is empty, mysql_connect() attempts to connect to the local host. An example connection call follows: @mysql_connect("localhost", "web", "4tf9zzzf") or die("Could not connect to MySQL server!"); In this case, localhost is the server host, web is the username, and 4tf9zzzf is the password. The @ preceding the mysql_connect() function will suppress any error message that results from a failed attempt, instead producing the custom one specified in the die() call. Note that no value is returned from the mysql_con- nect() call. This is fine when there is only one MySQL server connection that will come into play. However, when connections are made to multiple MySQL servers on multiple hosts, a link ID must be generated so that subsequent commands can be directed to the intended MySQL server. For example: <? $link1 = @mysql_connect("www.somehost.com", "web", "abcde") or die("Could not connect to MySQL server!"); $link2 = @mysql_connect("www.someotherhost.com", "usr", "secret") or die("Could not connect to MySQL server!"); ?> Now, $link1 and $link2 can be called as needed in subsequent queries. You will soon learn exactly how these link IDs are used in queries to specify the intended server. mysql_select_db() Once a successful connection is established with the MySQL server, a database residing on that server can be selected. This is accomplished with mysql_select_db(). Its syntax is: int mysql_select_db (string database_name [, int link_id]) Databases 267 NOTE The function mysql_pconnect() offers persistent connection sup- port. In multiuser environments, mysql_pconnect() is recommended over mysql_connect() as a means for conserving system resources. The mysql_pconnect() input and return parameters are exactly the same as in mysql_connect(). Gilmore_11 12/5/00 10:24 AM Page 267 The input parameter database_name should be selected and assigned an iden- tification handle (returned by mysql_select_db()). Note that the input parameter link_id is optional. This is true only when just a single MySQL server connection is open. When multiple connections are open, link_id must be specified. An example of how a database is selected using mysq(_select_db() follows: <? @mysql_connect("localhost", "web", "4tf9zzzf") or die("Could not connect to MySQL server!"); @mysql_select_db("company") or die("Could not select company database!"); ?> If there is only one database selection, there is no need to return a database ID. However, as with mysql_connect(), when multiple databases are open, the database ID must be returned so there is a way to specify exactly which database you would like to perform a query on; otherwise the most recently opened link is used. mysql_close() Once you have finished querying the MySQL server, you should close the connec- tion. The function mysql_close() will close the connection corresponding to the optional input parameter link_id. If the link_id input parameter is not specified, mysql_close() will close the most recently opened link. The syntax is: int mysql_close ([int link_id]) An example of mysql_close() follows: <? @mysql_connect("localhost", "web", "4tf9zzzf") or die("Could not connect to MySQL server!"); @mysql_select_db("company") or die("Could not select company database!"); print "You're connected to a MySQL database!"; mysql_close(); ?> In the above example, there is no need to specify a link identifier, since only one open server connection exists when mysql_close() is called. Chapter 11 268 Gilmore_11 12/5/00 10:24 AM Page 268 mysql_query() The function mysql_query() provides the functional interface from which a data- base can be queried. Its syntax is: int mysql_query (string query [, int link_id]) The input parameter query corresponds to an SQL query. This query is sent either to the server connection corresponding to the last opened link or to the connection specified by the optional input parameter link_id. People often mistakenly think that the mysql_query() function returns the results of the query. This is not the case. Depending on the type of query, mysql_query() has different outcomes. In a successful SELECT SQL statement, a result ID is returned that can subsequently be passed to mysql_result() so the selected data can be formatted and displayed to the screen. If the query fails, FALSE is returned. The function mysql_result() is introduced later in this section. Furthermore, the number of rows that have been selected can be determined by executing mysql_num_rows(). This function is also introduced later in this section. In the case of SQL statements involving INSERT, UPDATE, REPLACE, or DELETE, the function mysql_affected_rows() can be called to determine how many rows were affected by the query. (The function mysql_affected_rows() is introduced next.) With that said, I will delay presenting an example until the mysql_result() and mysql_affected_rows() functions are introduced. mysql_affected_rows() It is often useful to return the number of rows affected by an SQL query involving an INSERT, UPDATE, REPLACE, or DELETE. This is accomplished with the func- tion mysql_affected_rows(). Its syntax is: int mysql_affected_rows ([int link_id]) Databases 269 NOTE It is not necessary to close database server connections opened by mysql_pconnect(). TIP If you are concerned that you are using up too much memory when making various query calls, call the predefined PHP function mysql_free_result(). This function, which takes as input the result_id returned from mysql_query(), will free up all memory associated with that query call. Gilmore_11 12/5/00 10:24 AM Page 269 Notice that the input parameter link_id is optional. If it is not included, mysql_affected_rows() attempts to use the last opened link_id. Consider the fol- lowing example: <? // connect to the server and select a database. @mysql_connect("localhost", "web", "4tf9zzzf") or die("Could not connect to MySQL server!"); @mysql_select_db("company") or die("Could not select company database!"); // declare query $query = "UPDATE products SET prod_name = \"cantaloupe\" WHERE prod_id = \"1001pr\""; // execute query $result = mysql_query($query); // determine the number of rows that have been affected. print "Total row updated: ".mysql_affected_rows(); mysql_close(); ?> Executing this code example returns this: Total rows updated: 1 This will not work for queries involving a SELECT statement. To determine the number of rows returned from a SELECT, use the function mysql_num_rows() instead. This function is introduced next. mysql_num_rows() The function mysql_num_rows() is used to determine the number of rows returned from a SELECT query statement. Its syntax is: int mysql_num_rows (int result) A usage example of mysql_num_rows() follows: Chapter 11 270 CAUTION There seems to be a quirk when using mysql_affected_rows() in one particular situation. If you execute a DELETE without a WHERE clause, mysql_affected_rows() will return 0. Gilmore_11 12/5/00 10:24 AM Page 270 <? @mysql_connect("localhost", "web", "4tf9zzzf") or die("Could not connect to MySQL server!"); @mysql_select_db("company") or die("Could not select company database!"); // select all product names where the product name begins with a 'p' $query = "SELECT prod_name FROM products WHERE prod_name LIKE \"p%\""; // execute the query $result = mysql_query($query); print "Total rows selected: ".mysql_num_rows($result); mysql_close(); ?> Since there is only one product name beginning with p (pears), only one row is selected. This is the result: Total rows selected: 1 mysql_result() The function mysql_result() is used in conjunction with mysql_query() (when a SELECT query is involved) to produce a data set. Its syntax is: int mysql_result (int result_id, int row [, mixed field]) The input parameter result_id refers to a value returned by mysql_query(). The parameter row refers to a particular row in the dataset specified by the result_id. Lastly, the optional input parameter field can be used to specify the following: • Field offset in the table. • Field name • Field name specified in dot format. Dot format is simply another way to specify the field name, specified as fieldname.tablename. Consider Listing 11-1, which makes use of the database displayed in Figure 11-1. Databases 271 Gilmore_11 12/5/00 10:24 AM Page 271 [...]... want to develop database-independent applications that can be layered on top of a potential client’s existing database infrastructure ODBC, an acronym for Open Database Connectivity, is an API (application programming interface) used to abstract the database interface calls, resulting in the ability to implement a single set of commands to interact with several different types of databases The advantageous... Management Database using Gilmore_11 12/5/00 10:24 AM Page 2 87 Databases the wizard Be sure to insert some information into a table and take note of that table name, as you will need it in a while! 2 Save the database somewhere on your computer 3 Now it’s time to make that Access database available using ODBC Go to Start -> Settings -> Control Panel You should see an icon entitled “ODBC Data Sources... for storing the data? Sure, a text file works when storing relatively small and simple pieces of data, but chances are you will need a database to implement any truly powerful Web application In this project, I explain how a MySQL database can be used to store information regarding Web sites These sites are separated into categories to allow for more efficient navigation Users can use an HTML form to. .. popular database solution due in large part to its user-friendly graphical interface It alone can be used as the database solution, or its graphical interface can be used as a front end to interface with other databases, such as MySQL or Microsoft’s SQL Server To illustrate the use of PHP s ODBC support, I’ll describe how you can connect to an MS Access database using PHP It is surprisingly easy and is a. .. great addition to your PHP programming repertoire, due to the popularity of Microsoft Access I’ll detail this process step by step: 1 286 Go ahead and create an Access database I’ll assume that you know how to do this already If you don’t, but still want to follow along with this example, just quickly create a database using the Access Wizard For this example, I created the predefined Contact Management... from a database Building a Search Engine While all of us are certainly familiar with using a Web-based search engine to retrieve data, how is one built? A simple search engine must be able to accept at least one keyword, which is then passed to a SQL query, which in turn polls the database for matches There are many ways that a search engine could format results (for example, by category or match consistency)... adding the possibility to allow multiple keywords, partial keywords, or automated suggestions for keywords not in the table, but with similar matches I’ll leave these features to your creativeness as a programming exercise 277 Gilmore_11 12/5/00 10:24 AM Page 278 Chapter 11 Building a Table Sorter It is particularly useful for users to be able to sort data as they wish when displaying database data... the category information as an integer After all, you want to use category names that are easily intelligible by the user, right? Don’t worry, as you will soon create an array in an initialization file that will be used to create integer -to- category name mappings This is useful because you may wish to modify or even delete a category in the future Doing so is considerably easier if you use an array mapping... collectively known as the Unified ODBC Functions, provide the typical ODBC support in addition to the ability to use these functions to access certain databases that have based their own API on the already existing ODBC API These database servers are listed in below: • Adabas D • IODBC • IBM DB2 • Solid • Sybase SQL Anywhere It is important to note that when using any of these databases, there is actually no ODBC... Management database that I created using the Access wizard However, before reviewing the script, take a look at the Contacts table in Figure 11-3, as seen in Access 2 87 Gilmore_11 12/5/00 10:24 AM Page 288 Chapter 11 Figure 11-3 Contacts table as seen in MS Access Now that you have an idea of what information will be extracted, take a look at the script If you are unfamiliar with any of the functions, please . shown: Order ID Customer ID Product ID Quantity 100 005 200 0cu 100 2pr 11 100 0 04 200 2cu 100 0pr 9 100 003 200 0cu 100 0pr 12 100 002 200 3cu 100 1pr 5 100 001 200 1cu 100 2pr 3 As you can see, this feature can prove. company database (Figure 11-1), the default table displayed by Listing 11-6 follows. Order ID Customer ID Product ID Quantity 100 003 200 0cu 100 0pr 12 100 005 200 0cu 100 2pr 11 100 0 04 200 2cu 100 0pr. 100 0pr 9 100 002 200 3cu 100 1pr 5 100 001 200 1cu 100 2pr 3 Notice that there are four links shown as table headers. Since Quantity is des- ignated as the default sorting attribute, the rows are sorted

Ngày đăng: 09/08/2014, 12:22

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan