Practical PHP and MySQL reflects Jono’s commitment to the spirit of making open source subjects accessible to everyone.. Although the tools you need to create Web content are readily ava
Trang 2Practical PHP
Trang 3N E G U S L I V E L I N U X S E R I E S
Your practical, hands-on guides to getting
real results with free software
Books in the Negus Live Linux Series encourage and challengeyou to advance in the free software world Boot the live DVD or
CD that comes with each book and watch the Linux system,applications, and content described in the book come to lifebefore your eyes
Start as a novice by trying out examples and finish as a sional, mastering the many topics covered in the series, frombuilding PHP/MySQL sites to customizing live CDs and more.When you are finished, you will know how to use, customize, andrebuild that free and open source software yourself
profes-Overseeing the series is Christopher Negus, bestselling author
of the Red Hat Linux Bible series, Linux Toys series, and the
signature book for this series, Live Linux CDs.
Trang 5Many of the designations used by manufacturers and sellers to distinguish their products are claimed
as trademarks Where those designations appear in this book, and the publisher was aware of a mark claim, the designations have been printed with initial capital letters or in all capitals.
trade-The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases
or special sales, which may include electronic versions and/or custom covers and content particular
to your business, training goals, marketing focus, and branding interests For more information, please contact:
U.S Corporate and Government Sales
Visit us on the Web: www.prenhallprofessional.com
Library of Congress Cataloging-in-Publication Data
All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise For information regarding permissions, write to:
Pearson Education, Inc.
Rights and Contracts Department
75 Arlington Street, Suite 300
Trang 6To my family for their never-ending support…
Trang 7This page intentionally left blank
Trang 8Contents
Foreword xi
About the Author xii
Acknowledgments xiii
Introduction 1
A Different Approach 1
What You Need to Use This Book 3
Conventions 4
Onward 4
CHAPTER 1 A New Approach 5
The Technology 6
How the Dynamic Web Works 8
Summary 12
CHAPTER 2 Getting Started with PHP and MySQL 15
Setting Up PHP and MySQL 16
Getting Started with PHP 17
Rolling in MySQL 35
Connecting to MySQL in PHP 45
Summary 51
Trang 9CHAPTER 3 Running the Projects 53
About the Disc 53
Running the Applications 56
Using XAMPP 57
Summary 60
CHAPTER 4 Building a Weblog 63
Project Overview: Blogtastic Use Case 64
Building the Database 65
Starting to Code 68
Viewing Specific Entries 82
Building the Category Browser 92
Don’t Just Let Anyone Log In 95
Rolling Your Own Categories 102
Creating New Blog Entries 103
Update a Blog Entry 106
Summary 110
CHAPTER 5 Discussion Forums 111
Under the Hood 111
Building Your Own Forums 114
Before You Begin 114
Creating the Database 115
Creating the Site Design 122
Displaying the Forums 124
Managing User Logins 133
Posts and Replies 150
Creating Administrator-Specific Pages 158
Summary 167
CHAPTER 6 Creating a Shopping Cart 169
Project Overview 170
Building the Database 171
Starting to Code 175
Managing User Logins 180
Displaying and Selecting Products 184
Checking It Out 196
Administrator Pages 208
Summary 216
viii Contents
Trang 10CHAPTER 7 Building an Online Auction Site 219
Project Overview 219
Building the Database 220
Starting to Code 223
Displaying Auction Items 226
Dealing with Users 240
Adding an Item 243
Processing Auctions 259
Scheduling the Page to Be Run 262
Summary 263
CHAPTER 8 Creating a Web-Based Calendar 265
Project Overview 265
Building the Database 266
Starting to Code 267
Viewing Events 277
Summary 302
CHAPTER 9 FAQ Content Management System 303
Project Overview 304
Building the Database 305
Starting to Code 310
Displaying Questions 321
Dealing with Logins 330
Adding and Moderating Questions 341
Managing Subjects 356
Managing Topics 360
Subject Ownership 364
Summary 376
CHAPTER 10 Building a Re-Usable Project 379
Project Overview 380
Building the Database 381
Using Directories Intelligently 385
Starting to Code: Building the Backbone 386
Downloading Releases 393
Viewing Screenshots 396
Available Projects Viewer 397
ix
Contents
Trang 11Administering Projects 398
Changing General Settings 406
Managing Downloads 407
Deleting Releases 414
Managing Screenshots 415
Deleting Images 419
Adding a New Project 420
Deploying the Application 421
Summary 424
CHAPTER 11 Building a News Web Site 425
Project Overview 425
Installing PEAR Packages 426
Building the Database 428
Starting to Code 431
Handling User Logins 440
Viewing and Rating Stories 445
Managing Stories 451
Managing Categories 457
Creating Your Search Engine 461
Summary 467
APPENDIX A Web Site Design 469
Project Overview 469
Laying Out the Site 471
Starting to Code 474
Start Building the Stylesheet 479
Formatting the Main <div> Items 481
Creating an About Page 487
Creating a Frequently Asked Questions Page 489
Formatting Tables 492
Summary 495
Index 499
x Contents
Trang 12Foreword
Listen to podcasts by Jono Bacon and friends at LUG Radio (www.lugradio.org) andyou get a sense of both the spirit and thoughtfulness Jono brings to the open sourcecommunity At one moment they speak seriously about hurdles in contributing code
to free software projects, while the next they offer a Monty Python-like discussion
on which Linux distribution each of them most resembles
Practical PHP and MySQL reflects Jono’s commitment to the spirit of making
open source subjects accessible to everyone The book carefully walks you throughthe code for eight useful, dynamic Web applications Projects are presented in aplayful way, like the forum project that touts horror movies that make you “hidebehind the couch.” And everything in the book can be run live, modified, saved,and reused from the included live CD
Although the tools you need to create Web content are readily available fromthe open source community, having a skillful guide like Jono Bacon to help you create dynamic Web applications from those tools is a real treat The results form afoundation for developing your own blogs, forums, shopping carts, and other Webdestinations that should significantly cut your startup time
I am thrilled to have Jono Bacon’s Practical PHP and MySQL as one of the first
books in the Negus Live Linux Series Its content perfectly suits the goals of the series to put quality free and open source software covering various topics intopeoples’ hands so they can quickly get high-quality results I hope you enjoy learn-ing from this book as much as I have
—Christopher Negus
Series Editor, Negus Live Linux Series
Trang 13About the Author
Jono Bacon works for Canonical as the Ubuntu community manager and is anestablished speaker, author, and regular contributor to the Open Source community
As an author, Bacon co-authored Linux Desktop Hacks and the Official Ubuntu
Book, and has written more than 400 published articles in more than 14
publica-tions Bacon has also contributed as a columnist for Linux Format, Linux User &
Developer, and PC Plus, and is an O’Reilly Network weblog author.
In addition, Bacon is a regular contributor to Open Source in a range of jects, a lead developer on the Jokosher (www.jokosher.org) project, and one of theco-founders of the popular LUGRadio (www.lugradio.org) podcast—a show withmore than 15,000 listeners and an annual event that pulls visitors from around theworld
Trang 14Acknowledgments
Writing thank-you lists is always hard, because I always end up leaving out one important I want to give thanks to the following people for their incredible sup-port and help:
some-Susan Curtis, John and Pauline Bacon, Simon and Martin Bacon,
Banger and Frankie, Prentice Hall (Debra Williams-Cauley, Songlin Qiu), LUGRadio (Stuart Langridge, Matthew Revell, Adrian Bradshaw),
OpenAdvantage (Paul Cooper, Elliot Smith, Scott Thompson), #php,
#mysql, and #lugradio on Freenode, the LUGRadio community,
Kai “Oswald” Seidler, and many more
Trang 15This page intentionally left blank
Trang 16Introduction
Everyone is going nuts about the Web Ever since we started getting creaky oldmodems installed in our homes and businesses, the Web has become an increas-ingly dominant part of our lives With it we explore, shop, diagnose, entertain,amuse, communicate, collaborate, and more The Web is no longer a novelty itemthat the few use to stretch their technical muscles; millions of people all over theworld are living their normal lives, with the Web playing a central role
The popularity of the Web means interesting things for developers such as you.The Web has not only presented a means to develop information-rich resourcessuch as IMDB, Wikipedia, and so on, but the Web also provides a real opportunity
to create online applications for doing everyday things, such as managing contacts,balancing accounts, selling products or services, creating content, expressing opin-ions, chatting, and much more A worldwide audience awaits, and if you have thetechnical chops, you can tap into this audience
This is where PHP and MySQL swirl into play In recent years, PHP andMySQL have come together to form a unique and awesomely powerful platform.With their roots in Open Source, these entirely free tools can be used to createhugely functional, stable, enterprise-class Web sites We can wax lyrical about PHPand MySQL later, so let’s talk about what this book can do for you
A D IFFERENT A PPROACH
If you walk into the vast majority of bookstores and look for programming books,they all use approximately the same format These books tend to progressively andlinearly ramble through the subject and present a series of facts This approach is
Trang 17not too dissimilar to learning at school, where you are trained to retain facts andskills, and it is up to you to apply those facts and skills to real-world scenarios.Well, that’s all very dull isn’t it? Whenever I want to learn something, I want todig in straight away and get at the core of the subject and its application When Ilearned to play guitar, I wanted to play songs, not learn music theory; when Ilearned to drive, I wanted to go places, not drive at 30 mph down a village road.This book takes exactly that approach Instead of teaching random programmingfacts, you get to roll up your sleeves and start writing applications straight away.This book starts with a brief introduction to the technology and then gives you aquick primer in core PHP and MySQL skills—just enough to get you started writ-ing an application After this short primer (because no one likes reading primers),you get straight into writing an application This way, you don’t have to wadethrough 200 pages of reading before you can get started writing an application.After the primer in Chapter 2, you get to the applications I have prepared amenu of applications for your esteemed delectation:
■ Chapter 3, “Running the Projects.” The Live CD that accompanies this bookcontains software projects, applications, and the LAMPP server This chapterprovides information about the CD contents and how you operate the disc onyour computer
■ Chapter 4, “Building a Weblog.” Plug into the weblog culture by creating aweblog system Here you can add posts, have your readers submit comments,create different categories, and much more
■ Chapter 5, “Discussion Forums.” Create a discussion forums Web site withall the bling of the circus You add forum categories, different forums,
threads and messages, user accounts, forum administration, and more
■ Chapter 6, “Creating a Shopping Cart.” Open an online shop with this ect, in which you add support for products, create a shopping cart, take pay-ment via checks/PayPal, support different accounts, and more
proj-■ Chapter 7, “Building an Online Auction Site.” Auction sites present an esting challenge, and in this chapter, you learn to support multiple accounts,write a bidding engine, support uploaded images, add auction summaries,and more
inter-■ Chapter 8, “Creating a Web-Based Calendar.” Don your orange sunglasses
and prepare to write the word Beta everywhere as you write an AJAX-driven
calendar Here you learn how AJAX works, create a calendar interface, port different events, set up user logins, and more
sup-2 Practical PHP and MySQL
Trang 18■ Chapter 9, “FAQ Content Management System.” In this chapter, you create aContent Management System (CMS) for FAQs Features include different
privilege levels for users, topic ownership, a submissions system, commentsupport, and more
■ Chapter 10, “Building a Re-Usable Project.” In this application, you create
an independent component that could be dropped into any Web site This isuseful if you want to create projects for other developers to download and
use This chapter discusses how to create a portable component and integrate
it into a separate site easily
■ Chapter 11, “Building a News Web Site.” This project solidifies much of theprevious knowledge in the book and also looks at categorization, search sup-port, and the use of the HTML_QuickForm PEAR extension
■ Appendix A, “Web Site Design.” In this chapter you create a static Web siteand add features such as a FAQ page and an About page, and design the
pages with Cascading Style Sheets (CSS)
As each project progresses, you learn more and more skills that are useful in awide variety of PHP and MySQL Web applications
W HAT Y OU N EED TO U SE T HIS B OOK
If you are keen to get started, all you need is an enthusiasm to learn and a computerrunning Linux, Windows, Mac OS X, or Solaris Each of these different operatingsystems supports PHP and MySQL, and as is explained later in the book, you canfast-track installation of the required software by using an awesome tool calledXAMPP
In addition to this core platform, it is recommended that you take plenty of time
to learn the different skills involved Learning to code is like baking a times it takes shorter or longer for concepts to bake in your head and solidify Con-cepts that may seem obvious to some take a little longer to sink in with others, andyou should allow yourself plenty of time to learn these different skills at your ownpace
cake—some-Finally, it is recommended that you have a look around the Internet and join up
on some of the PHP/MySQL discussion forums and mailing lists This will give you
a great support mechanism when you don’t understand certain concepts or needmore help
3
Introduction
Trang 19C ONVENTIONS
This book has a few different style conventions that are useful in helping youdevelop the applications Take a moment to get a quick understanding of theseconventions
First, there are some type conventions:
■ Monospaced text This style is used for technical items such as a command,keyword, or function
■ Italic text Italic text is used for words being defined and filenames.
Throughout the book, you will find literally hundreds of code snippets that areused to build your applications They look like this:
echo "hello world";
echo "this is extra code that has been added"
}
The bold line indicates a new line or a new section of code that is being added
to the snippet The non-bold text gives an easy way of double-checking that the newchunks of code are going in the right place
O NWARD
You are at the beginning of an exciting journey, and in the tradition of the rest of thebook, I don’t want to waste any of your time unnecessarily Sit down, plug yourself
in, and get ready to rock your world with PHP and MySQL Avast!
4 Practical PHP and MySQL
Trang 20One of the main reasons learning to code is so difficult is that code is typicallytaught in an unnatural way Most books and tutorials seem to follow a clear-cut path
of explaining the minor details of the language and then continuing to build uponeach detail to cover more complex concepts This kind of tuition is akin to cram-ming for exams—it is difficult to remember all of the separate bits of information inthe right order and how they relate to each other
This book is different Although most books follow the path just discussed, thisbook shakes up things and changes the recipe Instead of blinding you with 300pages of science, this book focuses primarily on a number of real-world projects,which you will write yourself These projects span a range of Web applications, and
by learning how to write these different applications, you will gain not only a betterunderstanding of PHP and MySQL, but also you will get a stronger sense of how to
write real applications.
The projects that you will work on in this book include the following:
■ Generic Web site
■ Weblog
■ Auction site
■ Shopping cart
■ Discussion forums
Trang 21■ Frequently Asked Questions (FAQ) management site
■ News site
■ Independent PHP application
■ Simple AJAX calendar
Each project provides the opportunity to learn new skills and focuses on cific challenges
spe-T HE T ECHNOLOGY
It should come as no surprise that the technology being used to build the Webapplications in this book uses PHP and MySQL If you picked up this book in theASP section of your bookstore, I am afraid someone has played a cruel joke on you.When put together, PHP and MySQL offer a compelling framework in whichyou can develop powerful and flexible Web applications The reason they work welltogether is that each provides a comprehensive part of the Web development toolkit
In building any Web application, the first thing you need is some form of language
in which to write dynamic pages and create features to handle dates, process data,connect to resources, manage users, and perform other tasks PHP steps up to solvethis problem PHP is an incredibly flexible language with a huge array of function-ality for solving common Web development challenges, many of which are covered
in the projects in this book The second requirement is to have somewhere to storethe oodles of data that you will be displaying, updating, removing, modifying, andotherwise showing off A solution for this challenge is to use a database, andMySQL provides a reliable and easy-to-use database that is well supported andflexible
Before looking at the architecture of how the Web works, however, this chapterexplores the tools of the trade in more detail
6 Practical PHP and MySQL
Trang 22Perl code with a C wrapper that added the capability to connect his Web pages to aMySQL database As his small project grew, he gave away his changes on the Inter-net as an Open Source project and cordially received improvements from other programmers with an interest in PHP The language was later renamed to the cur-rent recursive acronym PHP: Hypertext Preprocessor by Zeev Suraski and Andi Gutmans after they rewrote the parser in 1997 The software continued to developand now forms the comprehensive PHP platform we know today.
PHP provides a solid and well-defined programming language that includessupport for object-orientated programming, conditions, file handling, arithmetic,and more The language that PHP forms is similar in semantics to that of a shellscripting language combined with the easier bits of the C language
PHP subscribes to the batteries-included philosophy of programming guages and includes extensive support for a huge range of needs, such as cookies,forms, sessions, include files, network sockets, e-mail, LDAP, IRC, and more Data-base support covers not only MySQL but many others, including but not limited toPostgreSQL, Oracle, MS SQL, dBase, Sybase, and DB2 This flexible database sup-port is useful if you ever need to port your application to a different database
lan-In addition to PHP’s capability as a Web scripting language, PHP also can beused as a shell scripting language This means that you can use a single language towrite Web applications and create shell scripts to manage your computers You caneven use PHP for creating desktop applications Although this usage was typicallyone for the wiry-haired and zany part of the PHP demographic, more and moredevelopers are using it
PHP also extends its batteries-included philosophy and includes support forthird-party functionality via the PHP Extension and Application Repository(PEAR) library PEAR works in a similar fashion to Perl CPAN modules and pro-vides additional functionality that is easily available via a number of independentmodules built to solve specific problems These special modules can be included inyour application to access this special functionality easily For example, if you need
to send e-mail using your Web application, you can use the special PEAR mailfunctionality that extends the included PHP mail support This makes PHP better
at supporting third-party extensions and has resulted in a huge number of freelyavailable PEAR modules
MySQL
MySQL is a powerful and comprehensive relational database server, which wasoriginally developed by David Axmark, Allan Larsson, and Michael “Monty” Wide-nius The commercial company they founded, MySQL AB, develops and markets
7
CHAPTER 1 A New Approach
Trang 23MySQL and associated products Although the MySQL software originated as anOpen Source project, its creators were confident that they could run a businessusing the product as a base This business enables the developers to work full time
on the software, which in turn benefits both the Open Source community and mercial users of MySQL Both the open and commercial MySQL variants are func-tionally the same; the only difference in the software is how it is licensed.(Companies must buy a license if they want to deploy MySQL commercially in aclosed source application.) MySQL has enjoyed enormous popularity, and its cus-tomers include Yahoo! Finance, MP3.com, Motorola, NASA, Silicon Graphics, andTexas Instruments
com-MySQL is a full-featured database and uses open standards, such as the ANSISQL 99 standard, for communicating with databases with Structured Query Lan-guage (SQL) This standard provides a means to insert, update, and query informa-tion in the database by using an industry standard language This standardlanguage is used across database products, and like other products, MySQL sup-ports a number of additional SQL statements As well as being a standardized data-base, MySQL is also multi-platform This means that in addition to Linux, MySQLalso runs on other operating systems, such as Windows, Mac OS X, or BSD andUNIX variants
The database itself includes an interactive command-line client, which allowsyou to communicate with the server Although this client is useful, it’s a bit scary fornew users who are unfamiliar with command-line zen Fortunately, a number ofgraphical and Web-based clients can avoid the command-line encounter (Thisbook uses the Web-based phpMyAdmin client extensively.) MySQL also has sup-port for a number of programming languages to access and query the database Thisincludes languages such as PHP, Python, Perl, C, C++, and Java, among others.Although you may wish to initially use only PHP to query the database, multi-language support is useful if you need to write modules and applications in differ-ent languages in the future
H OW THE D YNAMIC W EB W ORKS
At its most fundamental level, the PHP and MySQL system provides a means toallow dynamic content to be distributed to a networked device This can be UncleBob connecting to your Web site, a delivery service connecting wirelessly to itstracking network, or you accessing your e-mail via the Web Each of these differentsolutions uses essentially the same software components that access each otherover different hardware contexts The technical description for the type of program-
ming you are engaging in with PHP and MySQL is called client/server development.
8 Practical PHP and MySQL
Trang 24To fully understand this concept, this chapter offers several examples and explainshow information is bounced between parts of the Web.
Imagine a Web site, any Web site Go on—be exciting and imagine you are anundercover spy who just so happens to have a Web site with your favorite spy-related stuff Assume that this Web site displays HTML code (the basic code that aWeb browser understands) and nothing else The page contains only a list of spy-related text, and there is no interactivity You simply connect to www.thewebaddress-ofthesite.com, and the Web site displays the information Figure 1-1 shows the kind
of interaction involved with this example
Figure 1-2 demonstrates the slightly more complex example of how an HTMLinput form works
Confirm
Send Form
Get Confirm Submit Form
Request Form
Web Browser Apache and
Trang 25to the client By following the direction of the arrows, you can see how the processworks and how information is sent between the client and the server.
The next example, shown in Figure 1-3, demonstrates what happens when youroll a database server into the mix In this case, you not only are filling in the formbut you want to store the contents of the form in the database For this to happen,you need to include one extra step when the Web site receives the contents of theform The Web site must send out a confirmation page and put the data in the data-base Because putting the data in the database is a one-way process, no two-wayarrow is included in this figure
The model shown in Figure 1-3 is virtually the same as before but with the extrastage added In addition to putting information into a database, you also need to beable to retrieve information from the database to display the results In Figure 1-4,you get the client to request a form, fill in the request details (such as a searchform), and then query the database for the results and return them to the client
10 Practical PHP and MySQL
Confirm Database
Send Form
Get Confirm Submit Form
Request Form
Web Browser Database Apache and
The client/server examples described here use a fairly loose definition of thedifferent components (such as the database, server, and browser) in the modelsshown The reason for this is so that you can concentrate on how data flows betweenthe different major parts of the client/server system
This last example (as shown in Figure 1-5) explains in detail how each stepworks in terms of these components
Trang 26CHAPTER 1 A New Approach
Database Apache and Web Browser
HTML Site
Find Data
Send Results Request Data
Send Form
Submit Form Request Form Send Results
FIGURE 1-4
This is a common situation—the user fills in a form and gets data from the database.
Database Apache and Web Browser
4. The Apache server receives the submitted form and loads the relevant file
to handle the form submission This file contains PHP code that is used to connect to the database This PHP code is passed to the PHP interpreter byApache and run by the interpreter PHP connects to the MySQL database
(which may be on the same computer or another one; it doesn’t matter