PHP And MySQL For Dynamic Web Sites GFX PHP.and.My SQL.for.Dynamic.Web.Sites.Visual.Quick Pro.Guide.4th.Edition
00c%20GFX-PHP.and.MySQL.for.Dynamic.Web.Sites.Visual.QuickPro.Guide.4th.Edition
PHP.and.MySQL-libro-biblioteca.for.Dynamic.Web.Sites.Visual.QuickPro.Guide.4th.Edition
User Manual:
Open the PDF directly: View PDF .
Page Count: 726
Download | |
Open PDF In Browser | View PDF |
VISUAL QUICK pro GUIDE PHP and MySQL for Dynamic Web Sites Fourth Edition Larry ULLman Peachpit Press Visual QuickPro Guide PHP and MySQL for Dynamic Web Sites, Fourth Edition Larry Ullman Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: www.peachpit.com To report errors, please send a note to: errata@peachpit.com Peachpit Press is a division of Pearson Education. Copyright © 2012 by Larry Ullman Editor: Rebecca Gulick Copy Editor: Patricia Pane Technical Reviewer: Anselm Bradford Production Coordinator: Myrna Vladic Compositor: Debbie Roberti Proofreader: Bethany Stough Indexer: Valerie Haynes-Perry Cover Design: RHDG / Riezebos Holzbaur Design Group, Peachpit Press Interior Design: Peachpit Press Logo Design: MINE™ www.minesf.com Notice of Rights All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact permissions@peachpit.com. Notice of Liability The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of the book, neither the author nor Peachpit Press 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 instructions contained in this book or by the computer software and hardware products described in it. Trademarks Visual QuickPro Guide is a registered trademark of Peachpit Press, a division of Pearson Education. MySQL is a registered trademark of MySQL AB in the United States and in other countries. Macintosh and Mac OS X are registered trademarks of Apple, Inc. Microsoft and Windows are registered trademarks of Microsoft Corp. Other product names used in this book may be trademarks of their own respective owners. Images of Web sites in this book are copyrighted by the original holders and are used with their kind permission. This book is not officially endorsed by nor affiliated with any of the above companies, including MySQL AB. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations appear as requested by the owner of the trademark. All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book. ISBN-13: 978-0-321-78407-0 ISBN-10: 0-321-78407-3 9 8 7 6 5 4 3 2 1 Printed and bound in the United States of America Dedication Dedicated to the fine faculty at my alma mater, Northeast Missouri State University. In particular, I would like to thank: Dr. Monica Barron, Dr. Dennis Leavens, Dr. Ed Tyler, and Dr. Cole Woodcox, whom I also have the pleasure of calling my friend. I would not be who I am as a writer, as a student, as a teacher, or as a person if it were not for the magnanimous, affecting, and brilliant instruction I received from these educators. Special Thanks to: My heartfelt thanks to everyone at Peachpit Press, as always. My gratitude to editor extraordinaire Rebecca Gulick, who makes my job so much easier. And thanks to Patricia Pane for her hard work, helpful suggestions, and impressive attention to detail. Thanks also to Valerie Haynes-Perry for indexing and Myrna Vladic and Deb Roberti for laying out the book, and thanks to Anselm Bradford for his technical review. Kudos to the good people working on PHP, MySQL, Apache, phpMyAdmin, MAMP, and XAMPP, among other great projects. And a hearty “cheers” to the denizens of the various newsgroups, mailing lists, support forums, etc., who offer assistance and advice to those in need. Thanks, as always, to the readers, whose support gives my job relevance. An extra helping of thanks to those who provided the translations in Chapter 17, “Example—Message Board,” and who offered up recommendations as to what they’d like to see in this edition. Thanks to Karnesha and Sarah for entertaining and taking care of the kids so that I could get some work done. Finally, I would not be able to get through a single book if it weren’t for the love and support of my wife, Jessica. And a special shout-out to Zoe and Sam, who give me reasons to, and not to, write books! Table of Contents Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Chapter 1 Introduction to PHP. . . . . . . . . . . . . . . . . . . . . 1 Basic Syntax . . . . . . . . . . . . . Sending Data to the Web Browser. Writing Comments. . . . . . . . . . What Are Variables?. . . . . . . . . Introducing Strings . . . . . . . . . Concatenating Strings . . . . . . . Introducing Numbers . . . . . . . . Introducing Constants . . . . . . . Single vs. Double Quotation Marks Basic Debugging Steps . . . . . . . Review and Pursue . . . . . . . . . Chapter 2 . . . . . . . . . . . . . . . . . . . . . Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 6 10 14 18 21 23 26 29 32 34 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 41 45 49 54 69 72 Creating Dynamic Web Sites . . . . . . . . . . . . . . 75 Including Multiple Files . . . . . . Handling HTML Forms, Revisited Making Sticky Forms . . . . . . . Creating Your Own Functions . . Review and Pursue . . . . . . . . iv . . . . . . . . . . . Programming with PHP . . . . . . . . . . . . . . . . . 35 Creating an HTML Form . . Handling an HTML Form . . Conditionals and Operators Validating Form Data . . . . Introducing Arrays. . . . . . For and While Loops . . . . Review and Pursue . . . . . Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 85 91 95 110 Chapter 4 Introduction to MySQL . . . . . . . . . . . . . . . . . 111 Naming Database Elements . . . . . Choosing Your Column Types . . . . Choosing Other Column Properties . Accessing MySQL . . . . . . . . . . . Review and Pursue . . . . . . . . . . Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 114 118 121 128 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 133 138 140 143 145 1 47 149 151 153 164 Database Design . . . . . . . . . . . . . . . . . . . . . 165 Normalization . . . . . . . . Creating Indexes . . . . . . Using Different Table Types Languages and MySQL . . . Time Zones and MySQL . . Foreign Key Constraints . . Review and Pursue . . . . . Chapter 7 . . . . . Introduction to SQL. . . . . . . . . . . . . . . . . . . . 129 Creating Databases and Tables Inserting Records . . . . . . . . Selecting Data . . . . . . . . . . Using Conditionals . . . . . . . Using LIKE and NOT LIKE . . . . Sorting Query Results. . . . . . Limiting Query Results . . . . . Updating Data . . . . . . . . . . Deleting Data . . . . . . . . . . Using Functions . . . . . . . . . Review and Pursue . . . . . . . Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 179 182 184 189 195 202 Advanced SQL and MySQL . . . . . . . . . . . . . . . 203 Performing Joins. . . . . . . . . . Grouping Selected Results . . . Advanced Selections . . . . . . . Performing FULLTEXT Searches Optimizing Queries . . . . . . . . Performing Transactions . . . . . Database Encryption . . . . . . . Review and Pursue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 214 218 222 230 234 237 240 Table of Contents v Chapter 8 Error Handling and Debugging . . . . . . . . . . . . 241 Error Types and Basic Debugging . . . . . Displaying PHP Errors. . . . . . . . . . . . Adjusting Error Reporting in PHP . . . . . Creating Custom Error Handlers. . . . . . PHP Debugging Techniques . . . . . . . . SQL and MySQL Debugging Techniques . Review and Pursue . . . . . . . . . . . . . Chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Table of Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 248 250 253 258 262 264 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 268 273 28 1 285 290 292 298 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 304 309 . 316 323 328 Web Application Development . . . . . . . . . . . . 329 Sending Email . . . . . . . . . . Handling File Uploads . . . . . PHP and JavaScript . . . . . . . Understanding HTTP Headers. Date and Time Functions . . . . Review and Pursue . . . . . . . vi . . . . . . . Common Programming Techniques . . . . . . . . . 299 Sending Values to a Script Using Hidden Form Inputs Editing Existing Records . Paginating Query Results. Making Sortable Displays Review and Pursue . . . . Chapter 11 . . . . . . . Using PHP with MySQL . . . . . . . . . . . . . . . . . 265 Modifying the Template. . . Connecting to MySQL. . . . Executing Simple Queries . Retrieving Query Results . Ensuring Secure SQL . . . . Counting Returned Records Updating Records with PHP Review and Pursue . . . . . Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330 336 348 355 362 366 Chapter 12 Cookies and Sessions . . . . . . . . . . . . . . . . . . 367 Making a Login Page . . . . Making the Login Functions Using Cookies . . . . . . . . Using Sessions. . . . . . . . Improving Session Security Review and Pursue . . . . . Chapter 13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 371 376 388 396 400 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402 409 414 418 42 1 425 432 Perl-Compatible Regular Expressions . . . . . . . . 433 Creating a Test Script . . . . . . . Defining Simple Patterns . . . . . Using Quantifiers . . . . . . . . . Using Character Classes . . . . . Finding All Matches . . . . . . . . Using Modifiers . . . . . . . . . . Matching and Replacing Patterns Review and Pursue . . . . . . . . Chapter 15 . . . . . . Security Methods . . . . . . . . . . . . . . . . . . . . . 401 Preventing Spam . . . . . . . . . Validating Data by Type. . . . . . Validating Files by Type. . . . . . Preventing XSS Attacks. . . . . . Using the Filter Extension . . . . Preventing SQL Injection Attacks Review and Pursue . . . . . . . . Chapter 14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434 438 4 41 443 446 450 452 456 Introducing jQuery . . . . . . . . . . . . . . . . . . . . 457 What is jQuery? . . . . . . Incorporating jQuery . . . Using jQuery . . . . . . . . Selecting Page Elements . Event Handling. . . . . . . DOM Manipulation . . . . Using Ajax . . . . . . . . . Review and Pursue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458 460 463 466 469 473 479 492 Table of Contents vii Chapter 16 An OOP Primer . . . . . . . . . . . . . . . . . . . . . . . . 493 Fundamentals and Syntax Working with MySQL . . . The DateTime Class . . . . Review and Pursue . . . . Chapter 17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494 497 511 518 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520 537 538 543 548 558 Example —User Registration . . . . . . . . . . . . . . 559 Creating the Templates . . . . . . Writing the Configuration Scripts Creating the Home Page . . . . . Registration . . . . . . . . . . . . Activating an Account. . . . . . . Logging In and Logging Out . . . Password Management. . . . . . Review and Pursue . . . . . . . . Chapter 19 . . . . Example—Message Board . . . . . . . . . . . . . . . 519 Making the Database . . . Creating the Index Page . Creating the Forum Page . Creating the Thread Page Posting Messages . . . . . Review and Pursue . . . . Chapter 18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560 566 5 74 576 586 589 594 604 Example —E-Commerce . . . . . . . . . . . . . . . . . 605 Creating the Database . . . . The Administrative Side . . . Creating the Public Template The Product Catalog . . . . . The Shopping Cart . . . . . . Recording the Orders . . . . . Review and Pursue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606 612 629 633 645 654 659 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661 BonuS AppenDix Appendix A Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . A1 viii Table of Contents Introduction Today’s Web users expect exciting pages that are updated frequently and provide a customized experience. For them, Web sites are more like communities, to which they’ll return time and again. At the same time, Web-site administrators want sites that are easier to update and maintain, understanding that’s the only reasonable way to keep up with visitors’ expectations. For these reasons and more, PHP and MySQL have become the de facto standards for creating dynamic, databasedriven Web sites. This book represents the culmination of my many years of Web development experience coupled with the value of having written several previous books on the technologies discussed herein. The focus of this book is on covering the most important knowledge in the most efficient manner. It will teach you how to begin developing dynamic Web sites and give you plenty of example code to get you started. All you need to provide is an eagerness to learn. What Are Dynamic Web Sites? Dynamic Web sites are flexible and potent creatures, more accurately described as applications than merely sites. Dynamic Web sites n n n n n Respond to different parameters (for example, the time of day or the version of the visitor’s Web browser) Have a “memory,” allowing for user registration and login, e-commerce, and similar processes Almost always integrate HTML forms, allowing visitors to perform searches, provide feedback, and so forth Often have interfaces where administrators can manage the site’s content Are easier to maintain, upgrade, and build upon than statically made sites Well, that and a computer. Introduction ix There are many technologies available for creating dynamic Web sites. The most common are ASP.NET (Active Server Pages, a Microsoft construct), JSP (Java Server Pages), ColdFusion, Ruby on Rails (a Web development framework for the Ruby programming language), and PHP. Dynamic Web sites don’t always rely on a database, but more and more of them do, particularly as excellent database applications like MySQL are available at little to no cost. What is pHp? PHP originally stood for “Personal Home Page” as it was created in 1994 by Rasmus Lerdorf to track the visitors to his online résumé. As its usefulness and capabilities grew (and as it started being used in more professional situations), it came to mean “PHP: Hypertext Preprocessor.” According to the official PHP Web site, found at www.php.net A, PHP is a “widely used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.” It’s a long but descriptive definition, whose meaning I’ll explain. A The home page for PHP. x Introduction Starting at the end of that statement, to say that PHP can be embedded into HTML means that you can take a standard HTML page, drop in some PHP wherever you need it, and end up with a dynamic result. This attribute makes PHP very approachable for anyone that’s done even a little bit of HTML work. Also, PHP is a scripting language, as opposed to a compiled language: PHP was designed to write Web scripts, not stand-alone applications (although, with some extra effort, you can now create applications in PHP). PHP scripts run only after an event occurs—for example, when a user submits a form or goes to a URL (Uniform Resource Locator, the technical term for a Web address). I should add to this definition that PHP is a server-side, cross-platform technology, both descriptions being important. Serverside refers to the fact that everything PHP does occurs on the server. A Web server application, like Apache or Microsoft’s IIS (Internet Information Services), is required and all PHP scripts must be accessed through a URL (http://something). Its What Happened to pHp 6? When I wrote the previous version of this book, PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide, the next major release of PHP— PHP 6—was approximately 50 percent complete. Thinking that PHP 6 would therefore be released sometime after the book was published, I relied upon a beta version of PHP 6 for a bit of that edition’s material. And then… PHP 6 died. One of the key features planned for PHP 6 was support for Unicode, meaning that PHP 6 would be able to work natively with any language. This would be a great addition to an already popular programming tool. Unfortunately, implementing Unicode support went from being complicated to quite difficult, and the developers behind the language tabled development of PHP 6. Not all was lost, however: Some of the other features planned for PHP 6, such as support for namespaces (an ObjectOriented Programming concept), were added to PHP 5.3. At the time of this writing, it’s not clear when Unicode support might be completed or what will happen with PHP 6. My hunch is that PHP will be making incremental developments along the version 5 trunk for some time to come. cross-platform nature means that PHP runs on most operating systems, including Windows, Unix (and its many variants), and Macintosh. More important, the PHP scripts written on one server will normally work on another with little or no modification. At the time this book was written, PHP was at version 5.3.6 and this book does assume you’re using at least version 5.0. Some functions and features covered will require more specific or current versions, like PHP 5.2 or greater. In those cases, I will make it clear when the functionality was added to PHP, and provide alternative solutions if you have a slightly older version of the language. If you’re still using version 4 of PHP, you really should upgrade. If that’s not in your plans, then please grab the second edition of this book instead. More information about PHP can always be found at PHP.net or at Zend (www.zend.com), the minds behind the core of PHP. Why use pHp? Put simply, when it comes to developing dynamic Web sites, PHP is better, faster, and easier to learn than the alternatives. What you get with PHP is excellent performance, a tight integration with nearly every database available, stability, portability, and a nearly limitless feature set due to its extendibility. All of this comes at no cost (PHP is open source) and with a very manageable learning curve. PHP is one of the best marriages I’ve ever seen between the ease with which beginning programmers can start using it and the ability for more advanced programmers to do everything they require. Finally, the proof is in the pudding: PHP has seen an exponential growth in use since its inception, and is the server-side Introduction xi technology of choice on over 76 percent of all Web sites B. In terms of all programming languages, PHP is the fifth most popular C. Of course, you might assume that I, as the author of a book on PHP (several, actually), have a biased opinion. Although not nearly to the same extent as PHP, I’ve also developed sites using Java Server Pages (JSP), Ruby on Rails (RoR), and ASP.NET. Each has its pluses and minuses, but PHP is the technology I always return to. You might hear that it doesn’t perform or scale as well as other technologies, but Yahoo!, Wikipedia, and Facebook all use PHP, and you can’t find many sites more visited or demanding than those. You might also wonder how secure PHP is. But security isn’t in the language; it’s in how that language is used. Rest assured that a complete and up-to-date discussion of all the relevant security concerns is provided by this book. B The Web Technology Surveys site provides this graphic regarding server-side technologies (www.w3techs.com/technologies/overview/ programming_language/all). How pHp works As previously stated, PHP is a server-side language. This means that the code you write in PHP sits on a host computer called a server. The server sends Web pages to the requesting visitors (you, the client, with your Web browser). When a visitor goes to a Web site written in PHP, the server reads the PHP code and then processes it according to its scripted directions. In the example shown in D, the PHP code tells the server to send the appropriate data—HTML code—to the Web browser, which treats the received code as it would a standard HTML page. This differs from a static HTML site where, when a request is made, the server merely sends the HTML data to the Web browser and there is no server-side interpretation C The Tiobe Index (http://www.tiobe.com/ index.php/content/paperinfo/tpci/index.html) uses a combination of factors to rank the popularity of programming languages. D How PHP fits into the client/server model when a user requests a Web page. xii Introduction occurring E. Because no server-side action is required, you can run HTML pages in your Web browser without using a server at all. To the end user and the Web browser there is no perceptible difference between what home.html and home.php may look like, but how that page’s content was created will be significantly different. What is MySQL? MySQL (www.mysql.com) F is the world’s most popular open-source database. In fact, today MySQL is a viable competitor to the pricey goliaths such as Oracle and Microsoft’s SQL Server (and, ironically, MySQL is owned by Oracle). Like PHP, MySQL offers excellent performance, portability, and reliability, with a moderate learning curve and little to no cost. MySQL is a database management system (DBMS) for relational databases (therefore, MySQL is an RDBMS). A database, in the simplest terms, is a collection of data, be it text, numbers, or binary files, stored and kept organized by the DBMS. There are many types of databases, from the simple flat-file to relational and objectoriented. A relational database uses multiple tables to store information in its most discernible parts. While relational databases may involve more thought in the design and programming stages, they offer improved reliability and data integrity that more than makes up for the extra effort required. Further, relational databases are more searchable and allow for concurrent users. E The client/server process when a request for a static HTML page is made. F The home page for the MySQL database application. Introduction xiii By incorporating a database into a Web application, some of the data generated by PHP can be retrieved from MySQL G. This further moves the site’s content from a static (hard-coded) basis to a flexible one, flexibility being the key to a dynamic Web site. more than 5 billion rows. MySQL can work with tables as large as 8 million terabytes on some operating systems, generally a healthy 4 GB otherwise. MySQL is used by NASA and the United States Census Bureau, among many others. MySQL is an open-source application, like PHP, meaning that it is free to use or even modify (the source code itself is downloadable). There are occasions in which you should pay for a MySQL license, especially if you are making money from the sales or incorporation of the MySQL product. Check MySQL’s licensing policy for more information on this. At the time of this writing, MySQL is on version 5.5.13, with versions 5.6 and 6.0 in development. The version of MySQL you have affects what features you can use, so it’s important that you know what you’re working with. For this book, MySQL 5.1.44 and 5.5.8 were used, although you should be able to do everything in this book as long as you’re using a version of MySQL greater than 5.0. The MySQL software consists of several pieces, including the MySQL server (mysqld, which runs and manages the databases), the MySQL client (mysql, which gives you an interface to the server), and numerous utilities for maintenance and other purposes. PHP has always had good support for MySQL, and that is even more true in the most recent versions of the language. MySQL has been known to handle databases as large as 60,000 tables with pronunciation Guide Trivial as it may be, I should clarify up front that MySQL is technically pronounced “My Ess Que Ell,” just as SQL should be said “Ess Que Ell.” This is a question many people have when first working with these technologies. While not a critical issue, it’s always best to pronounce acronyms correctly. G How most of the dynamic Web applications in this book will work, using both PHP and MySQL. xiv Introduction What You’ll need About This Book To follow the examples in this book, you’ll need the following tools: This book teaches how to develop dynamic Web sites with PHP and MySQL, covering the knowledge that most developers might require. In keeping with the format of the Visual QuickPro series, the information is discussed using a step-by-step approach with corresponding images. The focus has been kept on real-world, practical examples, avoiding “here’s something you could do but never would” scenarios. As a practicing Web developer myself, I wrote about the information that I use and avoided those topics immaterial to the task at hand. As a practicing writer, I made certain to include topics and techniques that I know readers are asking about. n A Web server application (for example, Apache, Abyss, or IIS) n PHP n MySQL n n n A Web browser (Microsoft’s Internet Explorer, Mozilla’s Firefox, Apple’s Safari, Google’s Chrome, etc.) A text editor, PHP-capable WYSIWYG application (Adobe’s Dreamweaver qualifies), or IDE (integrated development environment) An FTP application, if using a remote server One of the great things about developing dynamic Web sites with PHP and MySQL is that all of the requirements can be met at no cost whatsoever, regardless of your operating system! Apache, PHP, and MySQL are each free; Web browsers can be had without cost; and many good text editors are available for nothing. The appendix, which you can download from http://www.peachpit.com, discusses the installation process on the Windows and Mac OS X operating systems. If you have a computer, you are only a couple of downloads away from being able to create dynamic Web sites (in that case, your computer would represent both the client and the server in D and E). Conversely, you could purchase Web hosting for only dollars per month that will provide you with a PHP- and MySQLenabled environment already online. To download this book's appendix from peachpit.com, create a free account at http:// peachpit.com, and then register this book using ISBN number 0321784073. Once registered, you'll have access to the bonus content. The structure of the book is linear, and the intention is that you’ll read it in order. It begins with three chapters covering the fundamentals of PHP (by the second chapter, you will have already developed your first dynamic Web page). After that, there are four chapters on SQL (Structured Query Language, which is used to interact with all databases) and MySQL. Those chapters teach the basics of SQL, database design, and the MySQL application in particular. Then there’s one chapter on debugging and error management, information everyone needs. This is followed by a chapter introducing how to use PHP and MySQL together, a remarkably easy thing to do. The following five chapters teach more application techniques to round out your knowledge. Security, in particular, is repeatedly addressed in those pages. Two new chapters, to be discussed momentarily, expand your newfound knowledge. Finally, I’ve included three example chapters, in which the heart of different Web applications are developed, with instructions. Introduction xv is this book for you? What’s new in this edition This book was written for a wide range of people within the beginner-to-intermediate range. The book makes use of XHTML, so solid experience with XHTML or HTML is a must. Although this book covers many things, it does not formally teach HTML or Web-page design. Some CSS is sprinkled about these pages but also not taught. The first three editions of this book have been very popular, and I’ve received a lot of positive feedback on them (thanks!). In writing this new edition, I wanted to do more than just update the material for the latest versions of PHP and MySQL, although that is an overriding consideration throughout the book. Other new features you’ll find are: Second, this book expects that you have one of the following: n n n n The drive and ability to learn without much hand holding, or… Familiarity with another programming language (even solid JavaScript skills would qualify), or… n n A cursory knowledge of PHP Make no mistake: This book covers PHP and MySQL from A to Z, teaching everything you’ll need to know to develop real-world Web sites, but particularly the early chapters cover PHP at a quick pace. For this reason I recommend either some programming experience or a curious and independent spirit when it comes to learning new things. If you find that the material goes too quickly, you should probably start off with the latest edition of my book PHP for the World Wide Web: Visual QuickStart Guide, which goes at a much more tempered pace. No database experience is required, since SQL and MySQL are discussed starting at a more basic level. n n n n n New examples demonstrating techniques frequently requested by readers Even more advanced MySQL and SQL instruction and examples A tutorial on using the jQuery JavaScript framework An introduction to the fundamentals and basic usage of Object-Oriented Programming Even more information and examples for improving the security of your scripts and sites Expanded and updated installation and configuration instructions Removal of outdated content (e.g., things used in older versions of PHP or no longer applicable) A “Review and Pursue” section at the end of each chapter, with review questions and prompts for ways in which you can further expand your knowledge based upon the information just covered For those of you that also own a previous edition (thanks, thanks, thanks!), I believe that these new features will also make this edition a required fixture on your desk or bookshelf. xvi Introduction How this book compares to my other books book focuses almost exclusively on MySQL (there are but two chapters that use PHP). This is my fourth PHP and/or MySQL title, after (in order) With that in mind, read the section “Is this book for you?” and see if the requirements apply. If you have no programming experience at all and would prefer to be taught PHP more gingerly, my first book would be better. If you are already very comfortable with PHP and want to learn more of its advanced capabilities, pick up the second. If you are most interested in MySQL and are not concerned with learning much about PHP, check out the third. n n n PHP for the World Wide Web: Visual QuickStart Guide PHP 5 Advanced for the World Wide Web: Visual QuickPro Guide MySQL: Visual QuickStart Guide I hope this résumé implies a certain level of qualification to write this book, but how do you, as a reader standing in a bookstore, decide which title is for you? Of course, you are more than welcome to splurge and buy the whole set, earning my eternal gratitude, but… The PHP for the World Wide Web: Visual QuickStart Guide book is very much a beginner’s guide to PHP. This title overlaps it some, mostly in the first three chapters, but uses new examples so as not to be redundant. For novices, this book acts as a follow-up to that one. The advanced book is really a sequel to this one, as it assumes a fair amount of knowledge and builds upon many things taught here. The MySQL That being said, if you want to learn everything you need to know to begin developing dynamic Web sites with PHP and MySQL today, then this is the book for you! It references the most current versions of both technologies, uses techniques not previously discussed in other books, and contains its own unique examples. And whatever book you do choose, make sure you’re getting the most recent edition or, barring that, the edition that best matches the versions of the technologies you’ll be using. Introduction xvii Companion Web Site I have developed a companion Web site specifically for this book, which you may reach at www.LarryUllman.com. There you will find every script from this book, a text file containing lengthy SQL commands, and a list of errata that occurred during publication. (If you have problems with a command or script, and you are following the book exactly, check the errata to ensure there is not a printing error before driving yourself absolutely mad.) At this Web site you will also find useful Web links, a popular forum where readers can ask and answer each other’s questions (I answer many of them myself), and more! Questions, comments, or suggestions? If you have any questions on PHP or MySQL, you can turn to one of the many Web sites, mailing lists, newsgroups, and FAQ repositories already in existence. A quick search online will turn up virtually unlimited resources. For that matter, if you need an immediate answer, those sources or a quick Web search will most assuredly serve your needs (in all likelihood, someone else has already seen and solved your exact problem). You can also direct your questions, comments, and suggestions to me. You’ll get the fastest reply using the book’s corresponding forum (I always answer those questions first). If you’d rather email me, my contact information is available on the Web site. I do try to answer every email I receive, although I cannot guarantee a quick reply. xviii Introduction publisher’s Tip: Check out the Accompanying Video Training from Author Larry ullman! Visual QuickStart Guides are now even more visual: Building on the success of the top-selling Visual QuickStart Guide books, Peachpit now offers Video QuickStarts. As a companion to this book, Peachpit offers more than an hour of short, task-based videos that will help you master key features and techniques; instead of just reading about how to write PHP and MySQL scripts, you can watch it in action. It’s a great way to learn all the basics and some of the newer or more complex features of the languages. Log on to the Peachpit site at www.peachpit. com/register to register your book, and you’ll find a free streaming sample; purchasing the rest of the material is quick and easy. 1 Introduction to PHP Although this book focuses on using MySQL and PHP in combination, you’ll do a vast majority of your legwork using PHP alone. In this and the following chapter, you’ll learn its basics, from syntax to variables, operators, and language constructs (conditionals, loops, and whatnot). At the same time you are picking up these fundamentals, you’ll also begin developing usable code that you’ll integrate into larger applications later in the book. This introductory chapter will cruise through most of the basics of the PHP language. You’ll learn the syntax for coding PHP, how to send data to the Web browser, and how to use two kinds of variables (strings and numbers) plus constants. Some of the examples may seem inconsequential, but they’ll demonstrate ideas you’ll have to master in order to write more advanced scripts further down the line. The chapter concludes with some quick debugging tips…you know…just in case! in This Chapter 2 Sending Data to the Web Browser 6 Writing Comments 10 What Are Variables? 14 Introducing Strings 18 Concatenating Strings 21 Introducing Numbers 23 Introducing Constants 26 Single vs. Double Quotation Marks 29 Basic Debugging Steps 33 Review and Pursue 34 Basic Syntax As stated in the book’s introduction, PHP is an HTML-embedded scripting language, meaning that you can intermingle PHP and HTML code within the same file. So to begin programming with PHP, start with a simple Web page. Script 1.1 is an example of a no-frills, no-content XHTML Transitional document, which will be used as the foundation for most Web pages in the book (this book does not formally discuss [X]HTML; see a resource dedicated to the topic for more information). Please also note that the template uses UTF-8 encoding, a topic discussed in the sidebar. Script 1.1 A basic XHTML 1.0 Transitional Web page. 1 2 3 4 5 6 7 8 9 10Page Title To add PHP code to a page, place it within PHP tags: understanding encoding Encoding is a huge subject, but what you most need to understand is this: the encoding you use in a file dictates what characters can be represented (and therefore, what languages can be used). To select an encoding, you must first confirm that your text editor or Integrated Development Environment (IDE)—whatever application you’re using to create the HTML and PHP scripts—can save documents using that encoding. Some applications let you set the encoding in the preferences or options area; others set the encoding when you save the file. To indicate the encoding to the Web browser, there’s the corresponding meta tag: The charset=utf-8 part says that UTF-8 encoding is being used, short for 8-bit Unicode Transformation Format. Unicode is a way of reliably representing every symbol in every alphabet. Version 6 of Unicode—the current version at the time of this writing—supports over 99,000 characters! If you want to create a multilingual Web page, UTF-8 is the way to go, and I’ll be using it in this book’s examples. You don’t have to, of course. But whatever encoding you do use, make sure that the encoding indicated by the XHTML page matches the actual encoding set in your text editor or IDE. If you don’t, you’ll likely see odd characters when you view the page in a Web browser. 2 Chapter 1 Script 1.2 This first PHP script doesn’t do anything, but does demonstrate how a PHP script is written. It’ll also be used as a test script, prior to getting into elaborate PHP code. 1 5 6 7 8 9Basic PHP Page This is standard HTML.
10 11 12 13 2 3 4 HTML5 At the time of this writing, the next major release of HTML—HTML5—is being actively developed and discussed, but is not production ready, which is why I chose not to use it in the book. In fact, I wouldn’t be surprised if HTML5 is still not released by the time I start the fifth edition of this book, and it will take even longer for broad browser adoption of the language. Still, as HTML5 is an exciting future development, this book will occasionally mention features you can expect to see introduced and supported over time. Anything written within these tags will be treated by the Web server as PHP, meaning the PHP interpreter will process the code. Any text outside of the PHP tags is immediately sent to the Web browser as regular HTML. (Because PHP is most often used to create content displayed in the Web browser, the PHP tags are normally put somewhere within the page’s body.) Along with placing PHP code within PHP tags, your PHP files must have a proper extension. The extension tells the server to treat the script in a special way, namely, as a PHP page. Most Web servers use .html for standard HTML pages and .php for PHP files. Before getting into the steps, understand that you must already have a working PHP installation! This could be on a hosted site or your own computer, after following the instructions in Appendix A, “Installation,” which is a free download from peachpit.com. To make a basic pHp script: 1. Create a new document in your text editor or IDE, to be named first.php (Script 1.2). It generally does not matter what application you use, be it Adobe Dreamweaver (a fancy IDE), TextMate (a great and popular Macintosh plaintext editor), or vi (a plain-text Unix editor, lacking a graphical interface). Still, some text editors and IDEs make typing and debugging HTML and PHP easier (conversely, Notepad on Windows does some things that makes coding harder: don’t use Notepad!). If you don’t already have an application you’re attached to, search the Web or use the book’s corresponding forum (www.LarryUllman.com/forums/) to find one. continues on next page Introduction to PHP 3 2. Create a basic HTML document:Basic PHP Page This is standard HTML.
Although this is the syntax being used throughout the book, you can change the HTML to match whichever standard you intend to use (e.g., HTML 4.0 Strict). Again, see a dedicated (X)HTML resource if you’re unfamiliar with any of this HTML code. 3. Before the closing body tag, insert the PHP tags: These are the formal PHP tags, also known as XML-style tags. Although PHP supports other tag types, I recommend that you use the formal type, and I will do so throughout this book. 4. Save the file as first.php. Remember that if you don’t save the file using an appropriate PHP extension, the script will not execute properly. (Just one of the reasons not to use Notepad is that it will secretly add the .txt extension to PHP files, thereby causing many headaches.) 5. Place the file in the proper directory of your Web server. If you are running PHP on your own computer (presumably after following the installation directions in Appendix A), you just need to move, copy, or save the file to a specific folder on your computer. Check Appendix A or the documentation for your particular Web server to identify the correct directory, if you don’t already know what it is. If you are running PHP on a hosted server (i.e., on a remote computer), you’ll need to use a File Transfer Protocol (FTP) application to upload the file to the proper directory. Your hosting company will provide you with access and the other necessary information. 6. Run first.php in your Web browser A. Because PHP scripts need to be parsed by the server, you absolutely must access them via a URL (i.e., the address in the browser must begin with http://). You cannot simply open them in your Web browser as you would a file in other applications (in which case the address would start with file:// or C:\ or the like). A While it seems like any other (simple) HTML page, this is in fact a PHP script and the basis for the rest of the examples in the book. 4 Chapter 1 If you are running PHP on your own computer, you’ll need to use a URL like http://localhost/first.php, http://127.0.0.1/first.php, or http:// localhost/~/first.php (on Mac OS X, using your actual username for ). If you are using a Web host, you’ll need to use http://your-domain-name/ first.php (e. g., http://www.example. com/first.php). 7. If you don’t see results like those in A, start debugging! Part of learning any programming language is mastering debugging. It’s a sometimes-painful but absolutely necessary process. With this first example, if you don’t see a simple, but perfectly valid, Web page, follow these steps: 1. Confirm that you have a working PHP installation (see Appendix A for testing instructions). 2. Make sure that you are running the script through a URL. The address in the Web browser must begin with http://. If it starts with file://, that’s a problem B. 3. If you get a file not found (or similar) error, you’ve likely put the file in the wrong directory or mistyped the file’s name (either when saving it or in your Web browser). If you’ve gone through all this and are still having problems, turn to the book’s corresponding forum (www.LarryUllman.com/forums/). To find more information about HTML and XHTML, check out Elizabeth Castro’s excellent book HTML, XHTML, and CSS, Sixth Edition: Visual QuickStart Guide, (Peachpit Press, 2006) or search the Web. You can embed multiple sections of PHP code within a single HTML document (i.e., you can go in and out of the two languages). You’ll see examples of this throughout the book. Prior to UTF-8, ISO-8859-1 was one of the more commonly used encodings. It represents most Western European languages. It’s still the default encoding for many Web browsers and other applications. You can declare the encoding of an external CSS file by adding @charset "utf-8"; as the first line in the file. If you’re not using UTF-8, change the line accordingly. B PHP code will only be executed when run through http: / / (not that this particular script is affected either way). Introduction to PHP 5 Sending Data to the Web Browser To create dynamic Web sites with PHP, you must know how to send data to the Web browser. PHP has a number of built-in functions for this purpose, the most common being echo and print. I personally tend to favor echo: echo 'Hello, world!'; echo "What's new?"; You could use print instead, if you prefer (the name more obviously indicates what it does): print 'Hello, world!'; print "What's new?"; As you can see from these examples, you can use either single or double quotation marks (but there is a distinction between the two types of quotation marks, which will be made clear by the chapter’s end). The first quotation mark after the function name indicates the start of the message to be printed. The next matching quotation mark (i.e., the next quotation mark of the same kind as the opening mark) indicates the end of the message to be printed. Along with learning how to send data to the Web browser, you should also notice that in PHP all statements—a line of executed code, in layman’s terms—must end with a semicolon. Also, PHP is caseinsensitive when it comes to function names, so ECHO, echo, eCHo, and so forth will all work. The all-lowercase version is easiest to type, of course. 6 Chapter 1 needing an escape As you might discover, one of the complications with sending data to the Web involves printing single and double quotation marks. Either of the following will cause errors: echo "She said, "How are you?""; echo 'I'm just ducky.'; There are two solutions to this problem. First, use single quotation marks when printing a double quotation mark and vice versa: echo 'She said, "How are you?"'; echo "I'm just ducky."; Or, you can escape the problematic character by preceding it with a backslash: echo "She said, \"How are you?\""; echo 'I\'m just ducky.'; An escaped quotation mark will merely be printed like any other character. Understanding how to use the backslash to escape a character is an important concept, and one that will be covered in more depth at the end of the chapter. Script 1.3 Using print or echo, PHP can send data to the Web browser. 1 5 6 7 8 9 10 Using Echo This is standard HTML.
2 3 4 To send data to the Web browser: 1. Open first.php (refer to Script 1.2) in your text editor or IDE. 2. Between the PHP tags (lines 10 and 11), add a simple message (Script 1.3): echo 'This was generated using ➝ PHP!'; It truly doesn’t matter what message you type here, which function you use (echo or print), or which quotation marks, for that matter—just be careful if you are printing a single or double quotation mark as part of your message (see the sidebar “Needing an Escape”). 3. If you want, change the page title to better describe this script (line 5):Using Echo This change only affects the browser window’s title bar. A The results still aren’t glamorous, but this page was in part dynamically generated by PHP. 4. Save the file as second.php, place it in your Web directory, and test it in your Web browser A. Remember that all PHP scripts must be run through a URL (http://something)! continues on next page Introduction to PHP 7 5. If necessary, debug the script. If you see a parse error instead of your message B, check that you have both opened and closed your quotation marks and escaped any problematic characters (see the sidebar). Also be certain to conclude each statement with a semicolon. B This may be the first of many parse errors you see as a PHP programmer (this one is caused by the omission of the terminating quotation mark). If you see an entirely blank page, this is probably for one of two reasons: > There is a problem with your HTML. Test this by viewing the source of your page and looking for HTML problems there C. > An error occurred, but display_errors is turned off in your PHP configuration, so nothing is shown. In this case, see the section in Appendix A on how to configure PHP so that you can turn display_errors back on. Technically, echo and print are language constructs, not functions. That being said, don’t be flummoxed as I continue to call them “functions” for convenience. Also, as you’ll see later in the book, I include the parentheses when referring to functions— say number_format( ), not just number_ format—to help distinguish them from variables and other parts of PHP. This is just my own little convention. You can, and often will, use echo and print to send HTML code to the Web browser, like so D: echo 'Hello, world!
'; 8 Chapter 1 C One possible cause of a blank PHP page is a simple HTML error, like the closing title tag here (it’s missing the slash). D PHP can send HTML code (like the formatting here) as well as simple text A to the Web browser. Echo and print can both be used over multiple lines: echo 'This sentence is printed over two lines.'; E Printing text and HTML over multiple PHP lines will generate HTML source code that also extends over multiple lines. Note that extraneous white spacing in the HTML source will not affect the look of a page F but can make the source easier to review. What happens in this case is that the return (created by pressing Enter or Return) becomes part of the printed message, which isn’t terminated until the closing quotation mark. The net result will be the “printing” of the return in the HTML source code E. This will not have an effect on the generated page F. For more on this, see the sidebar “Understanding White Space.” F The return in the HTML source E has no effect on the rendered result. The only way to alter the spacing of a displayed Web page is to use HTML tags (like
and ). understanding White Space With PHP you send data (like HTML tags and text) to the Web browser, which will, in turn, render that data as the Web page the end user sees. Thus, what you are often doing with PHP is creating the HTML source of a Web page. With this in mind, there are three areas of notable white space (extra spaces, tabs, and blank lines): in your PHP scripts, in your HTML source, and in the rendered Web page. PHP is generally white space insensitive, meaning that you can space out your code however you want to make your scripts more legible. HTML is also generally white space insensitive. Specifically, the only white space in HTML that affects the rendered page is a single space (multiple spaces still get rendered as one). If your HTML source has text on multiple lines, that doesn’t mean it’ll appear on multiple lines in the rendered page (E and F). To alter the spacing in a rendered Web page, use the HTML tags
(line break,
in older HTML standards) and (paragraph). To alter the spacing of the HTML source created with PHP, you can . Use echo or print over the course of several lines. or . Print the newline character (\n) within double quotation marks, which is equivalent to Enter or Return. Introduction to PHP 9 Writing Comments Creating executable PHP code is only a part of the programming process (admittedly, it’s the most important part). A secondary but still crucial aspect to any programming endeavor involves documenting your code. In fact, when I’m asked what qualities distinguish the beginning programmer from the more experienced one, a good and thorough use of comments is my unwavering response. In HTML you can add comments using special tags: HTML comments are viewable in the source but do not appear in the rendered page (see E and F in the previous section). PHP comments are different in that they aren’t sent to the Web browser at all, meaning they won’t be viewable to the end user, even when looking at the HTML source. PHP supports three comment syntaxes. The first uses the pound or number symbol (#): # This is a comment. The second uses two slashes: // This is also a comment. Both of these cause PHP to ignore everything that follows until the end of the line (when you press Return or Enter). Thus, these two comments are for single lines only. They are also often used to place a comment on the same line as some PHP code: print 'Hello!'; // Say hello. A third style allows comments to run over multiple lines: /* This is a longer comment that spans two lines. */ 10 Chapter 1 Script 1.4 These basic comments demonstrate the three comment syntaxes you can use in PHP. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15Comments This is a line of text.
This is another line of text.'; 16 17 18 19 /* echo 'This line will not be executed.'; */ 20 21 22 23 24 25 echo "Now I'm done.
"; // End of PHP code. ?> To comment your scripts: 1. Begin a new PHP document in your text editor or IDE, to be named comments.php, starting with the initial HTML (Script 1.4):Comments 2. Add the initial PHP tag and write your first comments: This is a line of ➝ text.
This is another line ➝ of text.'; It doesn’t matter what you do here, just make something for the Web browser to display. For the sake of variety, the echo statement will print some HTML tags, including a line break (
) to add some spacing to the generated HTML page. 4. Use the multiline comments to comment out a second echo statement: /* echo 'This line will not be ➝ executed.'; */ By surrounding any block of PHP code with /* and */, you can render that code inert without having to delete it from your script. By later removing the comment tags, you can reactivate that section of PHP code. 5. Add a final comment after a third echo statement: echo "Now I'm done.
"; ➝ // End of PHP code. This last (superfluous) comment shows how to place a comment at the end of a line, a common practice. Note that double quotation marks surround this message, as single quotation marks would conflict with the apostrophe (see the “Needing an Escape” sidebar, earlier in the chapter). 6. Close the PHP section and complete the HTML page: ?> 7. Save the file as comments.php, place it in your Web directory, and test it in your Web browser A. 12 Chapter 1 A The PHP comments in Script 1.4 don’t appear in the Web page or the HTML source B. 8. If you’re the curious type, check the source code in your Web browser to confirm that the PHP comments do not appear there B. You shouldn’t nest (place one inside another) multiline comments (/* */). Doing so will cause problems. Any of the PHP comments can be used at the end of a line (say, after a function call): echo 'Howdy'; /* Say 'Howdy' */ Although this is allowed, it’s far less common. It’s nearly impossible to over-comment your scripts. Always err on the side of writing too many comments as you code. That being said, in the interest of saving space, the scripts in this book will not be as well documented as I would suggest they should be. It’s also important that as you change a script you keep the comments up-to-date and accurate. There’s nothing more confusing than a comment that says one thing when the code really does something else. B The PHP comments from Script 1.4 are nowhere to be seen in the client’s browser. Introduction to PHP 13 What Are Variables? Variables are containers used to temporarily store values. These values can be numbers, text, or much more complex data. PHP supports eight types of variables. These include four scalar (single-valued) types—Boolean (TRUE or FALSE), integer, floating point (decimals), and strings (characters); two nonscalar (multivalued)—arrays and objects; plus resources (which you’ll see when interacting with databases) and NULL (which is a special type that has no value). Regardless of what type you are creating, all variable names in PHP follow certain syntactical rules: n n n n 14 A variable’s name must start with a dollar sign ($), for example, $name. The variable’s name can contain a combination of letters, numbers, and the underscore, for example, $my_report1 . The first character after the dollar sign must be either a letter or an underscore (it cannot be a number). Variable names in PHP are casesensitive! This is a very important rule. It means that $name and $Name are entirely different variables. Chapter 1 To begin working with variables, this next script will print out the value of three predefined variables. Whereas a standard variable is assigned a value during the execution of a script, a predefined variable will already have a value when the script begins its execution. Most of these predefined variables reflect properties of the server as a whole, such as the operating system in use. Before getting into this script, there are two more things you should know. First, variables can be assigned values using the equals sign (=), also called the assignment operator. Second, to display the value of a variable, you can print the variable without quotation marks: print $some_var; Or variables can be printed within double quotation marks: print "Hello, $name"; You cannot print variables within single quotation marks: print 'Hello, $name'; // Won't work! Script 1.5 This script prints three of PHP’s many predefined variables. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26Predefined Variables You are running the file:
$file.\n"; // Print the user's information: echo "You are viewing this page using:
\n"; // Print the server's information: echo "
$userThis server is running:
\n"; ?> To use variables: 1. Begin a new PHP document in your text editor or IDE, to be named predefined.php, starting with the initial HTML (Script 1.5):
$server.Predefined Variables ➝ 2. Add the opening PHP tag and the first comment: You are running the ➝ file:
$file.\n"; The first variable to be printed is $file. Notice that this variable must be used within double quotation marks and that the statement also makes use of the PHP newline character (\n), which will add a line break in the generated HTML source. Some basic HTML tags— paragraph and bold—are added to give the generated page a bit of flair. 6. Print out the information of the user accessing the script: echo "You are viewing this page ➝ using:
\n"; This line prints the second variable, $user. To repeat what’s said in the fourth step, $user correlates to $_ SERVER['HTTP_USER_AGENT'] and refers to the operating system, browser type, and browser version being used to access the Web page. 7. Print out the server information: echo "
$userThis server is running: ➝
\n"; 8. Complete the PHP block and the HTML page: ?> 9. Save the file as predefined.php, place it in your Web directory, and test it in your Web browser A. If you have problems with this, or any other script, turn to the book’s corresponding Web forum (www.LarryUllman.com/ forums/) for assistance. If possible, run this script using a different Web browser and/or on another server B. Variable names cannot contain spaces. The underscore is commonly used in lieu of a space. The most important consideration when creating variables is to use a consistent naming scheme. In this book you’ll see that I use all-lowercase letters for my variable names, with underscores separating words ($first_name). Some programmers prefer to use capitalization instead: $FirstName (known as “camel-case” style). PHP is very casual in how it treats variables, meaning that you don’t need to initialize them (set an immediate value) or declare them (set a specific type), and you can convert a variable among the many types without problem. A The predefined.php script reports back to the viewer information about the script, the Web browser being used to view it, and the server itself. B This is the book’s first truly dynamic script, in that the Web page changes depending upon the server running it and the Web browser viewing it (compare with A ). Introduction to PHP 17 introducing Strings Now that you’ve been introduced to the general concept of variables, let’s look at variables in detail. The first variable type to delve into is the string. A string is merely a quoted chunk of characters: letters, numbers, spaces, punctuation, and so forth. These are all strings: n ‘Tobias’ n “In watermelon sugar” n ‘100’ n ‘August 2, 2011’ To make a string variable, assign a string value to a valid variable name: $first_name = 'Tobias'; $today = 'August 2, 2011'; When creating strings, you can use either single or double quotation marks to encapsulate the characters, just as you would when printing text. Likewise, you must use the same type of quotation mark for the beginning and the end of the string. If that same mark appears within the string, it must be escaped: $var = "Define \"platitude\", please."; Or you can also use the other quotation mark type: $var = 'Define "platitude", please.'; To print out the value of a string, use either echo or print: echo $first_name; To print the value of string within a context, you must use double quotation marks: echo "Hello, $first_name"; You’ve already worked with strings once— when using the predefined variables in the preceding section (the values of those variables happened to be strings). In this next example, you’ll create and use your own strings. 18 Chapter 1 Script 1.6 String variables are created and their values are sent to the Web browser in this script. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
$server.Strings The book $book was written by $first_name $last_name."; ?> To use strings: 1. Begin a new PHP document in your text editor or IDE, to be named strings.php, starting with the initial HTML and including the opening PHP tag (Script 1.6):Strings The book $book ➝ was written by $first_name ➝ $last_name."; All this script does is print a statement of authorship based upon three established variables. A little HTML formatting (the emphasis on the book’s title) is thrown in to make it more attractive. Remember to use double quotation marks here for the variable values to be printed out appropriately (more on the importance of double quotation marks at the chapter’s end). 4. Complete the PHP block and the HTML page: ?> 5. Save the file as strings.php, place it in your Web directory, and test it in your Web browser A. 6. If desired, change the values of the three variables, save the file, and run the script again B. If you assign another value to an existing variable (say $book), the new value will overwrite the old one. For example: $book = 'High Fidelity'; $book = 'The Corrections'; /* $book now has a value of 'The Corrections'. */ PHP has no set limits on how big a string can be. It’s theoretically possible that you’ll be limited by the resources of the server, but it’s doubtful that you’ll ever encounter such a problem. 20 Chapter 1 A The resulting Web page is based upon printing out the values of three variables. B The output of the script is changed by altering the variables in it. Script 1.7 Concatenation gives you the ability to append more characters onto a string. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22Concatenation The book $book was written by $author."; ?> $address = $city . ', ' . $state . ' 98101'; $address = $city . ', ' . $state . ' ' . 98101; Let’s modify strings.php to use this new operator. To use concatenation: 1. Open strings.php (refer to Script 1.6) in your text editor or IDE. 2. After you’ve established the $first_ name and $last_name variables (lines 11 and 12), add this line (Script 1.7): $author = $first_name . ' ' . ➝ $last_name; As a demonstration of concatenation, a new variable—$author—will be created as the concatenation of two existing strings and a space in between. continues on next page Introduction to PHP 21 3. Change the echo statement to use this new variable: echo "The book $book ➝ was written by $author.
"; Since the two variables have been turned into one, the echo statement should be altered accordingly. 4. If desired, change the HTML page title and the values of the first name, last name, and book variables. 5. Save the file as concat.php, place it in your Web directory, and test it in your Web browser A. PHP has a slew of useful string-specific functions, which you’ll see over the course of this book. For example, to calculate how long a string is (how many characters it contains), use strlen( ): $num = strlen('some string'); // 11 You can have PHP convert the case of strings with: strtolower( ), which makes it entirely lowercase; strtoupper( ), which makes it entirely uppercase; ucfirst( ), which capitalizes the first character; and ucwords( ), which capitalizes the first character of every word. If you are merely concatenating one value to another, you can use the concatenation assignment operator (.=). The following are equivalent: $title = $title . $subtitle; $title .= $subtitle; The initial example in this section could be rewritten using either $address = "$city, $state"; or $address = $city; $address .= ', '; $address .= $state; 22 Chapter 1 A In this revised script, the end result of concatenation is not apparent to the user. using the pHp Manual The PHP manual—accessible online at www.php.net/manual—lists every function and feature of the language. The manual is organized with general concepts (installation, syntax, variables) discussed first and ends with the functions by topic (MySQL, string functions, and so on). To quickly look up any function in the PHP manual, go to www.php.net/ functionname in your Web browser (for example, www.php.net/print). For each function, the manual indicates: . The versions of PHP the function is available in. . How many and what types of arguments the function takes (optional arguments are wrapped in square brackets). . What type of value the function returns. The manual also contains a description of the function. You should be in the habit of checking out the PHP manual whenever you’re confused by a function, how it’s properly used, or need to learn more about any feature of the language. It’s also critically important that you know what version of PHP you’re running, as functions and other particulars of PHP do change over time. introducing numbers In introducing variables, I stated that PHP has both integer and floating-point (decimal) number types. In my experience, though, these two types can be classified under the generic title numbers without losing any valuable distinction (for the most part). Valid number-type variables in PHP can be anything like n 8 n 3.14 n 10980843985 n -4.2398508 n 4.4e2 common ones are round( ) and number_ format( ). The former rounds a decimal to the nearest integer: $n = 3.14; $n = round ($n); // 3 It can also round to a specified number of decimal places: $n = 3.142857; $n = round ($n, 3); // 3.143 The number_format( ) function turns a number into the more commonly written version, grouped into thousands using commas: $n = 20943; $n = number_format ($n); // 20,943 Notice that these values are never quoted—quoted numbers are strings with numeric values—nor do they include commas to indicate thousands. Also, a number is assumed to be positive unless it is preceded by the minus sign (-). Along with the standard arithmetic operators you can use on numbers (Table 1.1), there are dozens of functions built into PHP. Two This function can also set a specified number of decimal points: $n = 20943; $n = number_format ($n, 2); // 20,943.00 To practice with numbers, let’s write a mock-up script that performs the calculations one might use in an e-commerce shopping cart. TABLe 1.1 Arithmetic Operators Operator Meaning + Addition - Subtraction * Multiplication / Division % Modulus ++ Increment -- Decrement Introduction to PHP 23 To use numbers: 1. Begin a new PHP document in your text editor or IDE, to be named numbers.php (Script 1.8):Numbers Numbers You are purchasing ' . $quantity . ' widget(s) at a cost of $' . $price . ' each. With tax, the total comes to $' . $total . '.'; ?> 4. Format the total: $total = number_format ($total, 2); The number_format( ) function will group the total into thousands and round it to two decimal places. Applying this function will properly format the calculated value. 5. Print the results: echo 'You are purchasing ' . ➝ $quantity . ' widget(s) at ➝ a cost of $' . $price . ' ➝ each. With tax, the total comes ➝ to $' . $total . '.
'; The last step in the script is to print out the results. The echo statement uses both single-quoted text and concatenated variables in order to print out the full combination of HTML, dollar signs, and variable values. You’ll see an alternative approach in the last example of this chapter. 6. Complete the PHP code and the HTML page: ?> 7. Save the file as numbers.php, place it in your Web directory, and test it in your Web browser A. 8. If desired, change the initial three variables and rerun the script B. A The numbers PHP page (Script 1.8) performs calculations based upon set values. PHP supports a maximum integer of around two billion on most platforms. With numbers larger than that, PHP will automatically use a floating-point type. When dealing with arithmetic, the issue of precedence arises (the order in which complex calculations are made). While the PHP manual and other sources tend to list out the hierarchy of precedence, I find programming to be safer and more legible when I group clauses in parentheses to force the execution order (see line 17 of Script 1.8). Computers are notoriously poor at dealing with decimals. For example, the number 2.0 may actually be stored as 1.99999. Most of the time this won’t be a problem, but in cases where mathematical precision is paramount, rely on integers, not decimals. The PHP manual has information on this subject, as well as alternative functions for improving computational accuracy. Many of the mathematical operators also have a corresponding assignment operator, letting you create a shorthand for assigning values. This line, $total = $total + ($total * $taxrate); could be rewritten as $total += ($total * $taxrate); If you set a $price value without using two decimals (e.g., 119.9 or 34), you would want to apply number_format( ) to $price before printing it. B To change the generated Web page, alter any or all of the three variables (compare with A ). Introduction to PHP 25 introducing Constants Constants, like variables, are used to temporarily store a value, but otherwise, constants and variables differ in many ways. For starters, to create a constant, you use the define( ) function instead of the assignment operator (=): define ('NAME', value); Notice that, as a rule of thumb, constants are named using all capitals, although this is not required. Most importantly, constants do not use the initial dollar sign as variables do (because constants are not variables). A constant can only be assigned a scalar value, like a string or a number: define ('USERNAME', 'troutocity'); define ('PI', 3.14); And unlike variables, a constant’s value cannot be changed. To access a constant’s value, like when you want to print it, you cannot put the constant within quotation marks: echo "Hello, USERNAME"; // Won't work! With that code, PHP literally prints Hello, USERNAME A and not the value of the USERNAME constant (because there’s no indication that USERNAME is anything other than literal text). Instead, either print the constant by itself: echo 'Hello, '; echo USERNAME; or use the concatenation operator: echo 'Hello, ' . USERNAME; PHP runs with several predefined constants, much like the predefined variables used earlier in the chapter. These include PHP_VERSION (the version of PHP running) and PHP_OS (the operating system of the server). This next script will print those two values, along with the value of a user-defined constant. 26 Chapter 1 A Constants cannot be placed within quoted strings. Script 1.9 Constants are another temporary storage tool you can use in PHP, distinct from variables. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18Constants Today is ' . TODAY . '.
This server is running version ' . PHP_VERSION . ' of PHP on the ' . PHP_OS . ' operating system.'; ?> To use constants: 1. Begin a new PHP document in your text editor or IDE, to be named constants.php (Script 1.9).Constants Today is ' . TODAY . ➝ '.
This server is running ➝ version ' . PHP_VERSION . ➝ ' of PHP on the ' . PHP_OS . ➝ ' operating system.'; Since constants cannot be printed within quotation marks, use the concatenation operator in the echo statement. continues on next page Introduction to PHP 27 4. Complete the PHP code and the HTML page: ?> 5. Save the file as constants.php, place it in your Web directory, and test it in your Web browser B. B By making use of PHP’s constants, you can learn more about your PHP setup. If possible, run this script on another PHP-enabled server C. The operating system called Darwin B is the technical term for Mac OS X. In Chapter 12, “Cookies and Sessions,” you’ll learn about another constant, SID (which stands for session ID). 28 Chapter 1 C Running the same script (refer to Script 1.9) on different servers garners different results. Single vs. Double Quotation Marks In PHP it’s important to understand how single quotation marks differ from double quotation marks. With echo and print, or when assigning values to strings, you can use either, as in the examples used so far. But there is a key difference between the two types of quotation marks and when you should use which. You’ve seen this difference already, but it’s an important enough concept to merit more discussion. In PHP, values enclosed within single quotation marks will be treated literally, whereas those within double quotation marks will be interpreted. In other words, placing variables and special characters (Table 1.2) within double quotes will result in their represented values printed, not their literal values. For example, assume that you have The code echo "var is equal to $var"; will print out var is equal to test, but the code echo 'var is equal to $var'; will print out var is equal to $var. Using an escaped dollar sign, the code echo "\$var is equal to $var"; will print out $var is equal to test, whereas the code echo '\$var is equal to $var'; will print out \$var is equal to $var A. As these examples should illustrate, double quotation marks will replace a variable’s name ($var) with its value (test) and a special character’s code (\$) with its represented value ($). Single quotes will always display exactly what you type, except for the escaped single quote (\') and the escaped backslash (\\), which are printed as a single quotation mark and a single backslash, respectively. As another example of how the two quotation marks differ, let’s modify the numbers.php script as an experiment. $var = 'test'; TABLe 1.2 Escape Sequences Code Meaning \" Double quotation mark \' Single quotation mark \\ Backslash \n Newline \r Carriage return \t Tab \$ Dollar sign A How single and double quotation marks affect what gets printed by PHP. Introduction to PHP 29 To use single and double quotation marks: Script 1.10 This, the final script in the chapter, demonstrates the differences between using single and double quotation marks. 1. Open numbers.php (refer to Script 1.8) in your text editor or IDE. 1 2. Delete the existing echo statement (Script 1.10). 2 3. Print a caption and then rewrite the original echo statement using double quotation marks: echo "Using double quotation ➝ marks:
"; echo "You are purchasing ➝ $quantity widget(s) at ➝ a cost of \$$price each. ➝ With tax, the total comes to ➝ \$$total.
\n"; In the original script, the results were printed using single quotation marks and concatenation. The same result can be achieved using double quotation marks. When using double quotation marks, the variables can be placed within the string. There is one catch, though: trying to print a dollar amount as $12.34 (where 12.34 comes from a variable) would suggest that you would code $$var. That will not work (for complicated reasons). Instead, escape the initial dollar sign, resulting in \$$var, as you see twice in this code. The first dollar sign will be printed, and the second becomes the start of the variable name. 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 30 Chapter 1Quotation Marks Using double quotation marks:"; echo "You are purchasing $quantity widget(s) at a cost of \$$price each. With tax, the total comes to \$$total.
\n"; // Print the results using single quotation marks: echo 'Using single quotation marks:
'; echo 'You are purchasing $quantity widget(s) at a cost of \$$price each. With tax, the total comes to \$$total.
\n'; ?> 4. Repeat the echo statements, this time using single quotation marks: echo 'Using single quotation ➝ marks:
'; echo 'You are purchasing ➝ $quantity widget(s) at ➝ a cost of \$$price each. ➝ With tax, the total comes to ➝ \$$total.
\n'; This echo statement is used to highlight the difference between using single or double quotation marks. It will not work as desired, and the resulting page will show you exactly what does happen instead. 5. If you want, change the page’s title. 6. Save the file as quotes.php, place it in your Web directory, and test it in your Web browser B. 7. View the source of the Web page to see how using the newline character (\n) within each quotation mark type also differs. You should see that when you place the newline character within double quotation marks it creates a newline in the HTML source. When placed within single quotation marks, the literal characters \ and n are printed instead. Because PHP will attempt to find variables within double quotation marks, using single quotation marks is theoretically faster. If you need to print the value of a variable, though, you must use double quotation marks. As valid HTML often includes a lot of double-quoted attributes, it’s often easiest to use single quotation marks when printing HTML with PHP: echo ''; If you were to print out this HTML using double quotation marks, you would have to escape all of the double quotation marks in the string: echo "
"; In newer versions of PHP, you can actually use $$price and $$total without preceding them with a backslash (thanks to some internal magic). In older versions of PHP, you cannot. To guarantee reliable results, regardless of PHP version, I recommend using the \$$var syntax when you need to print a dollar sign immediately followed by the value of a variable. If you’re still unclear as to the difference between the types, use double quotation marks and you’re less likely to have problems. B These results demonstrate when and how you’d use one type of quotation mark as opposed to the other. Introduction to PHP 31 Basic Debugging Steps Debugging is by no means a simple concept to grasp, and unfortunately, it’s one that is only truly mastered by doing. The next 50 pages could be dedicated to the subject and you’d still only be able to pick up a fraction of the debugging skills that you’ll eventually acquire and need. The reason I introduce debugging in this somewhat harrowing way is that it’s important not to enter into programming with delusions. Sometimes code won’t work as expected, you’ll inevitably create careless errors, and some days you’ll want to pull your hair out, even when using a comparatively user-friendly language such as PHP. In short, prepare to be perplexed and frustrated at times. I’ve been coding in PHP since 1999, and occasionally I still get stuck in the programming muck. But debugging is a very important skill to have, and one that you will eventually pick up out of necessity and experience. As you begin your PHP programming adventure, I can offer the following basic but concrete debugging tips. Note that these are just some general debugging techniques, specifically tailored to the beginning PHP programmer. Chapter 8, “Error Handling and Debugging,” goes into other techniques in more detail. 32 Chapter 1 To debug a pHp script: n n n Make sure you’re always running PHP scripts through a URL! This is perhaps the most common beginner’s mistake. PHP code must be run through the Web server application, which means it must be requested via http://something. When you see actual PHP code instead of the result of that code’s execution, most likely you’re not running the PHP script through a URL. Know what version of PHP you’re running. Some problems will arise from the version of PHP in use. Before you ever use any PHP-enabled server, run a phpinfo.php script (see Appendix A) or reference the PHP_VERSION constant to confirm the version of PHP in use. Make sure display_errors is on. This is a basic PHP configuration setting (also discussed in Appendix A). You can confirm this setting by executing the phpinfo( ) function ( just use your browser to search for display_errors in the resulting page). For security reasons, PHP may not be set to display the errors that occur. If that’s the case, you’ll end up seeing blank pages when problems occur. To debug most problems, you’ll need to see the errors, so turn this setting on while you’re learning. You’ll find instructions for doing so in Appendix A. n n n Check the HTML source code. Sometimes the problem is hidden in the HTML source of the page. In fact, sometimes the PHP error message can be hidden there! Trust the error message. Another very common beginner’s mistake is to not fully read or trust the error that PHP reports. Although an error message can often be cryptic and may seem meaningless, it can’t be ignored. At the very least, PHP is normally correct as to the line on which the problem can be found. And if you need to relay that error message to someone else (like when you’re asking me for help), do include the entire error message! Take a break! So many of the programming problems I’ve encountered over the years, and the vast majority of the toughest ones, have been solved by stepping away from the computer for a while. It’s easy to get frustrated and confused, and in such situations, any further steps you take are likely to only make matters worse. Introduction to PHP 33 Review and pursue New in this edition of the book, each chapter ends with a “Review and Pursue” section. In these sections you’ll find questions regarding the material just covered and prompts for ways to expand your knowledge and experience on your own. If you have any problems with these sections, either in answering the questions or pursuing your own endeavors, turn to the book’s supporting forum (www.LarryUllman.com/forums/). n What is the assignment operator? n How do you create a string variable? n n n n n n n n n n 34 What tags are used to surround PHP code? n n n What extension should a PHP file have? What does a page’s encoding refer to? What impact does the encoding have on the page? n What PHP functions, or language constructs, can you use to send data to the Web browser? n How does using single versus double quotation marks differ in creating or printing strings? What does it mean to escape a character in a string? What are the three comment syntaxes in PHP? Which one can be used over multiple lines? What character do all variable names begin with? What characters can come next? What other characters can be used in a variable’s name? Are variable names case-sensitive or case-insensitive? Chapter 1 How are constants defined and used? pursue Review n What is the concatenation operator? What is the concatenation assignment operator? n If you don’t already know—for certain— what version of PHP you’re running, check now. Look up one of the mentioned string functions in the PHP manual. Then check out some of the other available string functions listed therein. Look up one of the mentioned number functions in the PHP manual. Then check out some of the other available number functions listed therein. Search the PHP manual for the $_SERVER variable to see what other information it contains. Create a new script, from scratch, that defines and displays the values of some string variables. Use double quotation marks in the echo or print statement that outputs the values. For added complexity include some HTML in the output. Then rewrite the script so that it uses single quotation marks and concatenation instead of double quotation marks. Create a new script, from scratch, that defines, manipulates, and displays the values of some numeric variables. 2 Programming with PHP Now that you have the fundamentals of the PHP scripting language down, it’s time to build on those basics and start truly programming. In this chapter you’ll begin creating more elaborate scripts while still learning some of the standard constructs, functions, and syntax of the language. You’ll start by creating an HTML form, and then learn how you can use PHP to handle the submitted values. From there, the chapter covers conditionals and the remaining operators (Chapter 1, “Introduction to PHP,” presented the assignment, concatenation, and mathematical operators), arrays (another variable type), and one last language construct, loops. in This Chapter 36 41 45 49 54 69 72 Creating an HTML Form Handling an HTML form with PHP is perhaps the most important process in any dynamic Web site. Two steps are involved: first you create the HTML form itself, and then you create the corresponding PHP script that will receive and process the form data. It is outside the realm of this book to go into HTML forms in any detail, but I will lead you through one quick example so that it may be used throughout the chapter. If you’re unfamiliar with the basics of an HTML form, including the various types of elements, see an HTML resource for more information. An HTML form is created using the form tags and various elements for taking input. The form tags look like In terms of PHP, the most important attribute of your form tag is action, which dictates to which page the form data will be sent. The second attribute—method— has its own issues (see the “Choosing a Method” sidebar), but post is the value you’ll use most frequently. The different inputs—be they text boxes, radio buttons, select menus, check boxes, etc.—are placed within the opening and closing form tags. As you’ll see in the next section, what kinds of inputs your form has makes little difference to the PHP script handling it. You should, however, pay attention to the names you give your form inputs, as they’ll be of critical importance when it comes to your PHP code. 36 Chapter 2 Choosing a Method The method attribute of a form dictates how the data is sent to the handling page. The two options— get and post— refer to the HTTP (HyperText Transfer Protocol) method to be used. The GET method sends the submitted data to the receiving page as a series of name-value pairs appended to the URL. For example, http://www.example.com/script.php? ➝ name=Homer&gender=M&age=35 The benefit of using the GET method is that the resulting page can be bookmarked in the user’s Web browser (since it’s a complete URL). For that matter, you can also click Back in your Web browser to return to a GET page, or reload it without problems (none of which is true for POST). But there is a limit in how much data can be transmitted via GET, and this method is less secure (since the data is visible). Generally speaking, GET is used for requesting information, like a particular record from a database or the results of a search (searches almost always use GET). The POST method is used when an action is expected: the updating of a database record or the sending of an email. For these reasons I will primarily use POST throughout this book, with noted exceptions. Script 2.1 This simple HTML form will be used for several of the examples in this chapter. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
Simple HTML Form A Two text inputs. 5. Add a pair of radio buttons: B If multiple radio buttons have the same name value, only one can be selected by the user.Male ➝ Female
The radio buttons B both have the same name, meaning that only one of the two can be selected. They have different values, though. C The pull-down menu offers three options, of which only one can be selected (in this example). D The textarea form element type allows for lots and lots of text. 6. Add a pull-down menu: The select tag starts the pull-down menu, and then each option tag will create another line in the list of choices C. 7. Add a text box for comments: Textareas are different from text inputs; they are presented as a box D, not as a single line. They allow for much more information to be typed and are useful for taking user comments. continues on next page Programming with PHP 39 8. Complete the form: The first tag closes the fieldset that was opened in Step 3. Then a submit button is created and centered using a p tag. Finally, the form is closed. 9. Complete the HTML page: 10. Save the file as form.html, place it in your Web directory, and view it in your Web browser E. Since this page contains just HTML, it uses an .html extension. It could instead use a .php extension without harm (since code outside of the PHP tags is treated as HTML). You can specify the encoding to accept in an HTML form tag, too:By default, a Web page will use the same encoding as the page itself for any submitted data. 40 Chapter 2 E The complete form, which requests some basic information from the user. Handling an HTML Form Now that the HTML form has been created, it’s time to write a bare-bones PHP script to handle it. To say that this script will be handling the form means that the PHP page will do something with the data it receives (which is the data the user entered into the form). In this chapter, the scripts will simply print the data back to the Web browser. In later examples, form data will be stored in a MySQL database, compared against previously stored values, sent in emails, and more. The beauty of PHP—and what makes it so easy to learn and use—is how well it interacts with HTML forms. PHP scripts store the received information in special variables. For example, say you have a form with an input defined like so: Whatever the user types into that input will be accessible via a PHP variable named $_REQUEST['city']. It is very important that the spelling and capitalization match exactly! PHP is case-sensitive when it comes to variable names, so $_REQUEST['city'] will work, but $_ Request['city'] and $_REQUEST['City'] will have no value. This next example will be a PHP script that handles the already-created HTML form (Script 2.1). This script will assign the form data to new variables (to be used as shorthand, just like in Script 1.5, predefined.php). The script will then print the received values. Programming with PHP 41 To handle an HTML form: 1. Begin a new PHP document in your text editor or IDE, to be named handle_form.php starting with the HTML (Script 2.2): Form Feedback 2. Add the opening PHP tag and create a shorthand version of the form data variables:Form Feedback Thank you, $name, for the following comments:
$commentsWe will reply to you at $email.
\n"; 22 23 24 25 26 27 // Print the submitted information: ?> TABLe 2.1 Form Elements to PHP Variables Element Name Variable Name name $_REQUEST['name'] email $_REQUEST['email'] comments $_REQUEST['comments'] age $_REQUEST['age'] gender $_REQUEST['gender'] submit $_REQUEST['submit'] At this point, you won’t make use of the age, gender, and submit form elements. 3. Print out the received name, email, and comments values: echo "Thank you, $name, ➝ for the following comments:
$commentsWe will reply to you at ➝ $email.
\n"; The submitted values are simply printed out using the echo statement, double quotation marks, and a wee bit of HTML formatting. A To test handle_form.php, you must load the form through a URL, then fill it out and submit it. 4. Complete the page: ?> 5. Save the file as handle_form.php and place it in the same Web directory as form.html. B The script should display results like this. 6. Test both documents in your Web browser by loading form.html through a URL (http://something) and then filling out A and submitting the form B. Because the PHP script must be run through a URL (see Chapter 1), the form must also be run through a URL. Otherwise, when you go to submit the form, you’ll see PHP code C instead of the proper result B. C If you see the PHP code after submitting the form, the problem is likely that you did not access the form through a URL. Programming with PHP 43 $_REQUEST is a special variable type, known as a superglobal. It stores all of the data sent to a PHP page through either the GET or POST method, as well as data accessible in cookies. Superglobals will be discussed later in the chapter. If you have any problems with this script, apply the debugging techniques suggested in Chapter 1. If you still can’t solve the problem, check out the extended debugging techniques listed in Chapter 8, “Error Handling and Debugging.” If you’re still stymied, turn to the book’s supporting forum for assistance (www.LarryUllman.com/forums/). If the PHP script shows blank spaces where a variable’s value should have been printed, it means that the variable has no value. The two most likely causes are: you failed to enter a value in the form; or you misspelled or mis-capitalized the variable’s name. If you see any Undefined variable: variablename errors, this is because the variables you refer to have no value and PHP is set on the highest level of error reporting. The previous tip provides suggestions as to why a variable wouldn’t have a value. Chapter 8 discusses error reporting in detail. To see how PHP handles the different form input types, print out the $_REQUEST['age'] and $_REQUEST['gender'] values D. D The values of gender and age correspond to those defined in the form’s HTML. Magic Quotes Earlier versions of PHP had a feature called Magic Quotes, which has since been deprecated and will eventually be removed entirely. Magic Quotes—when enabled—automatically escapes single and double quotation marks found in submitted form data (there were actually three kinds of Magic Quotes, but this one kind is most important here). As an example, Magic Quotes would turn the string I’m going out into I\’m going out. The escaping of potentially problematic characters can be useful and even necessary in some situations. But if Magic Quotes are enabled on your PHP installation, you’ll see these backslashes when the PHP script prints out the form data. You can undo the effect of Magic Quotes using the stripslashes( ) function: $var = stripslashes($var); This function will remove any backslashes found in $var. This will have the result of turning an escaped submitted string back to its original, non-escaped value. To use this in handle_form.php (Script 2.2), you would write: $name = stripslashes($_REQUEST ➝ ['name']); If you’re not seeing backslashes added to your form data, then you don’t need to worry about Magic Quotes. 44 Chapter 2 Conditionals and operators An elseif clause allows you to add more conditions: PHP’s three primary terms for creating conditionals are if, else, and elseif (which can also be written as two words, else if). Every conditional begins with an if clause: if (condition) { // Do something! } An if can also have an else clause: if (condition) { // Do something! } else { // Do something else! } TABLe 2.2 Comparative and Logical Operators Symbol Meaning Type Example == is equal to comparison $x = = $y != is not equal to comparison $x != $y < less than comparison $x < $y > greater than comparison $x > $y if (condition1) { // Do something! } elseif (condition2) { // Do something else! } else { // Do something different! } If a condition is true, the code in the following curly braces ({ } ) will be executed. If not, PHP will continue on. If there is a second condition (after an elseif ), that will be checked for truth. The process will continue—you can use as many elseif clauses as you want— until PHP hits an else, which will be automatically executed at that point, or until the conditional terminates without an else. For this reason, it’s important that the else always come last and be treated as the default action unless specific criteria— the conditions—are met. A condition can be true in PHP for any number of reasons. To start, these are true conditions: n n $var, if $var has a value other than 0, an empty string, FALSE, or NULL isset($var), if $var has any value other than NULL, including 0, FALSE, or an empty string <= less than or equal to comparison $x <= $y >= greater than or equal to comparison $x >= $y n isset( ), is introduced. This function TRUE, true, True, etc. In the second example, a new function, ! not logical !$x && and logical $x && $y AND and logical $x and $y || or logical $x || $y OR or logical $x or $y XOR and not logical $x XOR $y checks if a variable is “set,” meaning that it has a value other than NULL (as a reminder, NULL is a special type in PHP, representing no set value). You can also use the comparative and logical operators (Table 2.2) in conjunction with parentheses to make more complicated expressions. Programming with PHP 45 To use conditionals: 1. Open handle_form.php (refer to Script 2.2) in your text editor or IDE, if it is not already. 2. Before the echo statement, add a conditional that creates a $gender variable (Script 2.3): if (isset($_REQUEST['gender'])) { $gender = $_REQUEST['gender']; } else { $gender = NULL; } This is a simple and effective way to validate a form input (particularly a radio button, check box, or select). If the user checks either gender radio button, then $_REQUEST['gender'] will have a value, meaning that the condition isset($_REQUEST['gender']) is true. In such a case, the shorthand version of this variable—$gender—is assigned the value of $_REQUEST['gender'], repeating the technique used with $name, $email, and $comments. If the user does not click one of the radio buttons, then this condition is not true, and $gender is assigned the value of NULL, indicating that it has no value. Notice that NULL is not in quotes. Script 2.3 In this remade version of handle_form. php, two conditionals are used to validate the gender radio buttons. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 // Create the $gender variable: if (isset($_REQUEST['gender'])) { $gender = $_REQUEST['gender']; } else { $gender = NULL; } // Print the submitted information: echo "Thank you, $name, for the following comments:
$commentsWe will reply to you at $email.
\n"; // Print a message based upon the gender value: 34 35 36 37 38 ?>