MySQL/PHP Database Applications 3537-4 FM.f.qc 12/15/00 15:31 Page i 3537-4 FM.f.qc 12/15/00 15:31 Page ii MySQL/PHP Database Applications Jay Greenspan and Brad Bulger M&T Books An imprint of IDG Books Worldwide, Inc. Foster City, CA ● Chicago, IL ● Indianapolis, IN ● New York, NY 3537-4 FM.f.qc 12/15/00 15:31 Page iii LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHOR 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. THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL. 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. Trademarks: All brand names and product names used in this book are trade names, service marks, trademarks, or registered trademarks of their respective owners. IDG Books Worldwide is not associated with any product or vendor mentioned in this book. is a registered trademark or trademark under exclusive license to IDG Books Worldwide, Inc. from International Data Group, Inc. in the United States and/or other countries. is a trademark of IDG Books Worldwide, Inc. MySQL/PHP Database Applications Published by M&T Books An imprint of IDG Books Worldwide, Inc. 919 E. Hillsdale Blvd., Suite 400 Foster City, CA 94404 www.idgbooks.com (IDG Books Worldwide Web site) Copyright © 2001 IDG Books Worldwide, Inc. All rights reserved. No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher. ISBN: 0-7645-3537-4 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 1O/QZ/QR/QR/FC Distributed in the United States by IDG Books Worldwide, Inc. Distributed by CDG Books Canada Inc. for Canada; by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty. Ltd. for Australia and New Zealand; by TransQuest Publishers Pte Ltd. for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc. for Taiwan; by ICG Muse, Inc. for Japan; by Intersoft or South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland; by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R. Ltda. for Peru; by WS Computer Publishing Corporation, Inc., for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc. for Micronesia; by Chips Computadoras S.A. de C.V. for Mexico; by Editorial Norma de Panama S.A. for Panama; by American Bookshops for Finland. For general information on IDG Books Worldwide’s books in the U.S., please call our Consumer Customer Service department at 800-762-2974. For reseller information, including discounts and premium sales, please call our Reseller Customer Service department at 800-434-3422. For information on where to purchase IDG Books Worldwide’s books outside the U.S., please contact our International Sales department at 317-572-3993 or fax 317-572-4002. For consumer information on foreign language translations, please contact our Customer Service department at 800-434-3422, fax 317-572-4002, or e-mail rights@idgbooks.com. For information on licensing foreign or domestic rights, please phone +1-650-653-7098. For sales inquiries and special prices for bulk quantities, please contact our Order Services department at 800-434-3422 or write to the address above. For information on using IDG Books Worldwide’s books in the classroom or for ordering examination copies, please contact our Educational Sales department at 800-434-2086 or fax 317-572-4005. For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 650-653-7000 or fax 650-653-7500. For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470. Library of Congress Cataloging-in-Publication Data Greenspan, Jay, 1968- My SQL/PHP database applications / Jay Greenspan and Brad Bulger. p. cm. ISBN 0-7645-3537-4 (alk. paper) 1. SQL (Computer program language) 2. PHP (Computer program language 3.Web databases. I. Bulger, Brad, 1959- II. Title. QA76.73.S67G73 2001 005.13’3 dc21 00-053995 3537-4 FM.f.qc 12/15/00 15:31 Page iv Eleventh Annual Computer Press Awards 1995 Tenth Annual Computer Press Awards 1994 Eighth Annual Computer Press Awards 1992 Ninth Annual Computer Press Awards 1993 IDG is the world’s leading IT media, research and exposition company. Founded in 1964, IDG had 1997 revenues of $2.05 billion and has more than 9,000 employees worldwide. IDG offers the widest range of media options that reach IT buyers in 75 countries representing 95% of worldwide IT spending. IDG’s diverse product and services portfolio spans six key areas including print publishing, online publishing, expositions and conferences, market research, education and training, and global marketing services. More than 90 million people read one or more of IDG’s 290 magazines and newspapers, including IDG’s leading global brands — Computerworld, PC World, Network World, Macworld and the Channel World family of publications. IDG Books Worldwide is one of the fastest-growing computer book publishers in the world, with more than 700 titles in 36 languages. The “ For Dummies ® ” series alone has more than 50 million copies in print. IDG offers online users the largest network of technology-specific Web sites around the world through IDG.net (http://www.idg.net), which comprises more than 225 targeted Web sites in 55 countries worldwide. International Data Corporation (IDC) is the world’s largest provider of information technology data, analysis and consulting, with research centers in over 41 countries and more than 400 research analysts worldwide. IDG World Expo is a leading producer of more than 168 globally branded conferences and expositions in 35 countries including E3 (Electronic Entertainment Expo), Macworld Expo, ComNet, Windows World Expo, ICE (Internet Commerce Expo), Agenda, DEMO, and Spotlight. IDG’s training subsidiary, ExecuTrain, is the world’s largest computer training company, with more than 230 locations worldwide and 785 training courses. IDG Marketing Services helps industry-leading IT companies build international brand recognition by developing global integrated marketing programs via IDG’s print, online and exposition products worldwide. Further information about the company can be found at www.idg.com. 1/26/00 Welcome to the world of IDG Books Worldwide. IDG Books Worldwide, Inc., is a subsidiary of International Data Group, the world’s largest publisher of computer-related information and the leading global provider of information services on information technology. IDG was founded more than 30 years ago by Patrick J. McGovern and now employs more than 9,000 people worldwide. IDG publishes more than 290 computer publications in over 75 countries. More than 90 million people read one or more IDG publications each month. Launched in 1990, IDG Books Worldwide is today the #1 publisher of best-selling computer books in the United States. We are proud to have received eight awards from the Computer Press Association in recognition of editorial excellence and three from Computer Currents’ First Annual Readers’ Choice Awards. Our best- selling For Dummies ® series has more than 50 million copies in print with translations in 31 languages. IDG Books Worldwide, through a joint venture with IDG’s Hi-Tech Beijing, became the first U.S. publisher to publish a computer book in the People’s Republic of China. In record time, IDG Books Worldwide has become the first choice for millions of readers around the world who want to learn how to better manage their businesses. Our mission is simple: Every one of our books is designed to bring extra value and skill-building instructions to the reader. Our books are written by experts who understand and care about our readers. The knowledge base of our editorial staff comes from years of experience in publishing, education, and journalism — experience we use to produce books to carry us into the new millennium. In short, we care about books, so we attract the best people. We devote special attention to details such as audience, interior design, use of icons, and illustrations. And because we use an efficient process of authoring, editing, and desktop publishing our books electronically, we can spend more time ensuring superior content and less time on the technicalities of making books. You can count on our commitment to deliver high-quality books at competitive prices on topics you want to read about. At IDG Books Worldwide, we continue in the IDG tradition of delivering quality for more than 30 years. You’ll find no better book on a subject than one from IDG Books Worldwide. John Kilcullen Chairman and CEO IDG Books Worldwide, Inc. 3537-4 FM.f.qc 12/15/00 15:31 Page v About the Authors Jay Greenspan made his living as a technical consultant and editor before finding his way into Wired Digital’s Webmonkey. There he learned everything he knows about Web technology and gained an appreciation for electronic music, the color orange, and a “cute top.” He now makes his living as a writer and consultant. He will neither confirm nor deny the rumors that he once worked for a prime-time game show. Brad Bulger can remember when computers were as big as refrigerators and old- timers would come into the machine room and call them “mini.” He learned more than anyone really should about database systems by working for Relational Technology nee Ingres nee CA for many years. After an interregnum, he got a job with Wired. He would still like to know when the future is going to get here, but has a sneaking suspicion he already knows. Credits ACQUISITIONS EDITOR Debra Williams Cauley PROJECT EDITOR Neil Romanosky TECHNICAL EDITORS Richard Lynch Michael Widenius COPY EDITOR S. B. Kleinman PROJECT COORDINATORS Louigene A. Santos Danette Nurse GRAPHICS AND PRODUCTION SPECIALISTS Robert Bilhmayer Rolly Delrosario Jude Levinson Michael Lewis Ramses Ramirez Victor Pérez-Varela QUALITY CONTROL TECHNICIAN Dina F Quan PERMISSIONS EDITOR Laura Moss MEDIA DEVELOPMENT SPECIALIST Angela Denny MEDIA DEVELOPMENT COORDINATOR Marisa Pearman BOOK DESIGNER Jim Donohue ILLUSTRATORS Gabriele McCann Ronald Terry PROOFREADING AND INDEXING York Production Services COVER IMAGE © Noma/Images.com 3537-4 FM.f.qc 12/15/00 15:31 Page vi In memory of Dr. Jonathan B. Postel 3537-4 FM.f.qc 12/15/00 15:31 Page vii 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 accomplished 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 system or an e-commerce application, MySQL is a great choice for your data storage. Is This Book for You? There are quite a few books that deal with PHP and a few that 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 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 will 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 four parts. Part I: Using MySQL Before you code any PHP scripts, you will need to know how to design a database, create tables in your database, and get the information you want from the database. Part I of this book will show you about all you need to know to work with MySQL. ix 3537-4 FM.f.qc 12/15/00 15:31 Page ix Part II: Using PHP As an applications developer, the bulk of your time will be spent writing scripts that access the database and present HTML to a user’s browser. Part II will start by showing you the basics of the PHP scripting language, covering how PHP works with variables, conditions, and control structures. Part II will also cover many of PHP’s functions and discuss techniques for writing clean, manageable code. Part III: Simple Applications In this part, we present two of the seven applications in this book: a guestbook and a survey. Here you will 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 will be more complex, as we present applications commonly used on the Web. You will see how you can design a content management system, a discussion board, a shopping cart, and other useful applications. Along the way, we will show 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 the appendixes, you will find installation and configuration instructions, quick refer- ence guides to PHP and MySQL functions, a regular expressions overview, and guides to MySQL administration. In addition, there are a few helpful resources, snippets of code, and instructions on using the CD-ROM. Tell Us What You Think Both the publisher and authors of this book hope you find it a valuable resource. Please feel free to register this book at the IDG Books Web site (http://www. idgbooks.com ) and give us your feedback. Also check in at the site we’ve dedicated to this book, http://www.mysqlphpapps.com/, where you will be able to contact the authors and find updates to the applications created for this book. x Preface 3537-4 FM.f.qc 12/15/00 15:31 Page x Acknowledgments This book would never have happened if not for the efforts of Debra Williams Cauley. I thank her for her patience and persistence. The efforts and talents of Neil Romanosky, S. B. Kleinman, and many others at IDG Books have made this book more lucid and attractive than we could have hoped. Richard Lynch’s exacting eye and technical acumen kept our code clean, fast, and readable. Any book on open-source software owes debt to those who have created these great tools. So I thank everyone involved with PHP and MySQL, from the core developers to those who contribute to the documentation. Special thanks to Michael (Monty) Widenius, MySQL’s lead developer. He has not only created a ter- rific relational database, but has offered his advice and expertise to the authors of this book. xi 3537-4 FM.f.qc 12/15/00 15:31 Page xi [...]... 10 8 Including files 10 9 Chapter 6 PHP s Built-in Functions 11 1 Function Basics 11 2 Arguments 11 2 Return values 11 3 Function Documentation 11 4 Important PHP 4 Functions 11 4 MySQL... Chapter Chapter 10 11 12 13 14 Catalog 249 Content Management System 285 Threaded Discussion 311 Problem Tracking System 3 31 Shopping Cart 3 61 3537-4 FM.f.qc 12 /15 /00 15 : 31 Page xiii Part V Appendixes Appendix A Appendix B HTML Forms 405 Brief Guide to PHP/ MySQL Installation... 3 01 content/authenticate .php 3 01 content/admin_user .php 304 content/edit_story .php 308 xix 3537-4 FM.f.qc xx 12 /15 /00 15 : 31 Page xx Contents Chapter 12 Threaded Discussion 311 Determining the Scope and Goals of the Application 312 What do you need? ... 11 5 String-handling functions 12 5 Regular expression functions 13 5 xvii 3537-4 FM.f.qc xviii 12 /15 /00 15 : 31 Page xviii Contents Type-conversion functions 14 0 Array functions 14 3 Print functions 14 8 Date/time functions... with PHP Chapter Chapter Chapter Chapter 4 5 6 7 Getting Started with PHP — Variables 71 Control Structures 95 PHP s Built-in Functions 11 1 Writing Organized and Readable Code 16 5 Part III Simple Applications Chapter 8 Chapter 9 Guestbook 2000, the (Semi-)Bulletproof Guestbook 19 3 Survey 215 Part... View My Guest Book!!! < ?php } else { include(“sign .php ); } ?> If the form, which is in sign .php, hasn’t been submitted, it is included and therefore will show the same form You may notice that this page is submitted to itself 3537-4 FM.f.qc 12 /15 /00 15 : 31 Page xxxvii Introduction The first time the create_entry .php page is called, the form in sign .php will be displayed... 17 1 include_once() and require_once() 17 1 User-Defined Functions 17 2 Function basics 17 3 Returning values 17 5 Using a variable number of arguments 17 7 Variable scope 17 8 Object-Oriented Programming... 211 Scripts 214 3537-4 FM.f.qc 12 /15 /00 15 : 31 Page xix Contents Chapter 9 xix Survey 215 Determining the Scope and Goals of the Application 215 Necessary Pages 216 What do we need to prevent? 219 Designing the Database 220... 10 Normalization 10 1st normal form 10 2nd normal form 12 3rd normal form 13 Types of Relationships 13 One-to-many relationship 14 One-to-one relationship 14 ... 16 1 Output buffering 16 2 Chapter 7 Writing Organized and Readable Code 16 5 Indenting 16 5 Code blocks 16 6 Function calls 16 7 SQL statements 16 8 Includes 16 9 . MySQL /PHP Database Applications 3537-4 FM.f.qc 12 /15 /00 15 : 31 Page i 3537-4 FM.f.qc 12 /15 /00 15 : 31 Page ii MySQL /PHP Database Applications Jay Greenspan and. paper) 1. SQL (Computer program language) 2. PHP (Computer program language 3.Web databases. I. Bulger, Brad, 19 59- II. Title. QA76.73.S67G73 20 01 005 .13 ’3 dc 21 00-053995 3537-4 FM.f.qc 12 /15 /00 15 : 31. Services COVER IMAGE © Noma/Images.com 3537-4 FM.f.qc 12 /15 /00 15 : 31 Page vi In memory of Dr. Jonathan B. Postel 3537-4 FM.f.qc 12 /15 /00 15 : 31 Page vii Preface Welcome. If you are thumbing through