We present the relational database theory needed for developingsimple applications, and we cover many other basic concepts,including how to tell when a database is the method of choice t
Trang 1database-independent query API, are fully integrated into examples and thoroughly
described in the text In addition, through a complex sample application Hugh and
Dave's Wine Store all the important
Trang 2introduced Good design is emphasized, such
as dividing logic from presentation The book introduces PHP 5 and MySQL 4.1 features, while providing techniques that can be used
on older versions of the software that are still
in widespread use.
Trang 3By David Lane, Hugh E Williams
Trang 7
Section D.2 Hypertext Transfer Protocol
Appendix E Modeling and Designing Relational Databases Section E.1 The Relational Model
Section E.2 Entity-Relationship Modeling
Appendix F Managing Sessions in theDatabase Tier Section F.1 Using a Database to Keep State
Trang 8Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly & Associates books may be purchased for educational,business, or sales promotional use Online editions are also
available for most titles (http://safari.oreilly.com) For moreinformation, contact our corporate/institutional sales
Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and O'Reilly Media, Inc.was aware of a trademark claim, the designations have beenprinted in caps or initial caps
While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein
Trang 9There are lots of PHP and MySQL resources So why did we
decide to add this book to the market? We made the decisionafter we started teaching graduate students how to programwith PHP in 1999 We found that the PHP and MySQL manuals,
as well as most books, train people to use particular tools Butalmost no resources explained the principles of programmingfor the Web We realized that Web administrators and
programmers needed to know more than what PHP functions touse and how to write SQL queries That's where this book
comes in: it'll help you learn about web database development,
as well as understand the principles
This book explains what to do and why, along with how it's done
in PHP and MySQL You'll find information here that you won'tfind elsewhere Hopefully, you'll use this knowledge with
whatever web tools you choose in the future But you'll alsolearn about the breadth and depth of PHP and MySQL Whenyou finish this book, you'll be able to build an online store, aportal, or a content management system
Trang 10This book is for developers who want to build database
applications that are integrated with the Web We show you theprinciples and techniques for developing small- to medium-scaleweb database applications that store, manage, and retrieve
data The architecture we describe is a successful framework forapplications that can run on modest hardware and process
more than a million hits per day
We show you all of the critical tasks you need to know to buildsuccessful web software We cover programming fundamentalsfor the Web We show you the principles and practice of workingwith databases using the SQL query language We teach youabout tracking users with sessions, securing an application,
separating presentation from code, writing database-independent code, writing reports, adding error handling, andadvanced object-oriented and database topics
An important feature of this book is our case study, Hugh and
Dave's Online Wines It's a complete but fictional online retail
store that illustrates how most of the techniques described inthe book can be put together to build a real application Thewinestore application allows users to browse and search a
database of wines, add items to a shopping cart, manage theirmembership, and purchase wines It has all the basic security,user-tracking, and error-handling features of a real-world
application It features a medium-size database that we use inquerying examples throughout the book
We use Open Source software, and we show you how to use it
on Unix-based platforms such as Linux and Mac OS X, and
under Microsoft Windows 2000, 2003, and XP Our databaseserver is MySQL, a system known for its suitability to
applications that require speed but low resource overheads Ourscripting language is PHP, which is best known for its function
Trang 11Apache is our web server of choice, but most other web serverscan be used successfully with MySQL, PHP, and this book
Trang 12This book is about understanding and developing applicationlogic that brings databases and the Web together We introducedatabase systems over the course of the book, but our
discussions don't replace a book or class dedicated to relationaldatabase theory, or a book about a specific relational databasesystem such as MySQL Likewise, we assume you're alreadyfamiliar with the Web We don't delve deeply into the three keyweb protocols, HTML, HTTP, and TCP/IP
You don't need to know how to program to use this book, butyou do need to understand basic HTML Our introduction to PHPdoesn't assume you are familiar with web scripting or are a
programmer, but we do assume you understand the basic HTMLconstructs and are familiar with the popular web browsers Ifyou can use a text editor to author an HTML document that
contains a form and a table, you have sufficient HTML skills touse this book It's the principles of structure in the markup
process that are important, not the attractiveness or usability ofthe presentation in the web browser
You don't need a detailed understanding of relational databases
to use this book, but a working knowledge is helpful We
present the relational database theory needed for developingsimple applications, and we cover many other basic concepts,including how to tell when a database is the method of choice tostore data, the database query language SQL, and a case studythat models system requirements and converts the model to adatabase design This book isn't a substitute for the many goodresources on database theory However, it's enough to begindeveloping the underlying databases for many web databaseapplications
We briefly introduce web servers and networking in Chapter 1
and provide additional material in Appendix B Both web servers
Trang 13architecture of a web database application For many
applications, this is sufficient Likewise, we present sufficientdetail so that you will understand what networking and networkprotocol issues impact web database application design
Trang 14Introduces the PHP scripting language It covers
programming in PHP and discusses the basic programmingconstructs, variables, types, functions, and techniques
Chapter 3
Explains the intermediate level features of PHP, includinghow to work with arrays, strings, and times and dates Thechapter is illustrated with many short examples that showhow each technique is used in practice
Chapter 4
Trang 15features of PHP4 and PHP5, and explains why OO
programming is popular and becoming important in PHP Amore advanced discussion of the new OO features in PHP5
is presented in Chapter 14, but this chapter gives you allthe knowledge you need to work with the PEAR packagesthat are discussed in Chapter 7
Chapter 5
Introduces MySQL and how to interact with it using the SQLquery language The focus of the chapter is an example-driven section on querying, and we illustrate it using
examples from the online winestore's database We alsointroduce you to the basics of creating, deleting, and
updating data and databases A more advanced discussion
of the features of MySQL 4.1 is presented in Chapter 15,but the basics discussed in this chapter are sufficient foryou to work with all of the material up to Chapter 13 andwith the online wines case study in Chapter 17 to Chapter
We show how user data is encoded, sent in requests from aweb browser to a web server, and decoded for processing inPHP We discuss the security implications in processing userdata and show steps to secure interactive querying
Trang 16access, and this chapter shows you how to install and
upgrade them The chapter focuses on a templates
packagea useful tool for separating HTML from codeand
another for database abstraction Both packages are used inlater chapters to develop robust, reusable code
Chapter 8
Covers writing data to web databases There are severalreasons why writing data is different from reading it andthat's why it isn't discussed in Chapter 6 For example,
reloading or printing a page from a web browser can causedata to be written to a database more than once Multipleusers accessing the same database introduces other
problems, such as data unexpectedly being changed by oneuser while it's being read by another We discuss how tosolve problems related to the nature of the Web and
multiple users We illustrate the principles with a case studyexample of collecting form data from a user and saving it in
a database
Chapter 9
Trang 17principles and techniques for user input validation We showyou techniques such as how to validate dates, credit cardnumbers, and phone numbers, and explain how to use
these in error-checking modules that are scalable and
practical for web database applications We also introduceclient-side, browser-based JavaScript and show you how touse it for common tasks including user input validation inthe web browser
Chapter 10
Covers the principles of adding session management to webdatabase applications Session management allows the
interactions between a user and the application to be
related so that, for example, a user can log in and log out of
an application and be guided through a series of steps in aprocess We show how PHP manages sessions and illustratethe techniques with a case study of managing error
feedback to users We also discuss when and when not touse sessions, and how to configure PHP's session handler soit's secure and scalable
Chapter 11
Discusses web security and authentication We show howPHP can be used for basic authentication, how databasescan be used to manage users, and why you might need tosecure communications with the secure sockets layer (SSL).The case study is a reusable authentication module withlogin, logout, and password change features
Chapter 12 to Chapter 15 discuss tasks and techniques you'llneed when you're building a real-world application or deploying
Trang 18Chapter 12
Error handling and debugging are the focus of this chapter
We discuss the types of errors that can occur in PHP andshow you how to identify the source of common
programming errors that cause these problems We thenshow you how to write your own error handler that can beintegrated into an application, and how to trigger your ownerrors when you need them Adding a custom error handlergives a professional finish to an application
Chapter 13
Discusses reporting for the Web and what solutions work inPHP The focus is producing PDF (Adobe Portable DocumentFormat) reports using a popular PHP PDF library, and weillustrate the techniques with several examples The chapterconcludes with a function reference for the class we use
Chapter 14
This chapter shows you the advanced features of PHP5'sobject-oriented programming model We extend the
discussion in Chapter 4, and show you how to build andreuse classes, and how to write powerful OO applications.The chapter concludes with a case study that shows how all
of the features can be used together to build a complex andpowerful class hierarchy
Trang 19This chapter shows you the advanced features of MySQL4.1 It extends the discussion in Chapter 5, and shows youhow to write complex queries, manipulate data in complexways, manage users, and tune your database and MySQLserver
Chapter 16 to Chapter 20 present and outline the winestorecase study that shows how most of the techniques discussed inthe book are put together to build an application The outlinesaren't comprehensive: we assume you've read the book andunderstand the principles of developing web database
applications
Chapter 16
Explains the structure of the winestore application and
discusses how the principles shown in earlier chapters areput together to build a real-world application that is flexible,robust, secure, and scalable It also shows how the scriptswork together through figures and explanations We alsoexplain how we've developed classes and functions for
general-purpose tasks, and we list the code of all of thereusable components
Chapter 17
Presents the code for customer management in the
winestore We list the scripts for collecting, validating, andmodifying customer details, and show how new accountsare created
Trang 20Presents the code for the shopping cart at the winestore.The shopping cart is stored in a database and each user'scart is tracked using the session techniques from Chapter
10 The cart module allows a user to view her cart, add
items to the cart, update item quantities, delete items, andempty the cart
Chapter 19
Presents the code for the ordering and shipping modules ofthe winestore The ordering process shows how complexdatabase processing is used to convert a shopping cart into
a customer order We also show how to validate credit carddetails, send an email confirmation of the order to the user,and show the confirmation as an HTML page
Chapter 20
Concludes the winestore application by presenting the userauthentication and searching modules The user
authentication module is almost identical to the one in
Chapter 11 The searching and browsing module shows how
to develop a component that presents a large number ofresults in separate pages and how to use previous and nextfunctionality to move between the pages
There are eight appendixes to this book:
Appendix A
A guide to installing the Apache web server, PHP, and
Trang 21as software changes over time, so the latest version of thisappendix can be downloaded at
Appendix E
Contains a case study that models the system requirements
Trang 22modeling It shows how this model can be converted to adesign It also details the SQL statements used to createthe winestore database
Appendix F
An extension of Chapter 10, this appendix shows how thedefault PHP method for session handling (which uses diskfiles) can be moved into a database
Trang 23as they are presented
Chapter 2 and Chapter 5 are designed as introductions to PHPand SQL, respectively Read them both for an introduction tothe key tools, and before you read Chapter 6 and later
chapters Chapter 3 and Chapter 4 provide more detail on PHPand are structured by topic You can read them as tutorials oruse them as references for functions or concepts
Chapter 6 through Chapter 13 are tutorial-style chapters thatfollow through the principles and practice of web database
applications, and include annotated function references and
short case study examples to illustrate the concepts Chapter 6
through Chapter 11 describe the basic principles and
components and should be read sequentially When you've readthese chapters, you're ready to start building your own
applications If you're using MySQL 4.1, then after you've read
Chapter 6, read Appendix H for more information on PHP's newimproved MySQL function library
Chapter 12 introduces writing custom error handlers that willaid your debugging and add robustness to your application
Trang 2413, you should be a master of the principles of developing webdatabase applications
Chapter 14 and Chapter 15 contain advanced topics These rely
on concepts from the earlier chapters and give you completeskills for building sophisticated applications using advanced
programming and database techniques You can reserve theseoptional chapters for later, when you get interested in advancedweb development You don't need to read these chapters tounderstand our sample application in Chapter 16 to Chapter 20
Chapter 16 to Chapter 20 present and briefly discuss completescripts for the online winestore case study The scripts showhow the techniques from Chapter 2 to Chapter 12 are applied inpractice and, as such, are most useful after mastering the
content of the earlier chapters The material in these later
chapters is most useful when the example application has beendownloaded and installed on a local server, allowing the scripts
to be modified and tested as the chapters are read
Appendix D and Appendix E are also in a tutorial style We
recommend Appendix D if you are interested in or are
unfamiliar with the web environment and its underlying
protocols Appendix E
is a brief introduction to entity-relationship modeling for databases and shows the steps wetook in designing the winestore database We recommend
reading Appendix E after completing Chapter 5
Trang 25The following conventions are used in this book:
Italic
Used for program names, example URLs, and databaseentities, and for new terms when they are defined
Trang 26This icon designates a warning relating to the nearby text.
Trang 27distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Web Database Applications with PHP and MySQL,
Second Edition, by Hugh E Williams and David Lane Copyright
2004 O'Reilly Media, Inc., 0-596-00543-1."
If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at
permissions@oreilly.com
Trang 28Please address comments and questions concerning this book tothe publisher:
Trang 29Code examples from this book, data used to create the onlinewinestore database, and the completed winestore applicationcan be found at this book's web site,
http://www.webdatabasebook.com
Trang 30We thank our technical reviewers, Donal Ellis, Kimberlee
Jensen, Caryn-Amy King, S.M.M (Saied) Tahaghoghi, and HarryWilliams for their time, patience, and care in helping us improvethis book We also thank our editor, Andy Oram Most of what'snew and fresh about this edition exists because Andy's pushed,helped, and encouraged us to deliver the best book we could.Thanks Andy, it's been fun!
Hugh thanks Selina and Lucy Seline, thanks for being patientwhile I write, write, write Lucy, you're not quite as patient, butyou're lovely And to Mum and Dad for starting it all: thanksDad for building the Dick Smith 2650, and thanks Mum for
We acknowledge the support of our employer, RMIT University.Hugh thanks the School of Computer Science and InformationTechnology, and Dave thanks InQuirion Pty Ltd
Trang 31the Web
Most of the services we enjoy on the Web are provided by webdatabase applications Web-based email, online shopping,
forums and bulletin boards, corporate web sites, and sports andnews portals are all database-driven To build a modern website, you need to develop a database application
This book presents a highly popular, easy, low-cost way to bringtogether the Web and databases to build applications The mostpopular database management system used in these solutions
is MySQL, a very fast and easy-to-use system distributed under
an Open Source license by its manufacturer, MySQL AB Wediscuss MySQL in detail in this book
With a web server such as Apache (we assume Apache in thisbook, although the software discussed here works with otherweb servers as well) and MySQL, you have most of what youneed to develop a web database application The key glue youneed is a way for the web server to talk to the database; inother words, a way to incorporate database operations into webpages The most popular glue that accomplishes this task isPHP
PHP is an open source project of the Apache Software
Foundation and it's the most popular Apache web server add-onmodule, with around 53% of the Apache HTTP servers havingPHP capabilities.[1] PHP is particularly suited to web databaseapplications because of its integration tools for the Web anddatabase environments In particular, the flexibility of
embedding scripts in HTML pages permits easy integration ofHTML presentation and code The database tier integration
support is also excellent, with more than 15 libraries available
to interact with almost all popular database servers In this
Trang 32as PEAR
[1] From the Security Space web server survey, Apache module report,
http://www.securityspace.com/s_survey/data/index.html (1 December 2003).
Apache, MySQL, and PHP can run on a wide variety of operatingsystems In this book, we show you how to use them on Linux,Mac OS X, and Microsoft Windows
This is an introductory book, but it gives you the sophisticatedknowledge you need to build applications properly This includescritical tasks such as checking user input, handling errors
robustly, and locking your database operations to avoid datacorruption Most importantly, we explain the principles behindgood web database applications You'll finish the book with notonly the technical skills to create an application, but also anappreciation for the strategies that make an application secure,reliable, maintainable, and expandable
Trang 33Figure 1-1 A two-tier architecture where a web browser makes a request and the web server
responds
A web server is not sophisticated storage software Complicatedoperations on data, done by commercial sites and anyone elsepresenting lots of dynamic data, should be handled by a
separate database This leads to a more complex architecturewith three-tiers: the browser is still the client tier, the web
server becomes the middle tier, and the database is the third ordatabase tier Figure 1-2 shows how a web browser requests aresource that's generated from a database, and how the
Trang 34Figure 1-2 A three-tier architecture where a web browser requests a resource, and a response is
generated from a database
Trang 35This book shows you how to develop web database applications
that are built around the three-tier architecture model shown in
Figure 1-3 At the base of an application is the database tier, consisting of the database management system that manages
Trang 36applications can probably handle tens of thousands of requestsevery hour
For popular web sites, a common implementation is to installthe web server and the database server on different machines,
so that resources are dedicated to permit a more scalable andfaster application For very high-end applications, a cluster ofcomputers can be used, where the database and web serversare replicated and the load distributed across many machines.Our focus is on simple implementations; replication and loaddistribution are beyond the scope of this book
Describing web database applications as three-tier architecturesmakes them sound formally structured and organized However,
it hides the reality that the applications must bring togetherdifferent protocols and software, and that the software needs to
protocols and network that connect the client and middle tiers
of the application: it provides the connection between the webbrowser and the web server HTTP is one component that bindstogether the three-tier architecture
Trang 37HTTP allows resources to be communicated and shared over theWeb Most web servers and web browsers communicate usingthe current version, HTTP/1.1 A detailed knowledge of HTTPisn't necessary to understand the material in this book, but it'simportant to understand the problems HTTP presents for webdatabase applications (A longer introduction to the underlyingweb protocols can be found in Appendix D.)
Trang 38<head>
Trang 39type After a blank line, the resource itself follows, and we'veshown only the first few lines In this example the resource is
the requested HTML document, /~hugh/index.html.
1.2.2 State
Traditional database applications are stateful Users log in, run
related transactions, and then log out when they are finished.For example, in a bank application, a bank teller might log in,use the application through a series of menus as he serves
customer requests, and log out when he's finished for the day.The bank application has state: after the teller is logged in, hecan interact with the application in a structured way using
menus When the teller has logged out, he can no longer usethe application
HTTP is stateless Any interaction between a web browser and a
web server is independent of any other interaction Each HTTPrequest from a web browser includes the same header
information, such as the security credentials of the user, thetypes of pages the browser can accept, and instructions on how
to format the response The server processes the headers,
formulates a response that explains how the request was
Trang 40response
Statelessness has benefits: the most significant are the
resource savings from not having to maintain information at theweb server to track a user or requests, and the flexibility toallow users to move between unrelated pages or resources.However, because HTTP is stateless, it is difficult to developstateful web database applications: for example, it's hard toforce a user to follow menus or a series of steps to complete atask
To add state to HTTP, you need a method to impose informationflows and structure A common solution is to exchange a token
or key between a web browser and a web server that uniquely
identifies the user and her session Each time a browser
requests a resource, it presents the token, and each time theweb server responds, it returns the token to the web browser.The token is used by the middle-tier software to restore
information about a user from her previous request, such aswhich menu in the application she last accessed
Exchanging tokens allows stateful structure such as menus,steps, and workflow processes to be added to the application.They can also be used to prevent actions from happening morethan once, time out logins after a period of inactivity, and
control access to an application
1.2.3 Thickening the Client in the Three-Tier
Model
Given that a web database application built with a three-tierarchitecture doesn't fit naturally with HTTP, why use that model
at all? The answer mostly lies in the popularity and