Head First PHP and MySQL.pdf - Advance Praise for Head First PHP MySQL PHP and MySQL are two of todays most popular web development technologies and

Head First PHP and MySQL.pdf - Advance Praise for Head...

This preview shows page 1 out of 814 pages.

Unformatted text preview: Advance Praise for Head First PHP & MySQL “PHP and MySQL are two of today’s most popular web development technologies, and this book shows readers why. Building a site without them is now as unthinkable as doing web design without CSS. This book is a great introduction and is laugh-out-loud funny. It’s the book I wish I had learned from.” — Harvey Quamen, Associate Professor of English and Humanities Computing, University of Alberta “Everything we’ve come to accept about the drudgery of technical learning has been abandoned and in its place an unusually fun method for learning is created. I have full confidence that the Head First series will revolutionize the technical publishing industry, and that these new methods will be the eventual standard. I bet my tech-phobic grandmother could pick up PHP and MySQL techniques after a single reading. She’d probably even have a good time doing it!” — Will Harris, Database Administrator, Powered By Geek “Reading Head First PHP & MySQL is like taking a class from the ‘cool’ teacher. It makes you look forward to learning.” — Stephanie Liese, Web Developer “Using images and humor the book is easy to digest and yet delivers real technical know-how.” — Jereme Allen, Web Developer “‘After a challenging, high-speed read-through and lots of quirky “Do This” projects, such as “My dog was abducted by aliens” and the “Mismatch Dating Agency,” I can’t wait to add some real PHP power to my web sites.” — David Briggs, Software Engineer and Technical Author Praise for Head First HTML with CSS & XHTML “Eric and Elisabeth Freeman clearly know their stuff. As the Internet becomes more complex, inspired construction of web pages becomes increasingly critical. Elegant design is at the core of every chapter here, each concept conveyed with equal doses of pragmatism and wit.” — Ken Goldstein, Executive Vice President & Managing Director, Disney Online “The Web would be a much better place if every HTML author started off by reading this book.” — L. David Baron, Technical Lead, Layout & CSS, Mozilla Corporation, “I’ve been writing HTML and CSS for ten years now, and what used to be a long trial and error learning process has now been reduced neatly into an engaging paperback. HTML used to be something you could just hack away at until things looked okay on screen, but with the advent of web standards and the movement towards accessibility, sloppy coding practice is not acceptable anymore... from a business standpoint or a social responsibility standpoint. Head First HTML with CSS & XHTML teaches you how to do things right from the beginning without making the whole process seem overwhelming. HTML, when properly explained, is no more complicated than plain English, and the Freemans do an excellent job of keeping every concept at eye-level.” — Mike Davidson, President & CEO, Newsvine, Inc. “Oh, great. You made an XHTML book simple enough a CEO can understand it. What will you do next? Accounting simple enough my developer can understand it? Next thing you know we’ll be collaborating as a team or something.” —Janice Fraser, CEO, Adaptive Path “This book has humor, and charm, but most importantly, it has heart. I know that sounds ridiculous to say about a technical book, but I really sense that at its core, this book (or at least its authors) really care that the reader learn the material. This comes across in the style, the language, and the techniques. Learning – real understanding and comprehension – on the part of the reader is clearly top most in the minds of the Freemans. And thank you, thank you, thank you, for the book’s strong, and sensible advocacy of standards compliance. It’s great to see an entry level book, that I think will be widely read and studied, campaign so eloquently and persuasively on behalf of the value of standards compliance in web page code. I even found in here a few great arguments I had not thought of – ones I can remember and use when I am asked – as I still am – ‘what’s the deal with compliance and why should we care?’ I’ll have more ammo now! I also liked that the book sprinkles in some basics about the mechanics of actually getting a web page live - FTP, web server basics, file structures, etc.” —Robert Neer, Director of Product Development, Movies.com Praise for Head First JavaScript “So practical and useful, and so well explained. This book does a great job of introducing a complete newbie to JavaScript, and it’s another testament to Head First’s teaching style. Out of the other JavaScript books, Head First JavaScript is great for learning, compared to other reference books the size of a phone book.” — Alex Lee, Student, University of Houston “An excellent choice for the beginning JavaScript developer.” — Fletcher Moore, Web Developer & Designer, Georgia Institute of Technology “Yet another great book in the classic ‘Head First’ style.” — TW Scannell “JavaScript has long been the client-side engine that drives pages on the Web, but it has also long been misunderstood and misused. With Head First JavaScript, Michael Morrison gives a straightforward and easy-to-understand introduction of this language, removing any misunderstanding that ever existed and showing how to most effectively use it to enhance your web pages.” — Anthony T. Holdener III, Web applications developer, and the author of Ajax: The Definitive Guide. “A web page has three parts—content (HTML), appearance (CSS), and behaviour (JavaScript). Head First HTML introduced the first two, and this book uses the same fun but practical approach to introduce JavaScript. The fun way in which this book introduces JavaScript and the many ways in which it reinforces the information so that you will not forget it makes this a perfect book for beginners to use to start them on the road to making their web pages interactive.” — Stephen Chapman, Owner Felgall Pty Ltd., JavaScript editor, about.com “This is the book I’ve been looking for to recommend to my readers. It is simple enough for complete beginners but includes enough depth to be useful to more advanced users. And it makes the process of learning fun. This might just be the only JavaScript book you ever need.” — Julie L Baumler, JavaScript Editor, BellaOnline.com Other related books from O’Reilly Learning PHP & MySQL Web Database Applications with PHP and MySQL Programming PHP Learning MySQL PHP in a Nutshell PHP CookbookTM PHP HacksTM MySQL in a Nutshell MySQL CookbookTM Other books in O’Reilly’s Head First series Head First JavaTM Head First Object-Oriented Analysis and Design (OOA&D) Head First HTML with CSS and XHTML Head First Design Patterns Head First Servlets and JSP Head First EJB Head First PMP Head First SQL Head First Software Development Head First JavaScript Head First Ajax Head First Physics Head First Statistics Head First Rails Head First Web Design Head First Algebra Head First PHP & MySQL Wouldn’t it be dreamy if there was a PHP & MySQL book that made databases and server-side web programming feel like a match made in heaven? It’s probably just a fantasy... Lynn Beighley Michael Morrison Beijing • Cambridge • Kln • Sebastopol • Taipei • Tokyo Head First PHP & MySQL by Lynn Beighley and Michael Morrison Copyright © 2009 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly Media books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected] Series Creators: Kathy Sierra, Bert Bates Series Editor: Brett D. McLaughlin Editor: Sanders Kleinfeld Design Editor: Louise Barr Cover Designers: Louise Barr, Steve Fehler Production Editor: Brittany Smith Proofreader: Colleen Gorman Indexer: Julie Hawks Page Viewers: Julien and Drew Michael’s nephew Julien generously lent his Superman powers to help get this book finished. Printing History: December 2008: First Edition. Drew is, at thi moment, installins very a new kitchen in g Lynn’s new old ho use. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The Head First series designations, Head First PHP & MySQL, and related trade dress are trademarks of O’Reilly Media, Inc. 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 O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. No hardwood floors, UFOs, Elvis look-alikes, or virtual guitars were harmed in the making of this book. But a few broken hearts were mended thanks to some careful mismatching! ISBN: 978-0-596-00630-3 [M] For my parents, who frequently use web applications and are always there for me. - Lynn Beighley To Rasmus Lerdorf, who single-handedly sparked the language that would eventually become PHP as we know it now. Enduring proof that it really only takes one person to lead us all down a new, more enlightened path. - Michael Morrison the author(s) Author(s) of Head First PHP & MySQL Lynn Beighley n Michael Morriso Lynn Beighley is a fiction writer stuck in a technical book writer’s body. Upon discovering that technical book writing actually paid real money, she learned to accept and enjoy it. After going back to school to get a Masters in Computer Science, she worked for the acronyms NRL and LANL. Then she discovered Flash, and wrote her first bestseller. A victim of bad timing, she moved to Silicon Valley just before the great crash. She spent several years working for Yahoo! and writing other books and training courses. Finally giving in to her creative writing bent, she moved to the New York area to get an MFA in Creative Writing. Her Head First-style thesis was delivered to a packed room of professors and fellow students. It was extremely well received, and she finished her degree, finished Head First SQL, and just finished Head First PHP & MySQL. Whew! Lynn loves traveling, writing, and making up elaborate background stories about complete strangers. She’s a little scared of UFOs. viii Michael Morrison has been an enthusiastic contributor to the online world ever since he ran a BBS on his Commodore 64 way back when being a nerd was far less cool than it is these days. A few thousand baud later, he still marvels at how far we’ve come, and how fast. Michael doesn’t run a BBS anymore, but he’s still very much involved in the modern equivalents and the tools we use to build them. He spends most of his “official” time writing about web-related technologies, having authored or co-authored over fifty books ranging from mobile game programming to XML. He entered the Head First foray with Head First JavaScript, and hasn’t looked back. Michael is also the founder of Stalefish Labs (www. stalefishlabs.com), an entertainment company specializing in games, toys, and interactive media. And he’s been known to actually spend time offline (gasp!) skateboarding, playing ice hockey, and hanging out next to his koi pond with his wife, Masheed. He even sleeps every once in a while. table of contents Table of Contents (Summary) Intro xxvii 1 It’s Alive: Add Life to Your Static Pages 1 2 How It Fits Together: Connecting to MySQL 59 3 Creating Your Own Data: Create and Populate a Database 103 4 Your Application on the Web: Realistic and Practical Applications 159 5 When a Database Just Isn’t Enough: Working With Data Stored in Files 223 6 Assume They’re All Out to Get You: Securing Your Application 295 7 Remember Me?: Building Personalized Web Apps 345 7 ½ Sharing is Caring: Eliminate Duplicate Code 417 8 Harvesting Data: Control Your Data, Control Your World 427 9 Better Living Through Functions: String and Custom Functions 501 10 Rules for Replacement: Regular Expressions 561 11 Drawing Dynamic Graphics: Visualizing Your Data... and More! 605 12 Interfacing to the World: Syndication and Web Services 657 i The Top Ten Topics (We Didn’t Cover): Leftovers 713 ii A Place to Play: Set Up a Development Environment 731 iii Get Even More: Extend Your PHP 749 Table of Contents (the real thing) Intro Your brain on PHP & MySQL.  Here you are trying to learn something, while here your brain is doing you a favor by making sure the learning doesn’t stick. Your brain’s thinking, “Better leave room for more important things, like which wild animals to avoid and whether underwater yoga is a bad idea.” So how do you trick your brain into thinking that your life depends on knowing PHP and MySQL? Who is this book for? We know what you’re thinking Metacognition Bend your brain into submission Read me The technical review team Acknowledgments xxviii xxix xxxi xxxiii xxxiv xxxvi xxxvii ix table of contents 1 add life to your static pages It’s Alive You’ve been creating great web pages with HTML, and a sprinkling of CSS. But you’ve noticed that visitors to your site can’t do much other than passively look at the content on the pages. The communication’s one-way, and you’d like to change that. In fact, you’d really like to know what your audience is thinking. But you need to be able to allow users to enter information into a web form so that you can find out what’s on their minds. And you need to be able to process the information and have it delivered to you. It sounds as if you’re going to need more than HTML to take your site to the next level. Have you seen him?  HTML is static and boring 2 PHP brings web pages to life 3 A form helps Owen get the whole story 5 Forms are made of HTML 6 The HTML form has problems 8 HTML acts on the client 10 PHP acts on the server 11 PHP scripts run on the server 12 Use PHP to access the form data 16 PHP scripts must live on a server! 18 The server turns PHP into HTML 22 A few PHP rules to code by 25 Finding the perfect variable name 26 Variables are for storing script data 31 $–POST is a special variable that holds form data 33 $–POST transports form data to your script 34 Creating the email message body with PH P 44 Even plain text can be formatted...a little 46 Newlines need double-quoted strings 47 Assemble an email message for Owen 48 Variables store the email pieces and parts 49 Sending an email message with PHP 50 Owen starts getting emails 53 Owen starts losing emails 54 table of contents 2 connecting to MySQL How it fits together Knowing how things fit together before you start building is a good idea. You’ve created your first PHP script, and it’s working well. But getting your form results in an email isn’t good enough anymore. You need a way to save the results of your form, so you can keep them as long as you need them and retrieve them when you want them. A MySQL database can store your data for safe keeping. But you need to hook up your PHP script to the MySQL database to make it happen. The new report form is great, but now I’m getting too many emails. I can’t drink enough caffeine to go through them all when I first receive them. Owen’s PHP form works well. Too well... 60 MySQL excels at storing data 61 Owen needs a MySQL database 62 Create a MySQL database and table 64 The INSERT statement in action 67 Use SELECT to get table data 70 Let PHP handle the tedious SQL stuff 73 PHP lets data drive Owen’s web form 74 Connect to your database from PHP 76 Insert data with a PHP script 77 Use PHP functions to talk to the database 78 Get connected with mysqli_connect() 80 Build the INSERT query in PHP 85 Query the MySQL database with PHP 86 Close your connection with mysqli–close() 87 $–POST provides the form data 91 Owen needs help sifting through his data 96 Owen’s on his way to finding Fang 98 $query Don Quayle 37 seconds back in 1991 ght dunno f li they loo ts o ked like poin don ands mad ouskey h e out of t metal... th a i w me yes shot ident.com [email protected] I epres really do love potatos. mysqli_query() xi table of contents 3 create and populate a database Creating your own data You don’t always have the data you need.  Sometimes you have to create the data before you can use it. And sometimes you have to create tables to hold that data. And sometimes you have to create the database that holds the data that you need to create before you can use it. Confused? You won’t be. Get ready to learn how to create databases and tables of your very own. And if that isn’t enough, along the way, you’ll build your very first PHP & MySQL application. Elmer’s cu stomer m This is taking too long. I’d rather be spending my time imitating Elvis, not sending out emails manually. ailing list: Anderso n Jillian w jill_an Kevin [email protected] [email protected] Newsom eckpizza. e uduck.co Amanda com Garcia m aman Roundtr Ed [email protected] [email protected] ee Jo0tt0msup pizza.com Ann Briggs .com jojoround Ch ris @b Harte reakneckp [email protected] Lloyd izza.com boards-r Toth hovercra     -us Anne [email protected] .com Wiley AnneTot [email protected] eckpizza.com Palumbo Andrew limos.com andreww Tom iley Ryan palofmine @objectville.ne t McKinne Alanna angrypir @mightygumba y Cla [email protected] ll.n y Meeker kneckpizz et [email protected] Ann a.com Powers annmee rbuzzcoffee.com Brian ker Manson [email protected] @chocoholic-in Anne eyc.com Mandel [email protected] doit.com Debra bjectville Tedesco debmon .net Janis [email protected] Talwar janistede akneckpiz Vikram [email protected] za.com Szwed [email protected] buzzcoffe Joe rbu e.com Sherida szwedjoe zzcoffee.com n Dia @o na Snow [email protected] bjectville.net Edward mig Otto snowman htygumball.ne Glenn t @tikib Hardy glenn00 Anne [email protected] eanlounge.com Deal ctv [email protected] Mary b0tt0ms ille.net Jagel up nobigde Ann [email protected] .com Melfi dreamgir zzcoffee.c James [email protected] om Oliver eckpizza. [email protected] Lee com Parker [email protected] 0tt0msup.com Anne weathero Ricci [email protected] rama.com Peter sta Reno [email protected] rbuzzcoffee.c Grace om tiki Moss [email protected] beanlounge.com Ze lda Day [email protected] objectville.net Clifford Bolger [email protected] eatherorama.com Joyce breakneck Blunt [email protected] Anne chocoholic pizza.com Bolling anneblu -inc.com Lindy [email protected] Gares [email protected] breakneckpiz za.com Fred be Jacobs [email protected] anlounge.com Anne bjectville .net anne99 @objectv ille.net Big Sale! The Elvis store is open for business 104 Elmer needs an application 105 Visualize Elmer’s application design 106 It all starts with a table 109 Make contact with the MySQL server 110 Create a database for Elmer’s emails 111 Create a table inside the database 112 We need to define our data 113 Take a meeting with some MySQL data types 114 Create your table with a query 117 USE the database before you use it 120 DESCRIBE reveals the structure of tables 123 Elmer’s ready to store data 125 Create the Add Email script 126 The other side of Elmer’s application 133 The nuts and bolts of the Send Email script 134 First things first, grab the data 135 mysqli_fetch_array() fetches query results 136 Looping for a WHILE 139 Looping through data with while 140 You’ve got mail...from Elmer! 145 Sometimes people want out 146 Removing data with DELETE 147 Dear Fellow Elvisonians, vis.com! Big sale this week at MakeMeEl 20% off! Genuine horse hair sideburns get one And don’t forget the “buy one, days free” leisure suits — only three left! xii Use WHERE to DELETE specific data 148 Minimize the risk of accidental deletions 149 MakeMeElvis.com is a web application 154 table of contents 4 realistic and practical applications Your Application on the Web Sometimes you have to be realistic and rethink your plans.  Or plan more carefully in the first place. When your application’s out there on the Web, you may discover that you haven’t planned well enough. Things that you thought would work aren’t good enough in the real world. This chapter takes a...
View Full Document

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture