PHP 6 and MySQL 6 Bible

Steve Suehring, Tim Converse, and Joyce Park PHP6 ® and MySQL

  Explore PHP syntax, datatypes, and functions

Create database-driven

  dynamic Web sites Master server-side Web programming

  

PHP 6 and

MySQL ®

   6 Bible

  Steve Suehring Tim Converse Joyce Park

  

PHP 6 and

MySQL ®

   6 Bible

  PHP 6 and MySQL 6 Bible

  Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256

  

  Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada

  ISBN: 978-0-470-38450-3 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions .

  Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.

  For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Library of Congress Cataloging-in-Publication Data Suehring, Steve.

  PHP 6 and MySQL 6 bible / Steve Suehring. p. cm. Includes index.

  ISBN 978-0-470-38450-3 (pbk.) 1. PHP (Computer program language) 2. MySQL (Electronic resource) I. Title. QA76.73.P224S94 2009 005.2’762 — dc22 2008048198

  Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its

  affiliates, in the United States and other countries, and may not be used without written permission. MySQL is a registered trademark of MySQL AB in the United States, European Union, and other countries. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.

  About the Authors Steve Suehring is a technology consultant with a diverse business and computing background.

  Steve’s extensive experience enables him to work cross-functionally within organizations to help create computing architectures that fit the business need. Steve has written several books and mag- azine articles and contributed to many others. Steve has spoken internationally at user groups and conventions. When he has the chance, Steve plays just about any sport or any musical instrument, some with better success than others.

  Tim Converse has written software to recommend neckties, answer questions about space sta-

  tions, pick value stocks, and make simulated breakfast. He has an M.S. in Computer Science from the University of Chicago, where he taught several programming classes. He is now an engineering manager in the Web search group at Yahoo!.

  Joyce Park has an M.A. in history from the University of Chicago, and has worked for several

  Silicon Valley startups including Epinions, KnowNow, and Friendster. She is a co-lead of the Mod-pubsub Open Source project.

  Acquisitions Editor

  Vice President and Executive Publisher

  Michael E. Trent

  Cover Designer

  Joyce Haughey

  Cover Illustration

  Ted Laux

  Proofreader Publication Services, Inc. Indexer

  Jeffrey Wilson, Happenstance Type-O-Rama

  Compositor

  Lynsey Stanford

  Project Coordinator, Cover

  Jim Minatel

  Associate Publisher

  Barry Pruett

  Richard Swadley

  Jenny Watson

  Vice President and Executive Group Publisher

  Tim Tate

  Production Manager

  Mary Beth Wakefield

  Editorial Manager

  Foxxe Editorial Services

  Copy Editor

  Rachel McConlogue

  Production Editor

  Aaron Saray

  Technical Editor

  Christopher J. Rivera

  Development Editor

  Credits

Acknowledgments

  People sometimes ask me how many books I’ve written. I never have the answer. You see, I’ve con- tributed to well over a dozen (maybe two dozen or more) books in one form or another, be it a chap- ter or two here, a section there, a rewrite of an existing title with much new material, a revision of another edition where the existing material is already pretty good (as was the case for this book), or an original, authored work. The short answer is: I don’t know. It’s really somewhat difficult to claim that I, alone, wrote a book. At best I put some words down into a word processor and several other people look them over, edit them, change them for both technical and grammatical usage, and the end result is my name on the cover or somewhere in the book, or sometimes not at all.

  This brings me to the difficulty at hand. I’ve written a sufficient number books that writing acknowledgments is becoming a bit mundane. Sure, I’ll thank my wife, Rebecca, and son, Jakob, for their patience while I wrote this. I’ll thank my family for their continued support. I’ll thank the Tueschers, Heins, Leus, and Guthries. I’ll thank Jason Keup and Aaron Saray, too. I’ll thank my agent Neil Salkind at Studio B., Jim Oliva and John Eckendorf, and the 90fm staff along with Nightmare Squad.

  Of course, I’ll thank Tim and Rob @ Partners, and Jay, Deb, and Brian, and Andy Hale and Eliot Irons and the SecAdmin team. Kyle Mac always gets mad if I don’t include him. There are lot of people at Knob Hill who deserve thanking, and the like. And I’ll always thank Mark Little and meek, Pat Dunn, AJ Prowant, and Andy Berkvam. But it’s the people that I don’t thank that always find me, asking why their name isn’t in this book. With that in mind, I’ll stop here and let them find me and hope that I write another book where I’ll remember to include them. Just a hint: Everyone who was thanked here has paid me.

  Introduction ............................................................................................................................. xxxv

  

Part I: Introducing PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 1: Why PHP and MySQL? .................................................................................................3 Chapter 2: Server-Side Scripting Overview .................................................................................. 11 Chapter 3: Getting Started with PHP ...........................................................................................19 Chapter 4: Learning PHP Syntax and Variables ...........................................................................33 Chapter 5: Learning PHP Control Structures and Functions .......................................................59 Chapter 6: Passing Information with PHP ....................................................................................99 Chapter 7: Learning PHP String Handling ................................................................................. 113 Chapter 8: Learning Arrays ........................................................................................................ 131 Chapter 9: Learning PHP Number Handling .............................................................................153 Chapter 10: PHP Gotchas ........................................................................................................... 165 Part II: MySQL Database Integration . . . . . . . . . . . . . . . . . . . . 183 Chapter 11: Introducing Databases and MySQL......................................................................... 185 Chapter 12: Installing MySQL ....................................................................................................189 Chapter 13: Learning Structured Query Language (SQL) .......................................................... 193 Chapter 14: Learning Database Administration and Design ......................................................207 Chapter 15: Integrating PHP and MySQL ................................................................................... 219 Chapter 16: Performing Database Queries .................................................................................237 Chapter 17: Integrating Web Forms and Databases ....................................................................253 Chapter 18: Improving Database Efficiency ............................................................................... 279 Chapter 19: MySQL Gotchas ......................................................................................................295 Part III: More PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 Chapter 20: Introducing Object-Oriented PHP .......................................................................... 311 Chapter 21: Advanced Array Functions ..................................................................................... 357 Chapter 22: Examining Regular Expressions ............................................................................. 371 Chapter 23: Working with the Filesystem .................................................................................. 391 Chapter 24: Working with Cookies and Sessions .......................................................................409 Chapter 25: Learning PHP Types ............................................................................................... 433 Chapter 26: Learning PHP Advanced Functions ........................................................................443 Chapter 27: Performing Math with PHP ..................................................................................... 455 Chapter 28: Securing PHP.......................................................................................................... 471 Chapter 29: Learning PHP Configuration ..................................................................................483

  Contents at a Glance

  Chapter 30: Handing Exceptions with PHP ...............................................................................497 Chapter 31: Debugging PHP Programs....................................................................................... 511 Chapter 32: Learning PHP Style .................................................................................................525 Part IV: Other Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549 Chapter 33: Connecting PHP and PostgreSQL ........................................................................... 551 Chapter 34: Using PEAR DB with PHP ......................................................................................567 Chapter 35: An Overview of Oracle ........................................................................................... 575 Chapter 36: An Introduction to SQLite ......................................................................................605 Part V: Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .611 Chapter 37: Sending E-Mail with PHP ....................................................................................... 613 Chapter 38: Integrating PHP and Java ........................................................................................ 619 Chapter 39: Integrating PHP and JavaScript .............................................................................. 631 Chapter 40: Integrating PHP and XML ......................................................................................647 Chapter 41: Creating and Consuming Web Services with PHP .................................................. 675 Chapter 42: Creating Graphics with PHP ...................................................................................689 Part VI: Case Studies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .713 Chapter 43: Developing a Weblog with PHP ..............................................................................715 Chapter 44: A Trivia Game ........................................................................................................ 727 Chapter 45: Data Visualization with Venn Diagrams .................................................................771 Appendix A: PHP for C Programmers ........................................................................................795 Appendix B: PHP for Perl Hackers ..............................................................................................801 Appendix C: PHP for HTML Coders ..........................................................................................809 Appendix D: PHP Resources ...................................................................................................... 817 Appendix E: PEAR .....................................................................................................................829 Index .......................................................................................................................................... 841

  

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxv

  Part I: Introducing PHP

  1 Chapter 1: Why PHP and MySQL? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

  What Is PHP? .......................................................................................................................3 What Is MySQL? ...................................................................................................................4 Deciding on a Web Application Platform ..............................................................................4

  Cost ............................................................................................................................4 Ease of Use..................................................................................................................5 HTML-embeddedness ................................................................................................5 Cross-platform compatibility ......................................................................................7 Stability ......................................................................................................................7 Many extensions .........................................................................................................8 Fast feature development ............................................................................................8 Not proprietary ...........................................................................................................8 Strong user communities ............................................................................................9

  Summary ............................................................................................................................ 10

  

Chapter 2: Server-Side Scripting Overview . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Static HTML ....................................................................................................................... 11 Client-Side Technologies ....................................................................................................13 Server-Side Scripting ..........................................................................................................15 What Is Server-Side Scripting Good For? ........................................................................... 17 Summary ............................................................................................................................ 18

Chapter 3: Getting Started with PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Installing PHP ....................................................................................................................19 Installation procedures .............................................................................................20 Installing PHP on CentOS ............................................................................... 21 Installing PHP on Debian ................................................................................22 Installing PHP from source .............................................................................22 Microsoft Windows and Apache .....................................................................25 Other web servers ...........................................................................................26 Development tools ....................................................................................................26 What’s to Come? ................................................................................................................. 27 Your HTML Is Already PHP-Compliant! ............................................................................. 27

Contents

  Escaping from HTML .........................................................................................................28 Canonical PHP tags ..................................................................................................28 Hello World ..............................................................................................................28 Jumping in and out of PHP mode .............................................................................30 Including files ...........................................................................................................30

  Summary ............................................................................................................................32

  

Chapter 4: Learning PHP Syntax and Variables . . . . . . . . . . . . . . . . . . . . . . . 33

PHP Is Forgiving ................................................................................................................33 HTML Is Not PHP ..............................................................................................................34 PHP’s Syntax Is C-Like .......................................................................................................34 PHP is whitespace insensitive ...................................................................................34 PHP is sometimes case sensitive ............................................................................... 35 Statements are expressions terminated by semicolons .............................................. 35 Expressions are combinations of tokens ......................................................... 35 Expressions are evaluated ...............................................................................36 Precedence, associativity, and evaluation order ..............................................36 Expressions and types ....................................................................................37 Assignment expressions ..................................................................................37 Reasons for expressions and statements ..........................................................38 Braces make blocks ...................................................................................................38 Comments ..........................................................................................................................39 C-style multiline comments ......................................................................................39 Single-line comments: # and // .................................................................................39 Variables .............................................................................................................................40 PHP variables are Perl-like ........................................................................................40 Declaring variables (or not) ......................................................................................40 Assigning variables ................................................................................................... 41 Reassigning variables ................................................................................................ 41 Unassigned variables ................................................................................................ 41 Default values ................................................................................................. 41 Checking assignment with isset ...................................................................... 42 Variable scope ........................................................................................................... 43 Functions and variable scope .......................................................................... 43 You can switch modes if you want ............................................................................ 43 Constants..................................................................................................................44 Types in PHP: Don’t Worry, Be Happy ...............................................................................45 No variable type declarations ...................................................................................45 Automatic type conversion .......................................................................................45 Types assigned by context ........................................................................................45 Type Summary ...................................................................................................................46 The Simple Types ...............................................................................................................46 Integers ..................................................................................................................... 47 Read formats ................................................................................................... 47 Range .............................................................................................................. 47

Contents

  Doubles ..................................................................................................................... 47 Read formats ...................................................................................................48

  Booleans ...................................................................................................................49 Boolean constants ...........................................................................................49 Interpreting other types as Booleans ...............................................................49 Examples ........................................................................................................50

  NULL ........................................................................................................................50 Strings ...................................................................................................................... 51

  Singly quoted strings ......................................................................................52 Doubly quoted strings .....................................................................................52 Single versus double quotation marks .............................................................53 Variable interpolation .....................................................................................54 Newlines in strings ......................................................................................... 55 Limits .............................................................................................................. 55

  Output ................................................................................................................................ 55 Echo and print .......................................................................................................... 55

  Echo ................................................................................................................56 Print ................................................................................................................56

  Variables and strings .................................................................................................57 HTML and linebreaks .....................................................................................57

  Summary ............................................................................................................................57

  Chapter 5: Learning PHP Control Structures and Functions . . . . . . . . . . . . . . 59 Boolean Expressions ...........................................................................................................60 Boolean constants .....................................................................................................60 Logical operators ......................................................................................................60 Precedence of logical operators ....................................................................... 61 Logical operators short-circuit ........................................................................62 Comparison operators ..............................................................................................62 Operator precedence .......................................................................................63 String comparison ...........................................................................................63 The ternary operator .................................................................................................65 Branching ...........................................................................................................................65 If-else ........................................................................................................................65 Else attachment ...............................................................................................66 Elseif ...............................................................................................................67 Switch .......................................................................................................................69 Looping ..............................................................................................................................71 Bounded loops versus unbounded loops ..................................................................71 While ........................................................................................................................71 Do-while ...................................................................................................................72 For ............................................................................................................................72 Looping examples ..................................................................................................... 74 A bounded for loop ......................................................................................... 74 An unbounded while loop ..............................................................................75 Break and continue ................................................................................................... 76

Contents

  A note on infinite loops ............................................................................................79 Alternate Control Syntaxes .................................................................................................79 Terminating Execution .......................................................................................................80 Using Functions .................................................................................................................83

  Return values versus side effects ...............................................................................83 Function Documentation....................................................................................................84

  Headers in documentation ........................................................................................85 Finding function documentation ..............................................................................85

  Defining Your Own Functions............................................................................................86 What is a function? ...................................................................................................86 Function definition syntax .......................................................................................86 Function definition example .....................................................................................87 Formal parameters versus actual parameters ............................................................88 Argument number mismatches.................................................................................89

  Too few arguments ..........................................................................................89 Too many arguments ......................................................................................90

  Functions and Variable Scope ............................................................................................90 Global versus local .................................................................................................... 91 Static variables ..........................................................................................................92 Exceptions ................................................................................................................93

  Function Scope ...................................................................................................................95 Include and require ..................................................................................................95

  Including only once ........................................................................................96 The include path .............................................................................................96

  Recursion ..................................................................................................................96 Summary ............................................................................................................................98

  

Chapter 6: Passing Information with PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

HTTP Is Stateless ................................................................................................................99 GET Arguments ................................................................................................................100 A Better Use for GET-Style URLs ...................................................................................... 102 POST Arguments ..............................................................................................................104 Formatting Form Variables ...............................................................................................106 Consolidating forms and form handlers .................................................................109 PHP Superglobal Arrays ................................................................................................... 110 Summary .......................................................................................................................... 111

Chapter 7: Learning PHP String Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

Strings in PHP .................................................................................................................. 113 Interpolation with curly braces ............................................................................... 114 Characters and string indexes ................................................................................ 115 String operators ...................................................................................................... 115 Concatenation and assignment ............................................................................... 116 The heredoc syntax................................................................................................. 116 String Functions ............................................................................................................... 117 Inspecting strings ................................................................................................... 118

Contents

  Finding characters and substrings .......................................................................... 118 Comparison and searching .....................................................................................120 Searching ................................................................................................................120 Substring selection .................................................................................................. 121 String cleanup functions .........................................................................................123 String replacement .................................................................................................. 124 Case functions ........................................................................................................126 strtolower() ...................................................................................................126 strtoupper() .................................................................................................. 127 ucfirst() ......................................................................................................... 127 ucwords() ...................................................................................................... 127

  Escaping functions ................................................................................................. 127 Printing and output ................................................................................................128

  Summary ..........................................................................................................................130

  Chapter 8: Learning Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 The Uses of Arrays ............................................................................................................ 131 What Are PHP Arrays? .....................................................................................................132 Creating Arrays ................................................................................................................134 Direct assignment ...................................................................................................134 The array() construct ..............................................................................................134 Specifying indices using array() ............................................................................. 135 Functions returning arrays .....................................................................................136 Retrieving Values ..............................................................................................................136 Retrieving by index .................................................................................................136 The list() construct .................................................................................................136 Multidimensional Arrays .................................................................................................. 137 Inspecting Arrays .............................................................................................................139 Deleting from Arrays ........................................................................................................140 Iteration ............................................................................................................................140 Support for iteration ...............................................................................................140 Using iteration functions ........................................................................................ 141 Our favorite iteration method: foreach .................................................................... 142 Iterating with current() and next() ......................................................................... 143 Starting over with reset() ........................................................................................ 145 Reverse order with end() and prev() ....................................................................... 146 Extracting keys with key() ...................................................................................... 147 Empty values and the each() function .................................................................... 147 Walking with array_walk() ..................................................................................... 149 Summary .......................................................................................................................... 151 Chapter 9: Learning PHP Number Handling . . . . . . . . . . . . . . . . . . . . . . . . . 153 Numerical Types ..............................................................................................................153 Mathematical Operators ...................................................................................................154 Arithmetic operators ...............................................................................................154 Arithmetic operators and types .............................................................................. 155

Contents

  Incrementing operators ........................................................................................... 155 Assignment operators .............................................................................................156 Comparison operators ............................................................................................157 Precedence and parentheses ...................................................................................158

  Simple Mathematical Functions .......................................................................................158 Randomness .....................................................................................................................159

  Seeding the generator .............................................................................................160 Example: Making a random selection ..................................................................... 162

  Summary .......................................................................................................................... 163

Chapter 10: PHP Gotchas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 Installation-Related Problems ........................................................................................... 165 Symptom: Text of file displayed in browser window .............................................. 166 Symptom: PHP blocks showing up as text under HTTP or browser prompts you to save

  file ...................................................................................................................... 166 Symptom: Server or host not found/Page cannot be displayed ............................... 166

  Rendering Problems ......................................................................................................... 166 Symptom: Totally blank page.................................................................................. 167 Symptom: PHP code showing up in Web browser .................................................. 167

  Failures to Load Page ........................................................................................................168 Symptom: Page cannot be found .............................................................................168 Symptom: Failed opening [file] for inclusion .......................................................... 169

  Parse Errors ...................................................................................................................... 169 Symptom: Parse error message ............................................................................... 169 The missing semicolon ........................................................................................... 170 No dollar signs........................................................................................................ 170 Mode issues ............................................................................................................ 171 Unescaped quotation marks ................................................................................... 172 Unterminated strings .............................................................................................. 172 Other parse error causes ......................................................................................... 173

  Missing Includes ............................................................................................................... 173 Symptom: Include warning .................................................................................... 173

  Unbound Variables ........................................................................................................... 174 Symptom: Variable not showing up in print string ................................................. 174 Symptom: Numerical variable unexpectedly zero ................................................... 174 Causes of unbound variables .................................................................................. 174

  Case problems ............................................................................................... 175 Scoping problems .......................................................................................... 175

  Function Problems ........................................................................................................... 176 Symptom: Call to undefined function my_function() ............................................. 177 Symptom: Call to undefined function () ................................................................. 177 Symptom: Call to undefined function array() ......................................................... 177 Symptom: Cannot redeclare my_function() ............................................................ 177 Symptom: Wrong parameter count ......................................................................... 178

Contents

  Math Problems ................................................................................................................. 178 Symptom: Division-by-zero warning ...................................................................... 178 Symptom: Unexpected arithmetic result ................................................................ 178 Symptom: NaN (or NAN) ....................................................................................... 178

  Timeouts .......................................................................................................................... 179 Summary ..........................................................................................................................180