PHP & MySQL For Dummies, 4th Edition

Transcription

www.it-ebooks.info

Get More and Do More at Dummies.com Start with FREE Cheat SheetsCheat Sheets include Checklists Charts Common Instructions And Other Good Stuff!To access the Cheat Sheet created specifically for this book, go towww.dummies.com/cheatsheet/phpmysqlGet Smart at Dummies.comDummies.com makes your life easier with 1,000sof answers on everything from removing wallpaperto using the latest version of Windows.Check out our Videos Illustrated Articles Step-by-Step InstructionsPlus, each month you can win valuable prizes by enteringour Dummies.com sweepstakes. *Want a weekly dose of Dummies? Sign up for Newsletters on Digital Photography Microsoft Windows & Office Personal Finance & Investing Health & Wellness Computing, iPods & Cell Phones eBay Internet Food, Home & GardenFind out “HOW” at Dummies.com*Sweepstakes not currently available in all countries; visit Dummies.com for official rules.www.it-ebooks.info

PHP & MySQL‰FORDUMmIES‰4THwww.it-ebooks.infoEDITION

www.it-ebooks.info

PHP & MySQL‰FORDUMmIES‰4THby Janet Valadewww.it-ebooks.infoEDITION

PHP & MySQL For Dummies, 4th EditionPublished byWiley Publishing, Inc.111 River StreetHoboken, NJ 07030-5774www.wiley.comCopyright 2010 by Wiley Publishing, Inc., Indianapolis, IndianaPublished by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaNo part of this publication may be reproduced, stored in a retrieval system or transmitted in any form orby 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 writtenpermission of the Publisher, or authorization through payment of the appropriate per-copy fee to theCopyright 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.Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for theRest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, Making EverythingEasier, 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. All other trademarks are the property of their respectiveowners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book.LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NOREPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OFTHE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BECREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIESCONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THEUNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OROTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OFA COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THEAUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATIONOR WEBSITE 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 WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE.FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVECHANGED 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 CareDepartment within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.For technical support, please visit www.wiley.com/techsupport.Wiley also publishes its books in a variety of electronic formats. Some content that appears in print maynot be available in electronic books.Library of Congress Control Number: 2009940274ISBN: 978-0-470-52758-0Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1www.it-ebooks.info

About the AuthorJanet Valade is the author of PHP & MySQL Web Development All-in-One DeskReference For Dummies, PHP 5 For Dummies, PHP & MySQL Everyday AppsFor Dummies, and PHP & MySQL: Your visual blueprint for creating dynamic,database-driven Web sites, as well as the first, second, and third editions ofthis book. In addition, Janet is the author of Spring into Linux and a coauthorof Mastering Visually Dreamweaver 8 and Flash 8.Janet has twenty years of experience in the computing field. Most recently,she worked as a Web designer and programmer in an engineering firm forfour years. Before that, Janet worked for thirteen years in a university environment, where she was a systems analyst. During her tenure, she supervised the installation and operation of computing resources, designed anddeveloped a data archive, supported faculty and students in their computerusage, wrote numerous technical papers, and developed and presented seminars on a variety of technology topics.To keep in touch, see janetvalade.com.www.it-ebooks.info

www.it-ebooks.info

Author’s AcknowledgmentsFirst, I want to express my appreciation to the entire open source community. Without those who give their time and talent, there would be no coolPHP and MySQL for me to write about. Furthermore, I never would havelearned this software without the lists, where people generously spend theirtime answering foolish questions from beginners.I want to thank my mother for passing on a writing gene, along with manyother things. And my children always for everything. My thanks to my friendsArt, Dick, and Marge for responding to my last-minute call for help. I particularly want to thank Sammy, Dude, Spike, Lucky, Upanishad, Sadie, and E.B. fortheir important contributions.And, of course, I want to thank the professionals who make it all possible.Without the people at Wiley, this book would not exist. Because they all dotheir jobs so well, I can contribute my part to this joint project.www.it-ebooks.info

Publisher’s AcknowledgmentsWe’re proud of this book; please send us your comments at http://dummies.custhelp.com. Forother comments, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.Some of the people who helped bring this book to market include the following:Acquisitions and EditorialComposition ServicesProject Editor: Rebecca Senninger(Previous Edition: Pat O’Brien)Project Coordinator: Kristie ReesAcquisitions Editor: Kyle LooperLayout and Graphics: Melissa K. Jester,Christine WilliamsCopy Editor: Virginia SandersProofreader: Toni SettleTechnical Editor: John GosneyIndexer: BIM Indexing & ProofreadingEditorial Manager: Leah CameronEditorial Assistant: Amanda FoxworthSr. Editorial Assistant: Cherie CaseCartoons: Rich Tennant (www.the5thwave.com)Publishing and Editorial for Technology DummiesRichard Swadley, Vice President and Executive Group PublisherAndy Cummings, Vice President and PublisherMary Bednarek, Executive Acquisitions DirectorMary C. Corder, Editorial DirectorPublishing for Consumer DummiesDiane Graves Steele, Vice President and PublisherComposition ServicesDebbie Stailey, Director of Composition Serviceswww.it-ebooks.info

Contents at a GlanceIntroduction. 1Part I: Developing a Web Database ApplicationUsing PHP and MySQL. 7Chapter 1: Introduction to PHP and MySQL. 9Chapter 2: Setting Up Your Work Environment. 21Chapter 3: Developing a Web Database Application. 47Part II: MySQL Database. 73Chapter 4: Building the Database. 75Chapter 5: Protecting Your Data. 111Part III: PHP. 131Chapter 6: General PHP. 133Chapter 7: PHP Building Blocks for Programs. 165Chapter 8: Data In, Data Out. 211Chapter 9: Moving Information from One Web Page to the Next. 285Part IV: Applications. 305Chapter 10: Putting It All Together. 307Chapter 11: Building an Online Catalog. 321Chapter 12: Building a Members Only Web Site. 359Part V: The Part of Tens. 387Chapter 13: Ten Things You Might Want to Do Using PHP Functions. 389Chapter 14: Ten PHP Gotchas. 397Part VI: Appendixes. 403Appendix A: Installing PHP, MySQL, and Apache from XAMPP. 405Appendix B: Configuring PHP. 415Index. 421www.it-ebooks.info

www.it-ebooks.info

Table of ContentsIntroduction. 1About This Book. 1Conventions Used in This Book. 2What You’re Not To Read. 2Foolish Assumptions. 3How This Book Is Organized. 3Part I: Developing a Web Database ApplicationUsing PHP and MySQL. 4Part II: MySQL Database. 4Part III: PHP. 4Part IV: Applications. 4Part V: The Part of Tens. 4Part VI: Appendixes. 4Icons Used in This Book. 5Where to Go from Here. 5Part I: Developing a Web Database ApplicationUsing PHP and MySQL. 7Chapter 1: Introduction to PHP and MySQL . . . . . . . . . . . . . . . . . . . . . . . 9What Is a Web Database Application?. 9The database: Storing data. 11The application: Moving data in and out of the database. 11MySQL, My Database. 12Advantages of MySQL. 13How MySQL works. 14Communicating with the MySQL server. 14PHP, a Data Mover. 15Advantages of PHP. 16How PHP works. 16MySQL and PHP, the Perfect Pair. 17Advantages of the relationship. 18How MySQL and PHP work together. 18Keeping Up with PHP and MySQL Changes. 19PHP versions. 19MySQL versions. 20www.it-ebooks.info

xiiPHP & MySQL For Dummies, 4th EditionChapter 2: Setting Up Your Work Environment . . . . . . . . . . . . . . . . . . . 21Anatomy of a Web Site. 21Building a Web Site. 22Deciding Where to Publish Your Web Site. 23Using a Web hosting company. 24Using a company Web site. 28Setting up your own server. 29Deciding Where to Develop Your Web Site. 30On your own computer. 30On another computer. 30Setting Up Your Web Site. 31With a Web hosting company. 31On a company Web site. 32Information you need. 33Setting Up Your Development Environment. 34Your own computer. 34Web hosting company. 38A company computer. 39Testing, Testing, 1,2,3. 39Understanding PHP/MySQL functions. 40Testing PHP. 40Testing your local PHP configuration file. 43Testing MySQL. 43Chapter 3: Developing a Web Database Application . . . . . . . . . . . . . . 47Planning Your Web Database Application. 47Identifying what you want from the application. 48Taking the user into consideration. 50Making the site easy to use. 51Leaving room for expansion. 51Writing it down. 52Presenting the Two Running Examples in This Book. 52Stuff for Sale. 52Members Only. 53Designing the Database. 54Choosing the data. 54Organizing the data. 56Designing the Sample Databases. 60Pet Catalog design process. 61Members Only design process. 63Types of Data. 66Character data. 66Numerical data. 66Date and time data. 67Enumeration data. 67www.it-ebooks.info

Table of ContentsMySQL data type names. 67Writing it down. 69Taking a Look at the Sample Database Designs. 69Stuff for Sale database tables. 69Members Only database tables. 70Developing the Application. 71Building the database. 72Writing the programs. 72Part II: MySQL Database. 73Chapter 4: Building the Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Communicating with MySQL. 75Building SQL queries. 76Sending SQL queries. 77Building a Database. 82Creating a new database. 82Viewing the databases. 85Deleting a database. 85Adding tables to a database. 86Changing the database structure. 90Moving Data Into and Out of the Database. 92Adding information. 93Viewing information. 98Retrieving information. 99Combining information from tables. 104Updating information. 109Removing information. 110Chapter 5: Protecting Your Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111Controlling Access to Your Data. 111Understanding account names and hostnames. 112Finding out about passwords. 113Taking a look at account privileges. 115Setting Up MySQL Accounts. 116Adding accounts. 117Allowing access to a database. 118Changing privileges. 120Adding and changing passwords. 121Removing accounts. 121Backing Up Your Data. 122Exporting your data with phpMyAdmin. 123Viewing the Export file. 125Restoring Your Data. 127www.it-ebooks.infoxiii

xivPHP & MySQL For Dummies, 4th EditionPart III: PHP. 131Chapter 6: General PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133Adding a PHP Section to an HTML Page. 133Writing PHP Statements. 136Using PHP Variables. 139Naming a variable. 140Creating and assigning values to variables. 140Dealing with notices. 142Using PHP Constants. 142Working with Numbers. 144Working with Character Strings. 146Single-quoted strings versus double-quoted strings. 147Joining strings. 148Working with Dates and Times. 149Setting local time. 149Formatting a date. 150Storing a timestamp in a variable. 151Using dates with MySQL. 153Comparing Values. 154Making simple comparisons. 155Matching character strings to patterns. 157Joining Comparisons with and/or/xor. 161Adding Comments to Your Program. 163Chapter 7: PHP Building Blocks for Programs . . . . . . . . . . . . . . . . . . . 165Useful Simple Statements. 166Using echo statements. 167Using assignment statements. 170Using increment statements. 171Using exit. 172Using function calls. 173Using PHP Arrays. 173Creating arrays. 173Viewing arrays. 174Removing values from arrays. 176Sorting arrays. 176Getting values from arrays. 178Walking through an array. 180Multidimensional arrays. 183Useful Conditional Statements. 186Using if statements. 187Using switch statements. 190www.it-ebooks.info

Table of ContentsUsing Loops. 191Using for loops. 192Using while loops. 194Using do.while loops. 196Infinite loops. 197Breaking out of a loop. 199Using Functions. 201Using variables in functions. 203Passing values between a function and the main program. 204Using built-in functions. 209Chapter 8: Data In, Data Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211PHP and MySQL Functions. 212Making a Connection. 214Connecting to the MySQL server. 214Selecting the right database. 218Sending SQL queries. 219Getting Information from a Database. 220Sending a SELECT query. 220Getting and using the data. 221Using functions to get data. 228Getting Information from the User. 232Using HTML forms. 233Making forms dynamic. 238Using the information from the form. 251Checking the information. 253Giving users a choice with multiple submit buttons. 263Putting Information into a Database. 265Preparing the data. 265Adding new information. 270Updating existing information. 276Getting Information in Files. 279Using a form to upload the file. 280Processing the uploaded file. 280Putting it all together. 282Chapter 9: Moving Information from One Web Page to the Next . . . 285Moving Your User from One Page to Another. 286Moving Information from Page to Page. 289Adding information to the URL. 290Storing information via cookies. 294Passing information with HTML forms. 297Using PHP Sessions. 298Understanding how PHP sessions work. 298Opening sessions.

DUMmIES ‰ 4 TH EDITION www.it-ebooks.info. . Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and