MySQL ® /PHP Database Applications, Second Edition Brad Bulger, Jay Greenspan, and David Wall MySQL ® /PHP Database Applications, Second Edition Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana ISBN: 0-7645-4963-4 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 2O/RW/RQ/QT Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada 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 Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-Mail: permcoordinator@wiley.com. is a trademark of Wiley Publishing, Inc. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: WHILE THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK, THEY MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR YOUR SITUATION. YOU SHOULD CONSULT WITH A PROFESSIONAL WHERE APPROPRIATE. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES. For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. 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 Cataloging-in-Publication Data: 2002114859 Trademarks: Wiley, the Wiley Publishing logo, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. MySQL is a registered trademark of MySQL AB Company. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. About the Authors Brad Bulger can remember when computers were as big as refrigerators and old- timers would come into the machine room and call them “mini.” After working for several companies that no longer exist, he is now a member of The Madfish Group (http://www.madfishgroup.com), where he builds Web sites for money. He would still like to know when the future is going to get here but has a sneaking suspicion he already knows. Jay Greenspan is a New York–based writer, editor, and technical consultant. He has contributed to sites run by Apple Computer and Wired Digital, and is author of MySQL Weekend Crash Course. He runs Trans-City Productions, Inc. (http://www. trans-city.com ), a firm that provides editorial services to high-tech companies. David Wall is a freelance technical consultant, lecturer, and writer. He specializes in Linux/Apache/MySQL/PHP (LAMP) servers and in Voice over IP technologies from IBM and Cisco Systems. His consultancy, David Wall Enterprises (http:// www.davidwall.com ), has offices in Washington, D.C., and Sydney. Credits ACQUISITIONS EDITORS Debra Williams Cauley Jim Minatel PROJECT EDITORS Kevin Kent Neil Romanosky TECHNICAL EDITORS Zak Greant Bill Patterson Liz Warner COPY EDITOR S. B. Kleinman EDITORIAL MANAGER Mary Beth Wakefield VICE PRESIDENT & EXECUTIVE GROUP PUBLISHER Richard Swadley VICE PRESIDENT AND EXECUTIVE PUBLISHER Bob Ipsen VICE PRESIDENT AND PUBLISHER Joseph B. Wikert EXECUTIVE EDITORIAL DIRECTOR Mary Bednarek PROJECT COORDINATOR Maridee Ennis GRAPHICS AND PRODUCTION SPECIALISTS Beth Brooks Jennifer Click LeAndra Hosier Michael Kruzil PERMISSIONS EDITOR Carmen Krikorian MEDIA DEVELOPMENT SPECIALIST Angela Denny PROOFREADING AND INDEXING TECHBOOKS Production Services Preface Welcome. If you are thumbing through these pages, you’re probably considering writing Web-based applications with PHP and MySQL. If you decide to go with these tools, you’ll be in excellent company. Thousands of developers — from total newbies to programmers with years of experience — are turning to PHP and MySQL for their Web-based projects, and for good reason. Both PHP and MySQL are easy to use, fast, free, and powerful. If you want to get a dynamic Web site up quickly, there are no better choices. The PHP scripting lan- guage was built for the Web. All the tasks common to Web development can be per- formed in PHP with an absolute minimum of effort. Similarly, MySQL excels at tasks common to dynamic Web sites. Whether you’re creating a content-management sys- tem or an e-commerce application, MySQL is a great choice for your data storage. Is This Book for You? Quite a few books deal with PHP, and a few cover MySQL. We’ve read some of these and found a few to be quite helpful. If you’re looking for a book that deals with the gory details of either of these packages, you should probably look elsewhere. The focus of this book is applications development. We are concerned with what it takes to get data-driven Web sites up and running in an organized and efficient way. The book does not go into arcane detail of every aspect of either of these tools. For example, in this book you will not find a discussion of PHP’s LDAP functions or MySQL’s C application program interface (API). Instead, we focus on the pieces of both packages that affect one another. We hope that by the time you’re done with this book you’ll know what it takes to get an application up and running using PHP and MySQL. How This Book Is Organized We have organized the book into five parts. Part I: Working with MySQL Before you code any PHP scripts you need to know how to design a database, cre- ate tables in your database, and get the information you want from the database. Part I of this book shows you just about everything you need to know to work with MySQL. ix Part II: Working with PHP As an applications developer, you will spend the bulk of your time writing scripts that access the database and present HTML to a user’s browser. Part II starts by showing you the basics of the PHP scripting language, covering how PHP works with variables, conditions, and control structures. Part II also covers many of PHP’s functions and discusses techniques for writing clean, manageable code. Part III: Simple Applications In this part we present two of the nine applications in this book: a guestbook and a survey. Here you see the lessons from Parts I and II put into practice as we build working applications. Part IV: Not So Simple Applications Here the applications become more complex, as we present applications commonly used on the Web. You see how you can design a content management system, a discussion board, a shopping cart, and other useful applications. Along the way we show you some tips and techniques that should be helpful as you write your applications. Part V: Appendixes The appendixes cover several topics of interest to the MySQL/PHP developer. In them you can find installation and configuration instructions, quick reference guides to PHP and MySQL functions, a regular expressions overview, and guides to MySQL administration. In addition, you can find a few helpful resources, some snippets of code, and instructions on using the CD-ROM. x Preface Acknowledgments I owe so many people so many bags of chocolate peanuts for helping me that I should start a chocolate-peanut farm. Making this book happen, trying to cover products under very active development, has been like trying to paint an oil por- trait of a manic chameleon in a camouflage factory. I must single out Debra Williams Cauley, Acquisitions Editor, and Kevin Kent, Development Editor, for their help and their patience — they have been the essence of diplomacy; Jay Greenspan, for getting me into this; and Liz Warner, for all disclosed and undisclosed forms of assistance, but especially for helping me stay sane(ish). Thanks so much to MySQL AB for the generous use of the MySQL Function Reference in Appendix J, and to Zak Greant, Erik Granstrom, Bill Patterson, and David Sides, CEO of Dolphin, for all their assistance. To everyone who helped, thank you — you have our gratitude. — Brad Bulger Thanks to my friends, family, and colleagues for their support and freely shared expertise during the creation of this book. — David Wall xi Contents at a Glance Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Acknowledgments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv Part I Working with MySQL Chapter 1 Database Design with MySQL . . . . . . . . . . . . . . . . . 3 Chapter 2 The Structured Query Language for Creating and Altering Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Chapter 3 The Structured Query Language for Inserting, Editing, and Selecting Data . . . . . . . . . . . . . . . . . . 53 Part II Working with PHP Chapter 4 Getting Started with PHP — Variables . . . . . . . . . . . 91 Chapter 5 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . 117 Chapter 6 PHP’s Built-in Functions . . . . . . . . . . . . . . . . . . . 133 Chapter 7 Writing Organized and Readable Code . . . . . . . . . 191 Part III Simple Applications Chapter 8 Guestbook 2003, the (Semi-)Bulletproof Guestbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Chapter 9 Survey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 Part IV Not So Simple Applications Chapter 10 Threaded Discussion . . . . . . . . . . . . . . . . . . . . . . 311 Chapter 11 Content-Management System . . . . . . . . . . . . . . . 349 Chapter 12 Catalog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 Chapter 13 Problem-Tracking System . . . . . . . . . . . . . . . . . . 441 Chapter 14 Shopping Cart . . . . . . . . . . . . . . . . . . . . . . . . . . . 477 Chapter 15 XML Parsing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 Chapter 16 SOAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519 Chapter 17 Project Management . . . . . . . . . . . . . . . . . . . . . . 537 xii Part V Appendixes Appendix A What’s on the CD-ROM . . . . . . . . . . . . . . . . . . . . 557 Appendix B HTML Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561 Appendix C Brief Guide to MySQL/PHP Installation and Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . 571 Appendix D MySQL Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . 583 Appendix E MySQL User Administration . . . . . . . . . . . . . . . . 597 Appendix F PHP Function Reference . . . . . . . . . . . . . . . . . . . 607 Appendix G Regular Expressions Overview . . . . . . . . . . . . . . . 659 Appendix H Helpful User-Defined Functions . . . . . . . . . . . . . . 669 Appendix I PHP and MySQL Resources . . . . . . . . . . . . . . . . . 691 Appendix J MySQL Function Reference . . . . . . . . . . . . . . . . . 697 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 End-User License Agreement . . . . . . . . . . . . . . . . 765 xiii Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Acknowledgments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv Part I Working with MySQL Chapter 1 Database Design with MySQL . . . . . . . . . . . . . . . . . . . . . 3 Why Use a Relational Database? . . . . . . . . . . . . . . . . . . . . . . 3 Blasted Anomalies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 The update anomaly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 The delete anomaly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 The insert anomaly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 Normalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 First normal form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Second normal form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Third normal form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Types of Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 The one-to-many relationship . . . . . . . . . . . . . . . . . . . . . . . . 15 The one-to-one relationship . . . . . . . . . . . . . . . . . . . . . . . . . . 16 The many-to-many relationship . . . . . . . . . . . . . . . . . . . . . . . 17 Advanced Database Concepts . . . . . . . . . . . . . . . . . . . . . . . 19 Referential integrity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 Stored procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Chapter 2 The Structured Query Language for Creating and Altering Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Essential Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Null values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 The create database Statement . . . . . . . . . . . . . . . . . . . . . . . 26 The use database Statement . . . . . . . . . . . . . . . . . . . . . . . . . 27 The create table Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 28 Column Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 String column types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Numeric column types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Date and time types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Creating Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 xv [...]... to access the database, you’re going to need a few more CONNECTING TO THE DATABASE While you’re installing PHP you should let it know that you plan on using MySQL with it If you don’t do this, what we discuss now won’t work Even if PHP is aware that you’re using MySQL, in your specific scripts you must identify the exact database you need access to In this case, that is the guestbook database you just... won’t need to fool with it a whole lot But as you are developing your applications, you spend a lot of time writing code that makes your applications work In addition to PHP, several languages perform similar functions Some of the more popular choices are ASP, Perl, and ColdFusion xxix xxx Introduction RELATIONAL DATABASES Relational database management systems (RDBMSes) provide a great way to store and... relational database, but for most users it has plenty If you are serving out Web content or creating a moderately sized commerce site, MySQL has all the power you need For small to-medium-sized databases, MySQL is extremely fast The developers of MySQL take great pride in the speed of their product For applications like the ones presented in Parts III and IV of this book, it is unlikely you’ll find a database. .. never want to run on a live Web server We re-create this application in a more robust form in Chapter 8 Creating the database Now that you know exactly what you need, the first step is to create a database that stores this information To do this, you use the language common to most every database server: SQL You read a lot more about this later, so don’t worry if you don’t understand everything right... Then, at the prompt, create a new database When you’re done, you should have something that looks very much like this: [jay@mybox jay]$ mysql Welcome to the MySQL monitor Commands end with ; or \g Your MySQL connection id is 716 to server version: 4.0.1-log Type ‘help’ for help mysql> create database guestbook; Query OK, 1 row affected (0.00 sec) mysql> Now, within the database named guestbook you need... communicating with the browser A relational -database server stores whatever information the application requires Finally, you need a language to broker requests between the Web server and the database server; it is also used to perform programmatic tasks on the information that comes to and from the Web server Figure I-1 represents this system Introduction Relational Database (MySQL, Oracle, MS SQL) Middleware... data are inserted into the database Figures I-2 and I-3 show the pages that this script creates Figure I-2: create_entry.php the first time through Introduction Figure I-3: create_entry.php after submission VIEWING INFORMATION IN THE DATABASE This shouldn’t be too tough You already know that the file needs to include dbconnect.php Other than that, we’ve already mentioned that databases store information... it should be no surprise that there are many RDBMSes to choose from All the major databases make use of the Structured Query Language (SQL) Some of the more popular commercial RDBMSes are Oracle, Sybase, Informix, Microsoft’s SQL Server, and IBM’s DB2 In addition to MySQL, there are now two major open-source relational databases Postgres has been the major alternative to MySQL in the open-source arena... whom may be better suited for a particular task In Part I of this book we discuss MySQL in some detail In these chapters we mention features available in other relational databases that MySQL does not support (If you know your way around databases and are curious, these include stored procedures, triggers, and subqueries.) Given these limitations, MySQL is definitely not the best choice in certain environments... a quick statement that forces the server to re-read the permissions tables, effectively putting the new ones into effect: mysql> FLUSH PRIVILEGES; So now you have a database named guestbook and a table, also named guestbook, within the database Now it’s time to write an application in PHP that will enable you to insert, edit, and view information kept in this guestbook Your PHP script Now’s the time . MySQL ® /PHP Database Applications, Second Edition Brad Bulger, Jay Greenspan, and David Wall MySQL ® /PHP Database Applications, Second Edition Published. you need to know how to design a database, cre- ate tables in your database, and get the information you want from the database. Part I of this book shows