View
19
Download
1
Category
Preview:
Citation preview
Andrew Curioso, Ronald Bradford, Patrick Galbraith
Wrox Programmer to Programmer™Join the discussion @ p2p.wrox.com
PHP and MySQL®
Expert
Curiosoet al.
$44.99 USA $53.99 CANProgramming Languages / PHP
wrox.comProgrammer ForumsJoin our Programmer to Programmer forums to ask and answer programming questions about this book, join discussions on the hottest topics in the industry, and connect with fellow programmers from around the world.
Code Downloads Take advantage of free code samples from this book, as well as code samples from hundreds of other books, all ready to use.
Read More Find articles, ebooks, sample chapters, and tables of contents for hundreds of books, and more reference resources on programming topics that matter to you.
As the world’s most popular, general purpose, open source scripting language, PHP is frequently used with MySQL to create high-traffic, mission-critical applications. This indispensable book shares proven, author-tested best practices and expert techniques that can be applied to even the most demanding MySQL-driven PHP apps. You’ll explore ways to extend MySQL with user-defined functions, write PHP extensions, and solve problems when PHP and MySQL alone are not enough and other techniques or third-party tools are necessary.
Expert PHP and MySQL:
• Reviews essential techniques, such as design patterns, complex queries, and advanced regular expression
• Addresses advanced PHP concepts, such as iterators and closures
• Demonstrates using Gearman for multitasking in your web applications
• Discusses caching using memcached with MySQL and your PHP web applications
• Discusses ways to create PHP Extensions and MySQL User Defined Functions
• Shows how to use Sphinx for search functionality in your PHP web applications
Andrew Curioso is a senior software engineer at MyVBO (Virtual Business Office) creating an innovative and scalable infrastructure for Rich Internet Applications using PHP and MySQL.
Ronald Bradford is a technology strategist and advisor specializing in MySQL, Drizzle and related web technologies. With a primary focus on architecture, design, performance analysis and scalability of web applications, his consulting portfolio ranges from Internet startups to Fortune 500 companies.
Patrick Galbraith is a principal software engineer at Lycos, adding new PHP and MySQL offerings for Tripod Users, switching remaining apps using Oracle to MySQL as well as other interesting projects.
Wrox Expert books present the wisdom accumulated by an experienced author team who is recognized as experts by the programming community. These experts challenge professional developers to examine their current practices in pursuit of better results.
Best practices and expert techniques for today’s most demanding apps Expert
PHP and M
ySQL
®
Related Wrox Books
Beginning PHP5, Apache, and MySQL Web DevelopmentISBN: 978-0-7645-7966-0 PHP, Apache, and MySQL are the three key open source technologies that form the basis for most active web servers. This book guides you through the entire process of setting up your own site and walks you through every step, from the installation of PHP, Apache, and MySQL to database management, security, and integration with other technologies. The multi-platform approach addresses installation and usage on both Linux® and Windows®, and two common-themed, reusable web sites are examined. Upon completion of this book, you’ll be able to create well designed, dynamic web sites using open source tools.
Beginning PHP 5.3ISBN: 978-0-470-41396-8As one of the most popular open-source web-programming languages in use today, PHP is an ideal server-side scripting language that connects HTML-based web pages to a backend database for dynamic content. It allows you to create anything from a simple form-to-email script to a web forum application, a blogging platform, or a content management system. This guide introduces the PHP language and shows you how to write powerful web applications using PHP.
Professional PHP 5ISBN: 978-0-7645-7282-1 This book has a pragmatic focus on how to use PHP in the larger scheme of enterprise-class software development. It covers UML modeling and presents objects and object hierarchies that, when completed, comprise a robust toolkit that developers will be able to reuse on future projects. This book is designed to arm you with the sort of constructs that are available out of the box with platforms such as Java and .NET — from simple utility classes like Collection and Iterator, to more complex constructs like Model/View/Controller architectures and state machines.
Professional PHP Design PatternsISBN: 978-0-470-49670-1 This book bridges the gap between the PHP and the older programming language by applying those tried and tested Design Patterns to native PHP applications. It starts with an introduction to Design Patterns, describes their use and importance, and details where you’ve seen them already. The book continues through a host of Design Patterns with code examples and explanations. Finally, an in-depth case study shows you how to plan your next application using Design Patterns, how to program those patterns in PHP, and how to revise and refactor an existing block of code using Design Patterns from the book. The author approaches the concepts in technical yet usable formats that are familiar to both programmers who are self-taught and those with more extensive formal education.
Get more out of wrox.com
Programmer to Programmer™
InteractTake an active role online by participating in our P2P forums @ p2p.wrox.com
Wrox Online LibraryHundreds of our books are available online through Books24x7.com
Wrox Blox Download short informational pieces and code to keep you up to date and out of trouble!
Join the CommunitySign up for our free monthly newsletter at newsletter.wrox.com
BrowseReady for more Wrox? We have books and e-books available on .NET, SQL Server, Java, XML, Visual Basic, C#/ C++, and much more!
Contact Us. We always like to get feedback from our readers. Have a book idea? Need community support? Let us know by e-mailing wrox-partnerwithus@wrox.com
CONTENTS AT A GLANCE
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxix
CHAPTER 1 Techniques Every Expert Programmer Needs to Know . . . . . . . . . . . . . . . 1
CHAPTER 2 Advanced PHP Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
CHAPTER 3 MySQL Drivers and Storage Engines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
CHAPTER 4 Improving Performance through Caching . . . . . . . . . . . . . . . . . . . . . . . . . 131
CHAPTER 5 memcached and MySQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
CHAPTER 6 Advanced MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
CHAPTER 7 Extending MySQL with User-Defi ned Functions . . . . . . . . . . . . . . . . . . 271
CHAPTER 8 Writing PHP Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
CHAPTER 9 Full-Text Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
CHAPTER 10 Multi-tasking in PHP and MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
CHAPTER 11 Rewrite Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
CHAPTER 12 User Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
CHAPTER 13 Understanding the INFORMATION_SCHEMA . . . . . . . . . . . . . . . . . . . . 477
CHAPTER 14 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
CHAPTER 15 Command-Line and Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .517
CHAPTER 16 Optimization and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
563120ffirs.indd i563120ffirs.indd i 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
563120ffirs.indd ii563120ffirs.indd ii 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
EXPERT
PHP and MySQL®
563120ffirs.indd iii563120ffirs.indd iii 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
563120ffirs.indd iv563120ffirs.indd iv 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
EXPERT
PHP and MySQL®
Andrew CuriosoRonald BradfordPatrick Galbraith
563120ffirs.indd v563120ffirs.indd v 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
Expert PHP and MySQL®
Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com
Copyright © 2010 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-56312-0
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including without limitation warranties of fi tness for a particular purpose. No warranty may be created or extended by sales or pro-motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the pub-lisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Library of Congress Control Number: 2010920658
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other coun-tries, and may not be used without written permission. MySQL is a registered trademark of MySQL AB. All other trade-marks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book.
563120ffirs.indd vi563120ffirs.indd vi 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
This book is dedicated to my wife, Laura. Without
your support this book wouldn’t be possible. Thank
you for being by my side and planning the wedding
while I was doing my writing!����������� �For MySQL Culture, past, present, and future. To
many in the MySQL community: you are more than
colleagues, you are great friends.����������������This book is dedicated to my son, Kiran Patrick.
“Kiran” means “ray of light” in Sanskrit, and you are
a ray of light in my life!������������������
563120ffirs.indd vii563120ffirs.indd vii 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
563120ffirs.indd viii563120ffirs.indd viii 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
ABOUT THE AUTHORS
ANDREW CURIOSO has been coding in PHP and MySQL for a decade. His experience includes develop-ing professional-grade PHP and MySQL based web applications for MIT Lincoln Laboratory (part of the Massachusetts Institute of Technology) and being at the ground fl oor of the state-of-the-art web-publishing platform Webon at Lycos (currently the page builder technology for Angelfire.com). Aside from software engineering, Andrew takes interest in software usability, business, the semantic web, and robotics. He currently works at MyVBO, a virtual business offi ce that provides powerful tools to help small to medium sized business manage their companies online. Over the years, he’s had the opportu-nity to work on exciting projects and specializes in data portability, linked data, social media, and Rich Internet Applications. His home on the web can be found at http://andrewcurioso.com/.
RONALD BRADFORD has more than two decades of professional IT industry experience in a broad range of disciplines. His core expertise is in relational database management systems (RDBMS) including MySQL, Oracle and Ingres. His technical software development skills include working in Java (J2EE), PHP, Perl, Python, Web (HTML/CSS/XML/JSON), and Linux/Unix operating systems. He is a professional speaker, educational curriculum developer, and writer who special-izes in technical presentations, workshops, online content publishing, and knowledge transfer. More information on his related MySQL writings, presentations and useful tools can be found at http://ronaldbradford.com.
PATRICK GALBRAITH lives up in the sticks of southwestern New Hampshire near Mt. Monadnock with his wife Ruth and son Kiran. Since 1993, he has been using and developing Open Source soft-ware. He has worked on various Open Source projects including MySQL, federated storage engine, memcached Functions for MySQL, Drizzle, Narada Search Engine Slashcode, and is the maintainer of DBD::mysql. He has worked at a number of companies throughout his career, including MySQL AB, Classmates.com, OSDN/Slashdot, and Lycos. He currently works at NorthScale, a leading provider of scale-out infrastructure software for web applications. He is also part owner of a wire-less broadband company, Radius North, which provides Internet service to underserved rural areas of New Hampshire. His website, which comes by way of a 5.8GHz Alvarion access unit up in a pine tree, is http://patg.net.
563120ffirs.indd ix563120ffirs.indd ix 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
563120ffirs.indd x563120ffirs.indd x 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
ABOUT THE TECHNICAL EDITORS
ALAN COLLISON is a software engineer with more than a dozen years of experience developing scal-able PHP applications. His expertise ranges from the design and development of front end GUIs to the implementation of core server side application business logic.
JAY COSKEY is a software developer and software development manager who lives in Seattle, and has worked for companies including Cray Inc. and Amazon.com. He has used numerous languages on Linux, Unix, and Windows platforms, in environments ranging from OS development, to web and enterprise systems. When not involved in mathematics or software, he can sometimes be found woodworking.
ERIC DAY has been writing high-performance servers and databases for most of his career and cur-rently works on open source projects such as Drizzle and Gearman. He has also written a number of extensions for higher level languages such as PHP. When not hacking on code, he can be found run-ning, enjoying a good vegan meal, or blogging at http://oddments.org/.
KEN MACKE is a systems architect, developer, and owner of RockIP Networks — a provider of web hosting and IT consulting services. Ken has over 15 years of experience creating cutting-edge software with technologies such as PHP, C++, C#, and .NET. You can fi nd Ken online at twitter.com/kmacke.
ELIZABETH NARAMORE has been a web developer since 1997, with a focus in PHP and E-commerce. In addition to being a web developer, she is an author, editor, speaker, and educator, and active member of communities such as the PHP Community, PHPWomen, and her local PHP Users Group.
TROND NORBYE is a Senior Software Engineer specializing in databases and distributed caching. He currently works at NorthScale designing and implementing scale out data systems. Prior to joining NorthScale, Trond was a key member of Sun Microsystems’ Web Scale Infrastructure group where he worked on Drizzle, Gearman and Memcached. In his copious free time he is a core contributor on the Memcached, Libmemcached and OpenGrok Open Source projects.
KARL WILBUR is an enterprise consultant, PHP developer and Linux guru with more than a decade of LAMP experience and a passion for the bleeding-edge. When not out motorcycling the Midwest he can be found lurking on the Internet at http://karlwilbur.net/.
563120ffirs.indd xi563120ffirs.indd xi 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
563120ffirs.indd xii563120ffirs.indd xii 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
CREDITS
EXECUTIVE EDITOR
Robert Elliott
PROJECT EDITOR
Maureen Spears
TECHNICAL EDITORS
Alan Collison
Jay Coskey
Eric Day
Ken Macke
Elizabeth Naramore
Trond Norbye
Karl Wilbur
PRODUCTION EDITOR
Eric Charbonneau
COPY EDITOR
Kim Cofer
EDITORIAL DIRECTOR
Robyn B. Siesky
EDITORIAL MANAGER
Mary Beth Wakefi eld
MARKETING MANAGER
Ashley Zurcher
PRODUCTION MANAGER
Tim Tate
VICE PRESIDENT AND EXECUTIVE GROUP
PUBLISHER
Richard Swadley
VICE PRESIDENT AND EXECUTIVE PUBLISHER
Barry Pruett
ASSOCIATE PUBLISHER
Jim Minatel
PROJECT COORDINATOR, COVER
Lynsey Stanford
COMPOSITOR
Jeff Lytle, Happenstance Type-o-Rama
PROOFREADER
Nancy Bell
INDEXER
Johnna VanHoose Dinse
COVER DESIGNER
Michael E. Trent
COVER IMAGE
©Gavin Hellier/Photographer’s Choice RF/
Getty Images
563120ffirs.indd xiii563120ffirs.indd xiii 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
563120ffirs.indd xiv563120ffirs.indd xiv 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
ACKNOWLEDGMENTS
IT WAS THANKS TO MY BROTHER RAY CURIOSO JR. that I was really able to get a head start. He started an embroidery business in the 90s out of my parents’ garage. It has since moved to its own place but there was that time in-between where, thanks to his company, I was one of the only people that I knew with Internet access. It was slow and it took days to download software development kits and it wasn’t as easy to fi nd programming help for a beginner as it is today. But I made do with what I had. It was also because of him and his business — it needed an ecommerce site — that I put down the C code and the ASP and got my start with PHP and MySQL.
I’d like to thank my parents too for being a constant source of support for me. It was my father who taught me the value of hard work. And, of course, thank my wife who put up with me spending long nights working for a start up and writing a book at the same time. We were married during the writing and without her hard work planning the wedding, supporting me, and standing by my side this book would not have been possible.
I’d like to thank my teammates at Lycos. It was truly a pleasure working with each of them. I’d particularly like to thank my managers. Don Kosak for inspiring me, Neal Shanske for keeping me on my toes. I’d like to thank Derek Bruneau since everything I learned about good software design and usability I learned thanks to him. And I’d like to thank my fellow engineers Lisa Wallmark, Chandra Yadav, and Kevin Harrington. I’d like to also thank my team at MyVBO, in particular Robert (Bob) Wilkins and Matthew Sheppard for their understanding as I juggled work and writing.
Finally, I would also like to take a minute to thank the team that worked tirelessly to make this book happen. Bob Elliott who made this book happen, Maureen Spears who edited this whole thing cover to cover, and my co-authors Patrick and Ronald. Patrick in particular has been a good friend and deserves credit for putting the team together. He is the one thread that connects us all. Which brings me to the tech editors. They all did an amazing job and the book is much better because of each of them.
There are countless people who have helped me along the way. I am sure that I forgot someone. To anyone who has ever encouraged me to follow my dreams or supported me in any way: thank you.����������� �TODAY, I AM A WELL RESPECTED AUTHORITY in the MySQL fi eld. This was not possible without a lot of hard work and great mentorship. I would fi rst like to thank the late Frank Jarvis from DDIAE (now USQ) who in 1988 introduced me to the works of C.J. Date, M. Stonebraker and E.F. Codd during my university studies.
My fi rst relational database experience started with Ingres and led to immediate work with systems design and software development in the database fi eld. In the early 90’s, as a young, energetic and knowledgeable database architect with several successful government projects, my work alongside
563120ffirs.indd xv563120ffirs.indd xv 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
my now good friend Bruce Turner helped in my understanding and appreciation of more formal processes in the management and success of large scale deployments. We worked together again for Oracle Corporation in the late 90s where Bruce still works today. To Bruce, thank you for your sup-port and mentoring. Those TAFE days with Mike and Laurie still rate as some of my favorites. From my fi rst use of MySQL over ten years ago until today I still seek input, advice and encouragement from the MySQL community. Many of you from the MySQL community I consider as great friends.
Finally, to my fi ance Cindy who has been supportive throughout the entire process of my fi rst book in MySQL with compromises that have enabled me to complete this work on schedule.�������������ONE WEEKEND IN 1993, I had the chance to go on a getaway to San Diego. Instead, I opted to stay home and download, onto 26 fl oppies, Slackware Linux, which I promptly installed onto my Packard Bell 386. I could never get the built-in video card to work with X, so I ended up buying a separate video card and had to edit my XConfi g fi le to get it to work. How much more interesting this was to do than editing a confi g.sys and an autoexec.bat! From then on, I was hooked. I worked at Siemens Ultrasound Group in Issaquah, Washington, at the time. An engineer there named Debra, when asked what was a good thing to learn, said something I’ll never forget: ‘‘Learn Perl.’’ Debra — you were right! I always wanted to be a C ++ graphics programmer. That didn’t happen because of this thing called the World Wide Web. I remember Ray Jones and Randy Bentson of Celestial Software showing me a program called Mosaic, which allowed you to view text over the Internet. Images would be launched using XV. Everywhere I worked, I had to write programs that ran on the Web, which required me to write CGI in Perl. So much for my goal of being a C ++ programmer — but I consider this a great trade for a great career. (I did eventually get to write C ++ for MySQL!) I would fi rst like to thank my wife, Ruth, for being patient and supportive of me for numerous lost weekends with this book and my previous book Developing Web Applications with Perl, memcached, MySQL and Apache, as well as accepting me working on yet another book so soon after the fi rst! Next in line for thanks, our editor, Maureen Spears, who is not only a great editor, but also a friend. Not only did she edit this current work, but she was my editor for my previous book. Next, I would like to thank my co-authors, Andrew and Ronald. It’s been a whole different experience co-authoring versus being a sole author, having learned a bit about putting together something — as a team.
A special thanks goes to our tech editors as well as to Trond Norbye (memcached, libmemcached), Eric Day (Gearman, Drizzle) and Andrew Aksyonoff (Sphinx) for stepping up as tech editors when we were in a crunch and reviewing the material I wrote about their projects!
Thank you to Bob Elliott, who gave us the opportunity to work as a team to write this book! Thanks to Monty Widenius for creating MySQL and for being a mentor as well as a good friend who worked hard to include FederatedX into MariaDB while I was working on this book. Thanks also to Brian Aker for being another great mentor and friend, as well as being a software-producing machine with a scrolling page full of open source software projects that he’s created, including Drizzle and libmemcached.
563120ffirs.indd xvi563120ffirs.indd xvi 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
I WOULD LIKE TO THANK MY CURRENT COLLEAGUES at Northscale — Steve Yen, Dustin Sallings, James Phillips, Matt Ingenthron, Rod Ebrahimi, Eric Lambert and Trond Norbye — it’s a real privilege to work with guys who have so much expertise. Also thanks go to my former colleagues at Lycos who encouraged me while writing my previous book — Don Kosak, Chandra Yadav, Tristan Escalada, oth-ers, as well as Andrew Curioso! Also to former colleagues at Grazr and MySQL. Last but not least, thanks to the team members of MariaDB and Drizzle for integrating projecs I worked on while writing this book. Thanks also to anyone I forgot to mention. I know I probably forgot someone!���������������
563120ffirs.indd xvii563120ffirs.indd xvii 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
563120ffirs.indd xviii563120ffirs.indd xviii 2/18/10 9:07:32 AM2/18/10 9:07:32 AM
CONTENTS
INTRODUCTION XXIX
TECHNIQUES EVERY EXPERT PROGRAMMER CHAPTER 1: NEEDS TO KNOW 1
Object-Oriented PHP 2
Instantiation and Polymorphism 2
Interfaces 7
Magic Methods and Constants 8
Design Patterns 11
Using MySQL Joins 20
INNER JOIN 22
OUTER JOIN 24
Other JOIN Syntax 26
Complex Joins 27
MySQL Unions 28
GROUP BY in MySQL Queries 30
WITH ROLLUP 31
HAVING 32
Logical Operations and Flow Control in MySQL 33
Logic Operators 33
Flow Control 34
Maintaining Relational Integrity 35
Constraints 36
NOT NULL 36
UNSIGNED 36
ENUM and SET 37
UNIQUE KEY 37
FOREIGN KEY 38
Using Server SQL Modes 41
Storage Engine Integrity 45
What MySQL Does Not Tell You 45
What’s Missing? 46
Subqueries in MySQL 46
Subquery 46
Correlated Subquery 46
Derived Table 47
563120ftoc.indd xix563120ftoc.indd xix 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xx
CONTENTS
Using Regular Expressions 49
General Patterns 50
Expert Regular Expressions 52
Putting It All Together in PHP 55
Regular Expressions in MySQL 60
Summary 63
ADVANCED PHP CONCEPTS 6CHAPTER 2: 5
A Problem That Needs Solving 65
Iterators and the SPL 67
A Sample View for the Application 67
The Iterator Interface 69
The Countable Interface 73
The SeekableIterator Interface and Pagination 75
The ArrayAccess Interface 77
Lambda Functions and Closures 78
The Old Way: Lambda-Style Functions 78
Understanding Closures 81
Using the Query Builder for Prototyping 83
Summary 85
MYSQL DRIVERS AND STORAGE ENGINES 8CHAPTER 3: 7
MySQL Drivers 88
About MySQL Storage Engines 89
Obtaining Storage Engine Information 89
Default Storage Engines 93
MyISAM 93
InnoDB 97
Memory 103
Blackhole 108
Archive 109
Merge 110
CSV 112
Federated 112
Other MySQL Supplied Engines 118
Falcon 118
Maria 120
Pluggable Engines 121
InnoDB Plugin 121
PBXT 122
XtraDB 123
563120ftoc.indd xx563120ftoc.indd xx 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xxi
CONTENTS
Engines as Standalone Products 124
Infi niDB 124
TokuDB 124
Infobright 125
Other MySQL Off erings 125
Storage Engine Patch Products 125
MySQL-Related Products 126
Other Engines 127
Integrated Hardware Engines 128
Other Solutions 128
Waffl egrid 129
Summary 129
IMPROVING PERFORMANCE THROUGH CACHING 13CHAPTER 4: 1
eAccelerator and APC 132
Installing and Confi guring APC 132
Installing and Confi guring eAccelerator 133
User Cache 134
Checking the Cache Status 135
When to Use APC and eAccelerator 138
memcached 138
What Is memcached? 139
What memcached Does for You 139
How Does memcached Work? 139
How to Use memcached 141
What Is Gearman? 144
Caching Strategies 144
Installing memcached 145
Starting memcached 148
Startup Scripts 149
Testing Your memcached Installation 151
memcached Clients 153
Libmemcached 153
Libmemcached Features 154
Libmemcached Utility Programs 154
Installing libmemcached 155
Libmemcached Utility Programs 155
memcat 155
memfl ush 156
memcp 156
memstat 157
memrm 157
563120ftoc.indd xxi563120ftoc.indd xxi 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xxii
CONTENTS
memslap 157
memerror 158
PECL/Memcached 158
Connecting, Instantiation 160
Setting Client Behavior 162
Putting and Retrieving Data 163
Append and Prepend 166
Delete 168
Increment and Decrement 168
Multi-get 169
Multi-set 170
Cache Locality Using byKey Methods and Multi get/set 171
getDelayed 173
CAS 174
Statistics 176
Server List 178
Error Handling 178
Practical Caching 180
memcached Proxy: moxi 185
Other “memcapable” Key-Value Stores 186
Tokyo Tyrant 187
Summary 188
MEMCACHED AND MYSQL 19CHAPTER 5: 1
The Memcached Functions for MySQL 191
How the Memcached Functions for MySQL Work 192
Installing the Memcached Functions for MySQL 193
Prerequisites 193
Confi gure the Source 194
Build the Source 194
Install the UDF 195
Checking Installation 196
Using the Memcached Functions for MySQL 196
Establishing a Connection to the memcached Server 197
Data Setting Functions 198
Data Fetching Functions 204
Increment and Decrement 204
Behavioral Functions 206
Statistical Functions 209
Version Functions 211
Fun with Triggers (and UDFs) 212
563120ftoc.indd xxii563120ftoc.indd xxii 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xxiii
CONTENTS
Read-Through Caching with Simple Select Statements 216
Updates 219
Summary 220
ADVANCED MYSQL 22CHAPTER 6: 1
Views 221
Access Permissions 223
Additional Information about Views 225
Stored Procedures and Functions 226
General Attributes 226
Stored Routine Logic 228
Using Stored Routines Privileges and Meta Data 230
Extending Stored Routines 231
Stored Routine Disadvantages 231
User Defi ned Functions 231
Triggers 232
No Triggers 233
Trigger Syntax 233
Insert Triggers 233
Update Triggers 234
Delete Triggers 235
Replace Triggers 236
Trigger Permissions 237
Transactions 237
Atomicity 238
Consistency 240
Isolation 242
Durability 247
Implied Commit 250
Replication 250
Replication Purposes 250
Replication Setup 251
Testing MySQL Replication 254
How Does MySQL Replication Work? 255
Testing MySQL Replication 259
Important Confi guration Options 260
Important Replication Commands 261
Breaking Replication 261
Using Replication Selectively 262
The Issues with MySQL Replication 263
The Benefi ts of MySQL Replication 264
563120ftoc.indd xxiii563120ftoc.indd xxiii 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xxiv
CONTENTS
Events 264
Creating Events 265
Enabling the Events Scheduler 267
Altering Events 267
Event Privileges 268
Event Meta Data 269
Summary 270
EXTENDING MYSQL WITH USER-DEFINED FUNCTIONS 27CHAPTER 7: 1
Introduction to UDFs 272
Developing a UDF 273
UDF Development Requirements 273
UDF Required Functions 274
A Practical UDF Example 274
UDF High-Level Design 275
Designing an Algorithm to Use for Your UDF 277
Implementing the Program 277
Building the UDF 292
Installing the UDF 294
Running Your New UDF 295
Using a UDF with PHP 296
Connecting and Disconnecting to MySQL 296
Returning the Result Set Array 297
Other UDF SQL Statements 300
Debugging a UDF 300
Attaching gdb to an Already Running Process 301
Setting a BreakPoint and Stepping through Code 302
Dealing with Literal Values 304
Debugging Summary 304
Summary 305
WRITING PHP EXTENSIONS 30CHAPTER 8: 7
Setting Up the Build Environment 308
Creating an Extension with ext_skel 309
Creating and Compiling Skeleton Code 309
Using a Function Defi nitions File 312
Generating Help Files 313
Creating an Extension with CodeGen_PECL 314
Creating the Basic XML File 314
Defi ning Functions 316
Defi ning Constants, INI Directives, and Globals 318
Defi ning Objects, Methods, and Properties 319
563120ftoc.indd xxiv563120ftoc.indd xxiv 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xxv
CONTENTS
Variables in PHP Extensions 321
Setting and Testing zvals 323
Reading and Comparing zvals 324
Dealing with Strings as zvals 326
Advanced Memory Management 328
Using Functions in Extensions 329
Basic Defi nitions 329
Using Arguments 331
Defi ning Argument Information 334
Returning Values 334
Built-In Functions 335
Creating and Consuming PHP API Functions 336
More Notes and Creating Helper Functions 339
Input/Output 340
Standard Out 340
Files and Streams 341
Networking 344
Errors and Warnings 346
Arrays and Hash Tables 347
Building and Accessing Arrays 347
Accessing and Modifying Hash Tables 349
Objects and Interfaces 349
Creating a Class 350
Interacting with Objects 355
Constants, INI Directives, and Globals 357
Constants 357
Globals and INI Directives 358
Describing an Extension 361
Printing a Description 361
Building a Table 362
Specifying a Logo 362
Summary 364
FULL-TEXT SEARCHING 36CHAPTER 9: 5
MySQL FULLTEXT Indexes 365
Using MySQL FULLTEXT Indexes 367
MySQL FULLTEXT Index Issues 368
A Better Solution: The Sphinx Full-Text Search Engine 369
Sphinx Confi guration and Installation 370
Sphinx.conf Settings 371
Starting Sphinx 382
Searching Sphinx 383
563120ftoc.indd xxv563120ftoc.indd xxv 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xxvi
CONTENTS
Delta Indexes 389
Merging Indexes 394
Developing Applications That Use SPHINX 395
Sphinx and PHP 395
Summary 399
MULTI-TASKING IN PHP AND MYSQL 40CHAPTER 10: 1
Gearman 401
What Is Gearman? 402
Installing and Running Gearman 404
Using the Gearman MySQL UDFs 407
PHP and Gearman 409
Narada: A Search Engine Application 412
Obtaining Narada 413
Narada Components 413
Database Tables for the Search Engine Application 415
Sphinx Setup 416
Gearman Workers 429
Index Page 435
One Other Tidbit of Code 438
The Big Picture 439
Running Narada 439
To-Do List for Narada 441
Other Job Server Systems 442
Summary 442
REWRITE RULES 44CHAPTER 11: 3
Using Rewrite Rules 444
Understanding the Purpose and Structure of Rewrite Rules 444
Understanding and Controlling Rewrite Rule Flow 445
Conditional Rules 447
Logging and Optimization 450
Rewrite Maps 451
Built-In Maps 451
Random and Text Lookups 452
Using PHP and MySQL 452
Summary 456
USER AUTHENTICATION 45CHAPTER 12: 7
Designing the Database 458
HTTP-Based Authentication 460
Basic Authentication 461
563120ftoc.indd xxvi563120ftoc.indd xxvi 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xxvii
CONTENTS
Digest Authentication 463
Pure PHP Authentication 466
Using PHP Sessions 467
Building Secure Cookies 471
Access Control Lists 473
Summary 475
UNDERSTANDING THE INFORMATION_SCHEMA 47CHAPTER 13: 7
Using the INFORMATION_SCHEMA 478
Table Objects Tables 479
Other Database Objects Tables 481
MySQL Status Tables 482
PROCESSLIST (5.1) 482
SESSION_STATUS/GLOBAL_STATUS (5.1) 484
SESSION_VARIABLES/GLOBAL_VARIABLES (5.1) 485
MySQL Meta Data Tables 486
CHARACTER_SETS 486
COLLATIONS 487
COLLATION_CHARACTER_SET_APPLICABILITY 488
MySQL ACL Permissions Tables 488
USER_PRIVILEGES 488
SCHEMA_PRIVILEGES 489
TABLE_PRIVILEGES 489
COLUMN_PRIVILEGES 490
INFORMATION_SCHEMA Extensions 491
SHOW Cross Reference 491
Summary 492
SECURITY 49CHAPTER 14: 3
Hardening Your MySQL Server 493
Installation Defaults 494
Operating System Security 495
MySQL Security Permissions 495
Additional Database Security 500
Auditing 500
Encoding Data 501
Bi-directional Encoding 501
Single-Directional Encoding 505
PHP Security Recipes 506
Protecting against SQL Injection 506
Protecting against Replay Attacks 507
563120ftoc.indd xxvii563120ftoc.indd xxvii 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
xxviii
CONTENTS
Protecting against XSS 509
Protecting against CSRF 511
Automation Attacks 514
Summary 516
COMMAND-LINE AND WEB SERVICES 51CHAPTER 15: 7
Creating Command-Line Scripts 517
Reading Command-Line Input 518
Prompting for Input 520
Completed Classes 521
Setting Up Cron Jobs 522
Bonus: Output in Color 523
Creating Web Services 524
RESTful Web Services 524
SOAP Web Services 532
Getting Started with the SOAP Library 533
Summary 541
OPTIMIZATION AND DEBUGGING 54CHAPTER 16: 3
Debugging PHP 543
Creating Stack Traces 544
Optimizing Queries 545
Reducing SQL 545
Identifying SQL Statements 545
Optimizing SELECT 546
Optimizing UPDATE 556
Optimizing DELETE 556
Optimizing INSERT 558
Optimizing REPLACE 558
INSERT … ON DUPLICATE KEY UPDATE 558
Debugging MySQL 560
Error Log 560
Slow Query Log 561
Processlist 562
Other Commands 564
Using a Debugger with MySQL 564
Summary 565
INDEX 567
563120ftoc.indd xxviii563120ftoc.indd xxviii 2/18/10 9:07:48 AM2/18/10 9:07:48 AM
Recommended