this print for content only—size & color not accurate spine = 2.02" 1,080 page countBooks for professionals By professionals Beginning PHP and MySQL: From Novice to Professional, THird
Trang 1this print for content only—size & color not accurate spine = 2.02" 1,080 page count
Books for professionals By professionals
Beginning PHP and MySQL:
From Novice to Professional, THird EdiTioN
Dear Reader, PHP and MySQL have long ranked among the world’s most popular technologies for building powerful Web sites, and with little wonder Both offer developers
an amazing array of features, yet have managed to remain very approachable even to the most novice of developers In the latest edition of this bestselling book, you’ll learn all about PHP and MySQL, setting you along the path toward creating the Web site you’ve long dreamed about.
I begin with a vast overview of PHP’s capabilities, starting with a survey of the installation and configuration process on both the Windows and Linux platforms
Next, I devote several chapters to basic PHP concepts, including variables, datatypes, functions, string manipulation, object orientation, and user interaction
I also explain key concepts such as PEAR, session handling, the Smarty templating engine, Web services, and PDO You’ll also find a new chapter devoted to creating multilingual Web sites, and a new chapter that shows you how to create power- ful Web sites faster using the popular Zend Framework I’ve also updated the material to introduce key new features found in the PHP 6 release.
I then introduce many of MySQL’s key features, beginning by guiding you through MySQL’s installation and configuration process Next, you’ll learn about MySQL’s storage engines and datatypes, administration utilities, security features, and data import/export facilities I’ll also introduce you to several advanced features such as triggers, stored procedures, and views Along the way, you’ll gain insight into PHP’s ability to communicate with MySQL, and learn how to create and execute queries, perform searches, and carry out other key database tasks from within your Web site.
Beginning PHP and Oracle:
From Novice to Professional
9 781590 598627
5 4 6 9 9
Learn how to build dynamic, database-driven Web sites using two of the world’s most popular open source technologies.
IntroducesPHP 5andPHP 6!
THE APRESS ROADMAP
The Definitive Guide to MySQL, Third Edition
Beginning PHP and MySQL, Third Edition
Pro MySQL Pro PHP
PHP Objects, Patterns, and Practice, Second Edition
Beginning Joomla!
Practical Web 2.0 Applications with PHP
Visit the companion site at http://www.beginningphpandmysql.com/
Trang 3Beginning PHP and MySQL
From Novice to Professional, Third Edition
■ ■ ■
W Jason Gilmore
Trang 4Beginning PHP and MySQL: From Novice to Professional, Third Edition
Copyright © 2008 by W Jason Gilmore
All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-59059-862-7
ISBN-10 (pbk): 1-59059-862-8
ISBN-13 (electronic): 978-1-4302-0299-8
ISBN-10 (electronic): 1-4302-0299-8
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book Rather than use a trademark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
Lead Editor: Jonathan Gennick
Technical Reviewers: Jay Pipes and Matt Wade
Editorial Board: Clay Andres, Steve Anglin, Ewan Buckingham, Tony Campbell, Gary Cornell,
Jonathan Gennick, Kevin Goff, Matthew Moodie, Joseph Ottinger, Jeffrey Pepper, Frank Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Senior Project Manager: Tracy Brown Collins
Copy Editor: Bill McManus
Associate Production Director: Kari Brooks-Copony
Production Editor: Kelly Winquist
Compositor: Susan Glinert
Proofreader: Erin Poe
Indexer: John Collin
Artist: April Milne
Cover Designer: Kurt Krames
Manufacturing Director: Tom Debolski
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, or visit http://www.springeronline.com
For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA 94705 Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit http:// www.apress.com
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty Although every precaution has been taken in the preparation of this work, neither the author nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work
The source code for this book is available to readers at http://www.apress.com You will need to answer questions pertaining to this book in order to successfully download the code.
Trang 5This one is dedicated to you, Ruby!
Trang 6Contents at a Glance
About the Author xxvii
About the Technical Reviewers xxix
Acknowledgments xxxi
Introduction xxxiii
■ CHAPTER 1 Introducing PHP 1
■ CHAPTER 2 Configuring Your Environment 11
■ CHAPTER 3 PHP Basics 55
■ CHAPTER 4 Functions 113
■ CHAPTER 5 Arrays 127
■ CHAPTER 6 Object-Oriented PHP 163
■ CHAPTER 7 Advanced OOP Features 193
■ CHAPTER 8 Error and Exception Handling 213
■ CHAPTER 9 Strings and Regular Expressions 231
■ CHAPTER 10 Working with the File and Operating System 277
■ CHAPTER 11 PEAR 309
■ CHAPTER 12 Date and Time 323
■ CHAPTER 13 Forms 349
■ CHAPTER 14 Authenticating Your Users 365
■ CHAPTER 15 Handling File Uploads 387
■ CHAPTER 16 Networking 401
■ CHAPTER 17 PHP and LDAP 425
■ CHAPTER 18 Session Handlers 445
■ CHAPTER 19 Templating with Smarty 471
■ CHAPTER 20 Web Services 503
■ CHAPTER 21 Secure PHP Programming 539
Trang 7■ CHAPTER 22 SQLite 567
■ CHAPTER 23 Building Web Sites for the World 591
■ CHAPTER 24 MVC and the Zend Framework 601
■ CHAPTER 25 Introducing MySQL 621
■ CHAPTER 26 Installing and Configuring MySQL 635
■ CHAPTER 27 The Many MySQL Clients 663
■ CHAPTER 28 MySQL Storage Engines and Datatypes 693
■ CHAPTER 29 Securing MySQL 731
■ CHAPTER 30 Using PHP with MySQL 767
■ CHAPTER 31 Introducing PDO 793
■ CHAPTER 32 Stored Routines 819
■ CHAPTER 33 MySQL Triggers 849
■ CHAPTER 34 MySQL Views 863
■ CHAPTER 35 Practical Database Queries 879
■ CHAPTER 36 Indexes and Searching 907
■ CHAPTER 37 Transactions 925
■ CHAPTER 38 Importing and Exporting Data 939
■ INDEX 957
Trang 9Contents
About the Author xxvii
About the Technical Reviewers xxix
Acknowledgments xxxi
Introduction xxxiii
■ CHAPTER 1 Introducing PHP 1
History 2
PHP 4 3
PHP 5 4
PHP 6 5
General Language Features 7
Practicality 7
Power 8
Possibility 9
Price 9
Summary 10
■ CHAPTER 2 Configuring Your Environment 11
Installation Prerequisites 12
Downloading Apache 12
Downloading PHP 13
Obtaining the Documentation 14
Installing Apache and PHP on Linux 15
Installing Apache and PHP on Windows 17
Installing IIS and PHP on Windows 20
Installing IIS and PHP 21
Configuring FastCGI to Manage PHP Processes 22
Testing Your Installation 23
Configuring PHP 25
Configuring PHP at Build Time on Linux 25
Customizing the Windows Build 26
Contents
Trang 10Run-Time Configuration 27
Managing PHP’s Configuration Directives 27
PHP’s Configuration Directives 30
Choosing a Code Editor 48
Adobe Dreamweaver CS3 48
Notepad++ 49
PDT (PHP Development Tools) 49
Zend Studio 50
Choosing a Web Hosting Provider 50
Seven Questions for Any Prospective Hosting Provider 51
Summary 53
■ CHAPTER 3 PHP Basics 55
Embedding PHP Code in Your Web Pages 56
Default Syntax 56
Short-Tags 57
Script 58
ASP Style 58
Embedding Multiple Code Blocks 59
Commenting Your Code 59
Single-Line C++ Syntax 59
Shell Syntax 60
Multiple-Line C Syntax 60
Outputting Data to the Browser 61
The print() Statement 61
The printf() Statement 63
The sprintf() Statement 65
PHP’s Supported Datatypes 65
Scalar Datatypes 65
Compound Datatypes 67
Converting Between Datatypes Using Type Casting 69
Adapting Datatypes with Type Juggling 70
Type-Related Functions 71
Type Identifier Functions 72
Identifiers 73
Variables 73
Variable Declaration 74
Variable Scope 76
PHP’s Superglobal Variables 80
Variable Variables 86
Trang 11Constants 86
Expressions 87
Operands 87
Operators 88
String Interpolation 95
Double Quotes 95
Single Quotes 96
Heredoc 97
Control Structures 98
Conditional Statements 98
Looping Statements 101
File-Inclusion Statements 108
Summary 112
■ CHAPTER 4 Functions 113
Invoking a Function 113
Creating a Function 115
Passing Arguments by Value 115
Passing Arguments by Reference 117
Default Argument Values 118
Returning Values from a Function 119
Recursive Functions 121
Function Libraries 124
Summary 125
■ CHAPTER 5 Arrays 127
What Is an Array? 128
Creating an Array 129
Creating Arrays with array() 130
Extracting Arrays with list() 131
Populating Arrays with a Predefined Value Range 132
Testing for an Array 134
Adding and Removing Array Elements 134
Adding a Value to the Front of an Array 135
Adding a Value onto the End of an Array 135
Removing a Value from the Front of an Array 135
Removing a Value from the End of an Array 136
Trang 12Locating Array Elements 136
Searching an Array 136
Retrieving Array Keys 137
Retrieving Array Values 138
Traversing Arrays 138
Retrieving the Current Array Key 139
Retrieving the Current Array Value 139
Retrieving the Current Array Key and Value 140
Moving the Array Pointer 140
Passing Array Values to a Function 142
Determining Array Size and Uniqueness 143
Determining the Size of an Array 143
Counting Array Value Frequency 144
Determining Unique Array Values 145
Sorting Arrays 145
Reversing Array Element Order 146
Flipping Array Keys and Values 146
Sorting an Array 147
Merging, Slicing, Splicing, and Dissecting Arrays 153
Merging Arrays 153
Recursively Appending Arrays 154
Combining Two Arrays 155
Slicing an Array 155
Splicing an Array 156
Calculating an Array Intersection 157
Calculating Associative Array Intersections 158
Calculating Array Differences 159
Calculating Associative Array Differences 159
Other Useful Array Functions 160
Returning a Random Set of Keys 160
Shuffling Array Elements 160
Summary 162
■ CHAPTER 6 Object-Oriented PHP 163
The Benefits of OOP 164
Encapsulation 164
Inheritance 165
Polymorphism 166
Trang 13Key OOP Concepts 166
Classes 166
Objects 167
Fields 168
Properties 172
Constants 176
Methods 177
Constructors and Destructors 182
Constructors 182
Destructors 186
Static Class Members 187
The instanceof Keyword 189
Helper Functions 189
Autoloading Objects 191
Summary 192
■ CHAPTER 7 Advanced OOP Features 193
Advanced OOP Features Not Supported by PHP 194
Object Cloning 194
Cloning Example 195
The clone() Method 196
Inheritance 198
Class Inheritance 199
Inheritance and Constructors 201
Interfaces 203
Implementing a Single Interface 205
Implementing Multiple Interfaces 206
Abstract Classes 207
Introducing Namespaces 208
Summary 211
■ CHAPTER 8 Error and Exception Handling 213
Configuration Directives 214
Error Logging 217
Exception Handling 221
Why Exception Handling Is Handy 221
PHP’s Exception-Handling Implementation 223
Summary 229
Trang 14■ CHAPTER 9 Strings and Regular Expressions 231
Regular Expressions 232
Regular Expression Syntax (POSIX) 232
PHP’s Regular Expression Functions (POSIX Extended) 235
Regular Expression Syntax (Perl) 239
Other String-Specific Functions 248
Determining the Length of a String 249
Comparing Two Strings 249
Manipulating String Case 252
Converting Strings to and from HTML 254
Alternatives for Regular Expression Functions 260
Padding and Stripping a String 269
Counting Characters and Words 271
Taking Advantage of PEAR: Validate_US 274
Installing Validate_US 274
Using Validate_US 275
Summary 276
■ CHAPTER 10 Working with the File and Operating System 277
Learning About Files and Directories 278
Parsing Directory Paths 278
Calculating File, Directory, and Disk Sizes 281
Determining Access and Modification Times 284
Working with Files 286
The Concept of a Resource 286
Recognizing Newline Characters 287
Recognizing the End-of-File Character 287
Opening and Closing a File 287
Reading from a File 289
Writing a String to a File 297
Moving the File Pointer 298
Reading Directory Contents 299
Executing Shell Commands 301
System-Level Program Execution 303
Sanitizing the Input 303
PHP’s Program Execution Functions 305
Summary 308
Trang 15■ CHAPTER 11 PEAR 309
Popular PEAR Packages 310
Preinstalled Packages 310
Installer-Suggested Packages 310
The Power of PEAR: Converting Numeral Formats 312
Installing and Updating PEAR 313
Installing PEAR 313
PEAR and Hosting Companies 315
Updating PEAR 315
Using the PEAR Package Manager 316
Viewing an Installed PEAR Package 316
Learning More About an Installed PEAR Package 317
Installing a PEAR Package 318
Including a Package Within Your Scripts 320
Upgrading Packages 320
Uninstalling a Package 322
Downgrading a Package 322
Summary 322
■ CHAPTER 12 Date and Time 323
The Unix Timestamp 323
PHP’s Date and Time Library 324
Validating Dates 325
Formatting Dates and Times 325
Converting a Timestamp to User-Friendly Values 330
Working with Timestamps 331
Date Fu 333
Displaying the Localized Date and Time 334
Displaying the Web Page’s Most Recent Modification Date 338
Determining the Number of Days in the Current Month 339
Determining the Number of Days in Any Given Month 339
Calculating the Date X Days from the Present Date 340
Taking Advantage of PEAR: Creating a Calendar 341
Date and Time Enhancements for PHP 5.1+ Users 345
Introducing the DateTime Constructor 345
Formatting Dates 346
Setting the Date After Instantiation 346
Setting the Time After Instantiation 347
Modifying Dates and Times 347
Summary 348
Trang 16■ CHAPTER 13 Forms 349
PHP and Web Forms 349
A Simple Example 351
Passing Form Data to a Function 352
Working with Multivalued Form Components 354
Taking Advantage of PEAR: HTML_QuickForm 355
Installing HTML_QuickForm 356
Creating a Simple Form 356
Using Auto-Completion 363
Summary 364
■ CHAPTER 14 Authenticating Your Users 365
HTTP Authentication Concepts 366
PHP Authentication 367
Authentication Variables 367
Useful Functions 368
PHP Authentication Methodologies 370
Hard-Coded Authentication 370
File-based Authentication 371
Database-based Authentication 373
IP-based Authentication 375
Taking Advantage of PEAR: Auth_HTTP 377
User Login Administration 380
Testing Password Guessability with the CrackLib Library 380
One-Time URLs and Password Recovery 383
Summary 386
■ CHAPTER 15 Handling File Uploads 387
Uploading Files via HTTP 387
Uploading Files with PHP 388
PHP’s File Upload/Resource Directives 389
The $_FILES Array 390
PHP’s File-Upload Functions 391
Upload Error Messages 393
A Simple Example 394
Trang 17Taking Advantage of PEAR: HTTP_Upload 395
Installing HTTP_Upload 395
Uploading a File 396
Learning More About an Uploaded File 397
Uploading Multiple Files 398
Summary 399
■ CHAPTER 16 Networking 401
DNS, Services, and Servers 402
DNS 402
Services 407
Establishing Socket Connections 408
Mail 411
Configuration Directives 411
Sending E-mail Using a PHP Script 412
Common Networking Tasks 418
Pinging a Server 418
Creating a Port Scanner 419
Creating a Subnet Converter 420
Testing User Bandwidth 422
Summary 424
■ CHAPTER 17 PHP and LDAP 425
Using LDAP from PHP 427
Connecting to an LDAP Server 427
Retrieving LDAP Data 430
Counting Retrieved Entries 435
Sorting LDAP Records 435
Inserting LDAP Data 436
Updating LDAP Data 438
Deleting LDAP Data 438
Working with the Distinguished Name 440
Error Handling 441
Summary 443
Trang 18■ CHAPTER 18 Session Handlers 445
What Is Session Handling? 445
The Session-Handling Process 447
Configuration Directives 448
Managing the Session Storage Media 448
Setting the Session Files Path 449
Automatically Enabling Sessions 449
Setting the Session Name 450
Choosing Cookies or URL Rewriting 450
Automating URL Rewriting 450
Setting the Session Cookie Lifetime 451
Setting the Session Cookie’s Valid URL Path 451
Setting Caching Directions for Session-Enabled Pages 452
Working with Sessions 453
Starting a Session 453
Destroying a Session 454
Setting and Retrieving the Session ID 454
Creating and Deleting Session Variables 455
Encoding and Decoding Session Data 456
Practical Session-Handling Examples 458
Automatically Logging In Returning Users 459
Generating a Recently Viewed Document Index 461
Creating Custom Session Handlers 462
Tying Custom Session Functions into PHP’s Logic 463
Using Custom MySQL-Based Session Handlers 464
Summary 469
■ CHAPTER 19 Templating with Smarty 471
What’s a Templating Engine? 472
Introducing Smarty 474
Installing Smarty 475
Using Smarty 477
Smarty’s Presentational Logic 479
Comments 480
Variable Modifiers 480
Control Structures 484
Statements 490
Creating Configuration Files 493
config_load 494
Referencing Configuration Variables 494
Trang 19Using CSS in Conjunction with Smarty 495
Caching 497
Working with the Cache Lifetime 498
Eliminating Processing Overhead with is_cached() 499
Creating Multiple Caches per Template 499
Some Final Words About Caching 501
Summary 501
■ CHAPTER 20 Web Services 503
Why Web Services? 504
Really Simple Syndication 506
Understanding RSS Syntax 509
Introducing MagpieRSS 510
SimpleXML 519
Loading XML 520
Parsing XML 523
SOAP 526
Introducing SOAP Messages 527
Introducing PHP’s SOAP Extension 528
Summary 537
■ CHAPTER 21 Secure PHP Programming 539
Configuring PHP Securely 540
Safe Mode 540
Other Security-Related Configuration Parameters 543
Hiding Configuration Details 546
Hiding Apache 546
Hiding PHP 547
Hiding Sensitive Data 549
Hiding the Document Root 549
Denying Access to Certain File Extensions 550
Sanitizing User Data 550
File Deletion 550
Cross-Site Scripting 551
Sanitizing User Input: The Solution 553
Taking Advantage of PEAR: Validate 556
Data Encryption 559
PHP’s Encryption Functions 559
The MCrypt Package 562
Summary 565
Trang 20■ CHAPTER 22 SQLite 567
Introduction to SQLite 567
Installing SQLite 568
Using the SQLite Command-Line Interface 569
PHP’s SQLite Library 571
sqlite.assoc_case = 0 | 1 | 2 571
Opening a Connection 571
Creating a Table in Memory 573
Closing a Connection 573
Querying a Database 574
Parsing Result Sets 576
Retrieving Result Set Details 580
Manipulating the Result Set Pointer 582
Retrieving a Table’s Column Types 585
Working with Binary Data 585
Creating and Overriding SQLite Functions 587
Creating Aggregate Functions 589
Summary 590
■ CHAPTER 23 Building Web Sites for the World 591
Translating Web Sites with Gettext 592
Step 1: Update the Web Site Scripts 592
Step 2: Create the Localization Repository 594
Step 3: Create the Translation Files 595
Step 4: Translate the Text 596
Step 5: Generate Binary Files 597
Step 6: Set the Desired Language Within Your Scripts 597
Localizing Dates, Numbers, and Times 598
Summary 600
■ CHAPTER 24 MVC and the Zend Framework 601
Introducing MVC 601
PHP’s Framework Solutions 605
The CakePHP Framework 605
The Solar Framework 606
The symfony Framework 606
The Zend Framework 607
Trang 21Introducing the Zend Framework 607
Downloading and Installing the Zend Framework 609
Creating Your First Zend Framework–Driven Web Site 610
Searching the Web with Zend_Service_Yahoo 617
Summary 620
■ CHAPTER 25 Introducing MySQL 621
What Makes MySQL So Popular? 622
Flexibility 622
Power 623
Flexible Licensing Options 626
A (Hyper) Active User Community 627
The Evolution of MySQL 628
MySQL 4 628
MySQL 5.0 629
MySQL 5.1 630
Prominent MySQL Users 631
craigslist 631
Wikipedia 632
Yahoo! Finance 632
Summary 633
■ CHAPTER 26 Installing and Configuring MySQL 635
Downloading MySQL 636
Downloading MySQL for Windows 636
Installing MySQL 636
Installing MySQL on Linux 637
Installing and Configuring MySQL on Windows 642
Setting the MySQL Administrator Password 645
Starting and Stopping MySQL 646
Controlling the Daemon Manually 646
Starting and Stopping MySQL Automatically 648
Configuring and Optimizing MySQL 652
The mysqld_safe Wrapper 652
MySQL’s Configuration and Optimization Parameters 653
The my.cnf File 657
Configuring PHP to Work with MySQL 661
Reconfiguring PHP on Linux 661
Reconfiguring PHP on Windows 661
Summary 662
Trang 22■ CHAPTER 27 The Many MySQL Clients 663
Introducing the Command-Line Clients 663 The mysql Client 663The mysqladmin Client 676 Other Useful Clients 678Client Options 683MySQL’s GUI Client Programs 686Installing GUI Tools 687MySQL Administrator 687MySQL Query Browser 688MySQL Migration Toolkit 690 phpMyAdmin 691Summary 692
■ CHAPTER 28 MySQL Storage Engines and Datatypes 693
Storage Engines 693 MyISAM 695 InnoDB 698MEMORY 699MERGE 700FEDERATED 701ARCHIVE 703 CSV 703EXAMPLE 704BLACKHOLE 704Storage Engine FAQ 705 Datatypes and Attributes 706 Datatypes 707 Datatype Attributes 714Working with Databases and Tables 718Working with Databases 718Working with Tables 720 Altering a Table Structure 724The INFORMATION_SCHEMA 725 Summary 728
■ CHAPTER 29 Securing MySQL 731
What You Should Do First 732Securing the mysqld Daemon 734
301dec1fa5e91e80bc32cf05b48566eb
Trang 23The MySQL Access Privilege System 734How the Privilege System Works 735Where Is Access Information Stored? 738 User and Privilege Management 750Creating Users 750 Deleting Users 751Renaming Users 751 The GRANT and REVOKE Commands 752Reviewing Privileges 759 Limiting User Resources 759Secure MySQL Connections 760Grant Options 761SSL Options 762Starting the SSL-Enabled MySQL Server 764Connecting Using an SSL-Enabled Client 764Storing SSL Options in the my.cnf File 764 Summary 765
■ CHAPTER 30 Using PHP with MySQL 767
Handling Installation Prerequisites 768 Enabling the mysqli Extension on Linux/Unix 769Enabling the mysqli Extension on Windows 769 Managing User Privileges 769Working with Sample Data 769Using the mysqli Extension 770 Setting Up and Tearing Down the Connection 770 Handling Connection Errors 772Retrieving Error Information 772Storing Connection Information in a Separate File 774 Securing Your Connection Information 775 Interacting with the Database 775Sending a Query to the Database 775Parsing Query Results 779Determining the Rows Selected and Rows Affected 781Working with Prepared Statements 782Executing Database Transactions 790 Enabling Autocommit Mode 790 Committing a Transaction 790 Rolling Back a Transaction 790Summary 791
Trang 24■ CHAPTER 31 Introducing PDO 793
Another Database Abstraction Layer? 795 Using PDO 796 Installing PDO 796 PDO’s Database Options 797Connecting to a Database Server and Selecting a Database 798 Handling Errors 802Getting and Setting Attributes 804Executing Queries 805Introducing Prepared Statements 807Retrieving Data 811 Setting Bound Columns 815 Working with Transactions 816Summary 817
■ CHAPTER 32 Stored Routines 819
Should You Use Stored Routines? 820 Stored Routine Advantages 820Stored Routine Disadvantages 820How MySQL Implements Stored Routines 821Stored Routine Privilege Tables 822Creating a Stored Routine 824 Declaring and Setting Variables 828Executing a Stored Routine 830Creating and Using Multistatement Stored Routines 830Calling a Routine from Within Another Routine 840Modifying a Stored Routine 841Deleting a Stored Routine 841Viewing a Routine’s Status 841Viewing a Routine’s Creation Syntax 843Handling Conditions 844 Integrating Routines into Web Applications 845Creating the Employee Bonus Interface 845Retrieving Multiple Rows 846Summary 847
Trang 25■ CHAPTER 33 MySQL Triggers 849
Introducing Triggers 849Why Use Triggers? 850 Taking Action Before an Event 850Taking Action After an Event 851Before Triggers vs After Triggers 852 MySQL’s Trigger Support 853 Creating a Trigger 854Viewing Existing Triggers 856 Modifying a Trigger 859Deleting a Trigger 859Integrating Triggers into Web Applications 859Summary 861
■ CHAPTER 34 MySQL Views 863
Introducing Views 864MySQL’s View Support 865 Creating and Executing Views 865Viewing View Information 872Modifying a View 874 Deleting a View 875Updating Views 875Incorporating Views into Web Applications 876 Summary 878
■ CHAPTER 35 Practical Database Queries 879
Sample Data 880 Creating Tabular Output with PEAR 880Installing HTML_Table 881 Creating a Simple Table 882Creating More Readable Row Output 884Creating a Table from Database Data 885Generalizing the Output Process 887Sorting Output 890Creating Paged Output 892
Trang 26Listing Page Numbers 895Querying Multiple Tables with Subqueries 897Performing Comparisons with Subqueries 899Determining Existence with Subqueries 899Performing Database Maintenance with Subqueries 901 Using Subqueries with PHP 901Iterating Result Sets with Cursors 902 Cursor Basics 903Creating a Cursor 904Opening a Cursor 904Using a Cursor 904 Closing a Cursor 906 Using Cursors with PHP 906Summary 906
■ CHAPTER 36 Indexes and Searching 907
Database Indexing 907Primary Key Indexes 908 Unique Indexes 910 Normal Indexes 911Full-Text Indexes 913Indexing Best Practices 918 Forms-Based Searches 919 Performing a Simple Search 919 Extending Search Capabilities 921Performing a Full-Text Search 923Summary 924
■ CHAPTER 37 Transactions 925
What’s a Transaction? 925 MySQL’s Transactional Capabilities 926 System Requirements 927Table Creation 927
A Sample Project 928Creating Tables and Adding Sample Data 929Executing an Example Transaction 930 Backing Up and Restoring InnoDB Tables 932 Usage Tips 933
Trang 27Building Transactional Applications with PHP 933The Swap Meet Revisited 934Summary 937
■ CHAPTER 38 Importing and Exporting Data 939
Sample Table 940Using Data Delimitation 940 Importing Data 941Importing Data with LOAD DATA INFILE 941Importing Data with mysqlimport 946Loading Table Data with PHP 950Exporting Data 951 SELECT INTO OUTFILE 951 Summary 955
■ INDEX 957
Trang 29About the Author
■W JASON GILMORE is a Columbus, Ohio–based developer, consultant, writer, and
editor He’s co-founder of IT Enlightenment (http://www.itenlightenment.com/) and the CodeMash conference (http://www.codemash.org), and is a member of the 2008
MySQL Conference speaker selection board In his previous capacity as Apress’s open
source editor, he fostered the development of more than 60 books, along the way
helping to transform Apress’s open source line into one of the industry’s most respected publishing programs
Jason has more than 100 articles to his credit within prominent publications such
as Developer.com, Linux Magazine, and TechTarget He’s the author of several books, including the best-selling Beginning PHP and MySQL: From Novice to Professional,
Beginning PHP and PostgreSQL 8: From Novice to Professional, and Beginning PHP
and Oracle: From Novice to Professional
Away from the laptop you’ll find Jason starting more home-remodeling projects
than he could possibly complete, tickling the ivories, playing chess, and reading up on
military history Contact Jason at wj@wjgilmore.com, and be sure to visit his Web site
at http://www.wjgilmore.com
Trang 31About the
Technical Reviewers
■JAY PIPES is the North American Community Relations Manager at MySQL Coauthor
of Pro MySQL (Apress, 2005), Jay has also written articles for Linux Magazine and
regularly assists software developers in identifying how to make the most effective use
of MySQL He has given sessions on performance tuning at the MySQL Users
Confer-ence, RedHat Summit, NY PHP ConferConfer-ence, php|tek, OSCON, and Ohio LinuxFest,
among others He lives in Columbus, Ohio, with his wife, Julie, and his four animals
In his abundant free time, when not being pestered by his two needy cats and two
noisy dogs, he daydreams in PHP code and ponders the ramifications of clone()
■MATT WADE is a programmer, database developer, and system administrator He
currently works for a large financial firm by day and freelances by night He has
experience programming in several languages, though he most commonly utilizes
PHP and C On the database side of things, he regularly uses MySQL and Microsoft
SQL Server As an accomplished system administrator, he regularly has to maintain
Windows servers and Linux boxes and prefers to deal with FreeBSD
Matt resides in Jacksonville, Florida, with his wife, Michelle, and their three children,
Matthew, Jonathan, and Amanda When not working, Matt can be found fishing, doing
something at his church, or playing some video game Matt was the founder of
Codewalkers.com, a leading resource for PHP developers, and ran the site until 2007
Trang 33Acknowledgments
Back in 2000, Gary Cornell, co-founder of a small but ambitious computer publisher
called Apress, contacted me and asked whether I’d be interested in writing a book about
PHP At the time a developer and aspiring technical writer, I jumped at the opportunity,
albeit wondering how I’d ever be able to finish such a large writing project Like running
a first marathon, success was gauged by way of mere completion rather than by any
other benchmark
Eight years have since passed, and that original book is still alive and kicking, its
current incarnation being what you hold in your hands Suffice it to say this project
has exceeded my wildest expectations, and I thank Gary and Apress (now a much
larger but still ambitious publisher) profusely for the opportunity
I’d also like to thank my project manager Tracy Brown Collins for her infinite patience and organizational talents Technical reviewers Jay Pipes and Matt Wade offered valuable insight that greatly improved the material Copy editor Bill McManus once again proved
his keen ability to turn my jabbering into coherent English All other members of the
Apress team also deserve a hand for all of the hard work behind the scenes
Last but certainly not least, I’d like to thank my family and friends for reminding
me there is indeed life beyond the keyboard
Trang 35Introduction
Most great programming books sway far more toward the realm of the practical
than of the academic Although I have no illusions regarding my place among the
great technical authors of our time, it is always my goal to write with this point in
mind, producing material that you can apply to your own situation Given the size
of this book, it’s probably apparent that I attempted to squeeze out every last drop of
such practicality from the subject matter That said, if you’re interested in gaining
practical and comprehensive insight into the PHP programming language and MySQL
database server, and how these prominent technologies can be used together to create
dynamic, database-driven Web applications, this book is for you
The feverish work of the respective PHP and MySQL communities prompted this
new edition, and with it considerable changes over the previous edition In addition
to updating the material to reflect features found in PHP 6 and the latest MySQL releases,
two new chapters have been added Chapter 23 shows you how to create Web sites for
the world by taking advantage of open source internationalization and localization
tools Chapter 24 introduces the popular Zend Framework, a great solution for building
powerful Web applications Furthermore, all existing chapters have been carefully
revised, and in some cases heavily modified, to both update and improve upon the
previous edition’s material
If you’re new to PHP, I recommend beginning with Chapter 1, because gaining the
fundamental knowledge presented therein will be of considerable benefit to you when
you’re reading later chapters If you know PHP but are new to MySQL, consider
begin-ning with Chapter 25 Intermediate and advanced readers are invited to jump around
as necessary; after all, this isn’t a romance novel Regardless of your reading strategy,
I’ve attempted to compartmentalize the material found in each chapter so that you
can quickly learn each topic without having to necessarily master other chapters beyond those that concentrate on the technology fundamentals
Furthermore, novices and seasoned PHP and MySQL developers alike have
some-thing to gain from this book, as I’ve intentionally organized it in a hybrid format of
both tutorial and reference I appreciate the fact that you have traded hard-earned
cash for this book, and therefore have strived to present the material in a fashion that
will prove useful not only the first few times you peruse it, but far into the future
Trang 36Download the Code
Experimenting with the code found in this book is the most efficient way to best stand the concepts presented within For your convenience, a zip file containing all of the examples can be downloaded from http://www.apress.com
under-Contact Me!
I love reader e-mail, and invite you to contact me with comments, suggestions, and questions Feel free to e-mail me at jason@wjgilmore.com Also be sure to regularly check http://www.beginningphpandmysql.com for errata, code, and other updates
Trang 37■ ■ ■
Introducing PHP
In many ways the PHP language is representative of the stereotypical open source
project, created to meet a developer’s otherwise unmet needs and refined over time
to meet the needs of its growing community As a budding PHP developer, it’s important
you possess some insight into how the language has progressed, as it will help you
to understand the language’s strengths, and to some extent the reasoning behind its
occasional idiosyncrasies
Additionally, because the language is so popular, having some understanding of the
differences between the versions—most notably versions 4, 5, and 6—will help when
evaluating Web hosting providers and PHP-driven applications for your own needs
To help you quickly get up to speed in this regard, this chapter will get you acquainted
with PHP’s features and version-specific differences By the conclusion of this chapter,
you’ll learn the following:
• How a Canadian developer’s Web page traffic counter spawned one of the world’s
most popular scripting languages
• What PHP’s developers did to reinvent the language, making version 5 the best
yet released
• Why PHP 6 is going to further propel PHP’s adoption in the enterprise
• Which features of PHP attract both new and expert programmers alike
■ Note At the time of publication, PHP 6 was still a beta release, although many of the features are
stable enough that they can safely be discussed throughout the course of the book But be forewarned;
some of these features could change before the final version is released
Trang 38The clamor for the PHP toolset prompted Lerdorf to continue developing the language, with perhaps the most notable early change being a new feature for converting data entered in an HTML form into symbolic variables, encouraging exportation into other systems To accomplish this, he opted to continue development in C code rather than Perl Ongoing additions to the PHP toolset culminated in November 1997 with the release of PHP 2.0, or Personal Home Page/Form Interpreter (PHP/FI) As a result
of PHP’s rising popularity, the 2.0 release was accompanied by a number of ments and improvements from programmers worldwide
enhance-The new PHP release was extremely popular, and a core team of developers soon joined Lerdorf They kept the original concept of incorporating code directly alongside HTML and rewrote the parsing engine, giving birth to PHP 3.0 By the June 1998 release
of version 3.0, more than 50,000 users were using PHP to enhance their Web pages Development continued at a hectic pace over the next two years, with hundreds of functions being added and the user count growing in leaps and bounds At the beginning
of 1999, Netcraft (http://www.netcraft.com/), an Internet research and analysis company, reported a conservative estimate of a user base of more than 1 million, making PHP one of the most popular scripting languages in the world Its popularity surpassed even the greatest expectations of the developers, as it soon became apparent that users intended to use PHP to power far larger applications than originally anticipated Two core developers, Zeev Suraski and Andi Gutmans, took the initiative to completely rethink the way PHP operated, culminating in a rewriting of the PHP parser, dubbed the Zend scripting engine The result of this work was in the PHP 4 release
■ Note In addition to leading development of the Zend engine and playing a major role in steering the
overall development of the PHP language, Suraski and Gutmans are cofounders of Zend Technologies Ltd (http://www.zend.com/) Zend is the most visible provider of products and services for developing, deploying, and managing PHP applications Check out the Zend Web site for more about the company’s offerings, as well as an enormous amount of free learning resources
Trang 39PHP 4
On May 22, 2000, roughly 18 months after the first official announcement of the new
development effort, PHP 4.0 was released Many considered the release of PHP 4 to
be the language’s official debut within the enterprise development scene, an opinion
backed by the language’s meteoric rise in popularity Just a few months after the major
release, Netcraft estimated that PHP had been installed on more than 3.6 million
domains
PHP 4 added several enterprise-level improvements to the language, including
the following:
Improved resource handling: One of version 3.X’s primary drawbacks was
scal-ability This was largely because the designers underestimated how rapidly the
language would be adopted for large-scale applications The language wasn’t
originally intended to run enterprise-class Web sites, and continued interest in
using it for such purposes caused the developers to rethink much of the language’s
mechanics in this regard
Object-oriented support: Version 4 incorporated a degree of object-oriented
functionality, although it was largely considered an unexceptional and even poorly
conceived implementation Nonetheless, the new features played an important role
in attracting users used to working with traditional object-oriented programming
(OOP) languages Standard class and object development methodologies were
made available in addition to features such as object overloading and run-time
class information A much more comprehensive OOP implementation has been
made available in version 5 and is introduced in Chapter 6
Native session-handling support: HTTP session handling, available to version 3.X
users through the third-party package PHPLIB (http://phplib.sourceforge.net),
was natively incorporated into version 4 This feature offers developers a means
for tracking user activity and preferences with unparalleled efficiency and ease
Chapter 18 covers PHP’s session-handling capabilities
Encryption: The MCrypt (http://mcrypt.sourceforge.net) library was
incorpo-rated into the default distribution, offering users both full and hash encryption
using encryption algorithms including Blowfish, MD5, SHA1, and TripleDES,
among others Chapter 21 delves into PHP’s encryption capabilities
ISAPI support: ISAPI support offered users the ability to use PHP in conjunction
with Microsoft’s IIS Web server Chapter 2 shows you how to install PHP on both
the IIS and Apache Web servers
Trang 40Native COM/DCOM support: Another bonus for Windows users is PHP 4’s ability
to access and instantiate COM objects This functionality opened up a wide range of interoperability with Windows applications
Native Java support: In another boost to PHP’s interoperability, support for binding
to Java objects from a PHP application was made available in version 4.0
Perl Compatible Regular Expressions (PCRE) library: The Perl language has long
been heralded as the reigning royalty of the string-parsing kingdom The developers knew that powerful regular expression functionality would play a major role in the widespread acceptance of PHP and opted to simply incorporate Perl’s functionality rather than reproduce it, rolling the PCRE library package into PHP’s default distri-bution (as of version 4.2.0) Chapter 9 introduces this important feature in great detail and offers a general introduction to the often confusing regular expres-sion syntax
In addition to these features, literally hundreds of functions were added to version 4, greatly enhancing the language’s capabilities Many of these functions are discussed throughout the course of the book
PHP 4 represented a gigantic leap forward in the language’s maturity, offering new features, power, and scalability that swayed an enormous number of burgeoning and expert developers alike Yet the PHP development team wasn’t content to sit on their hands for long and soon set upon another monumental effort, one that could establish the language as the 800-pound gorilla of the Web scripting world: PHP 5
PHP 5
Version 5 was yet another watershed in the evolution of the PHP language Although previous major releases had enormous numbers of new library additions, version 5 contains improvements over existing functionality and adds several features
commonly associated with mature programming language architectures:
Vastly improved oriented capabilities: Improvements to PHP’s
object-oriented architecture is version 5’s most visible feature Version 5 includes numerous functional additions such as explicit constructors and destructors, object cloning, class abstraction, variable scope, and interfaces, and a major improvement regarding how PHP handles object management Chapters 6 and 7 offer thorough introductions to this topic