Tải bản đầy đủ

1262 PHP MySQL the missing manual, 2nd edition

www.it-ebooks.info


www.it-ebooks.info


PHP & MySQL
Second Edition

The book that should have been in the box®

Brett McLaughlin

Beijing | Cambridge | Farnham | Köln | Sebastopol | Tokyo

www.it-ebooks.info


PHP & MySQL: The Missing Manual, Second Edition
by Brett McLaughlin
Copyright © 2013 Brett McLaughlin. 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 books may be purchased for educational, business, or sales promotional use.
Online editions are also available for most titles (http://my.safaribooksonline.com).
For more information, contact our corporate/institutional sales department: (800)
998-9938 or corporate@oreilly.com.
November 2011: First Edition.
November 2012: Second Edition.
Revision History for the Second Edition:
2012-11-5

First release

See http://oreilly.com/catalog/errata.csp?isbn=0636920024927 for release details.

The Missing Manual is a registered trademark of O’Reilly Media, Inc. The Missing
Manual logo, and “The book that should have been in the box” 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 is aware of a trademark claim, the
designations are capitalized.
While every precaution has been taken in the preparation of this book, the publisher
assumes no responsibility for errors or omissions, or for damages resulting from the
use of the information contained in it.

[LSI]
ISBN: 978-1-449-32557-2

www.it-ebooks.info


Contents
The Missing Credits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Part One:


Chapter 1:



PHP and MySQL Basics
PHP: What, Why, and Where?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
PHP Comes in Two Flavors: Local and Remote. . . . . . . . . . . . . . . . . . . . . . . . . 15
PHP: Going Local . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Write Your First Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Run Your First Program. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
But Where’s That Web Server?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

Chapter2:

PHP Meets HTML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Script or HTML?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
PHP Talks Back. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Run PHP Scripts Remotely. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54



Chapter 3:

PHP Syntax: Weird and Wonderful. . . . . . . . . . . . . . . . . . . . . . . . . 61
Get Information from a Web Form. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Working with Text in PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
The $_REQUEST Variable Is an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
What Do You Do with User Information?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90



Chapter 4:

MySQL and SQL: Database and Language. . . . . . . . . . . . . . . . . 91
What Is a Database?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Installing MySQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
SQL Is a Language for Talking to Databases. . . . . . . . . . . . . . . . . . . . . . . . . . 104

Part Two:


Chapter 5:

Dynamic Web Pages
Connecting PHP to MySQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Writing a Simple PHP Connection Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Cleaning Up Your Code with Multiple Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Building a Basic SQL Query Runner. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

iii

www.it-ebooks.info




Chapter 6:

Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
String Matching, Double-Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156



Chapter 7:

Generating Dynamic Web Pages. . . . . . . . . . . . . . . . . . . . . . . . . . 173
Revisiting a User’s Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Planning Your Database Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Saving a User’s Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Show Me the User. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Revisiting (and Redirecting) the Create User Script. . . . . . . . . . . . . . . . . . . 208

Part Three:


Chapter 8:

From Web Pages to Web Applications
When Things Go Wrong (and They Will). . . . . . . . . . . . . . . . . . 221
Planning Your Error Pages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Finding a Middle Ground for Error Pages with PHP. . . . . . . . . . . . . . . . . . . . 229
Add Debugging to Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Redirecting On Error. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242



Chapter 9:

Handling Images and Complexity. . . . . . . . . . . . . . . . . . . . . . . . . 253
Images Are Just Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Images Are for Viewing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
And Now for Something Completely Different. . . . . . . . . . . . . . . . . . . . . . . . 288

Chapter 10:

Binary Objects and Image Loading. . . . . . . . . . . . . . . . . . . . . . . 289
Storing Different Objects in Different Tables . . . . . . . . . . . . . . . . . . . . . . . . . 290
Inserting a Raw Image into a Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
Your Binary Data Isn’t Safe to Insert...Yet . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Connecting Users and Images. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Show Me the Image!. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Embedding an Image Is Just Viewing an Image. . . . . . . . . . . . . . . . . . . . . . .324
So, Which Approach Is Best?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330



Chapter 11:

Listing, Iterating, and Administrating.. . . . . . . . . . . . . . . . . . . . 333
Thinking about What You Need as an Admin. . . . . . . . . . . . . . . . . . . . . . . . . 334
Listing All Your Users. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Deleting a User. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Talking Back to Your Users. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Standardizing on Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Integrating Utilities, Views, and Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

iv

Contents

www.it-ebooks.info


Part Four:

Security and the Real World

Chapter 12:

Authentication and Authorization. . . . . . . . . . . . . . . . . . . . . . . . 385
Basic Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Abstracting What’s the Same . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
Passwords Don’t Belong in PHP Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
Passwords Create Security, But Should Be Secure. . . . . . . . . . . . . . . . . . . . . 413

Chapter 13:

Cookies, Sign-Ins, and Ditching Crummy Pop-Ups. . . . . . . . 419
Moving Beyond Basic Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Logging In with Cookies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
Adding Context-Specific Menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443

Chapter 14:

Authorization and Sessions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Modeling Groups in Your Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Checking for Group Membership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Group-Specific Menus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
Entering Browser Sessions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
Memory Lane: Remember That Phishing Problem?. . . . . . . . . . . . . . . . . . . . 486
Why Would You Ever Use Cookies? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489

Part Five:

Appendixes

Appendix A:

Installing PHP on Windows Without WAMP. . . . . . . . . . . . . . . 493

Appendix B:

Installing MySQL Without MAMP or WAMP. . . . . . . . . . . . . . . 499
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513

Contents

www.it-ebooks.info

v


www.it-ebooks.info


The Missing Credits
About the Author
Brett McLaughlin is a senior-level technologist and strategist,
active especially in web programming and data-driven, customer-facing systems. Rarely focused on only one component of a
system, he architects, designs, manages, and implements largescale applications from start to finish with mission-critical implementations and deadlines.
Of course, that’s all fancy-talk for saying that Brett’s a geek,
spending most of his day in front of a computer with his hands
flying across a keyboard. Currently, he spends most of his time
working on NASA projects, which sounds much cooler than it actually is. But hey,
maybe that satellite overhead really is controlled by PHP and MySQL...

About the Creative Team
Nan Barber (editor) has been working on the Missing Manual series since its inception. She lives in Boston with her husband and various electronic devices. Email:
nanbarber@oreilly.com.
Holly Bauer (production editor) lives in Ye Olde Cambridge, Massachusetts, where
she is an avid home cook, prolific DIYer, and mid-century modern furniture design
enthusiast. Email: holly@oreilly.com.
Bob Russell (copyeditor) is a documentation specialist and President of Octal Publishing, Inc., in Salem, New Hampshire (www.octalpub.com). Email: bob.russell@
octalpub.com.
Bob Pfahler (indexer) is a freelance indexer. For the past five years, he has indexed
many computer books as well as biographies, history, and business books. When
he is not working, he likes to take bike rides in the foothills outside of Denver. He indexed this book as an associate for Potomac Indexing (www.potomacindexing.com).
Roger House (technical reviewer) is a freelance software developer living in northern
California. He has written code in many languages for various kinds of applications.
He enjoys algorithm design, use of data structures, and applications of mathematics.
Web: www.rogerfhouse.com. Email: rhouse@sonic.net.
Steve Suehring (technical reviewer) is a technical architect with an extensive background finding simple solutions to complex problems. Steve plays several musical
instruments (not at the same time) and can be reached through his website www​
.​braingia.org.

vii

www.it-ebooks.info


Acknowledgments
Acknowledgments are nearly impossible to do well. Before you can thank anyone
of substance, the music swells and they’re shuffling you off stage. Seriously, apart
from the writing, there’s my wife, Leigh, and my kids, Dean, Robbie, and Addie.
Any energy or joy or relaxation that happens during the long writing process filters
through those four, and there are never enough royalties to cover the time lost with
them. I suppose it’s a reflection of their love and support for me that they’re OK
with me writing anyway.
There’s certainly the writing. Brian Sawyer was the first guy to call me when I became
available to write, and he called when I was really in need of just what he gave me:
excitement about me writing and encouragement that I could write for the Missing
Manual series. I won’t forget that call anytime soon. And, there’s Nan Barber, who
IM’ed and emailed me throughout the entire process. She showed a really unhealthy
level of trust that wasn’t earned, and I’m quite thankful...especially in the dark days of
early August, when I had hundreds of pages left to write, in just a few short weeks.
Roger House and Steve Suehring, my technical reviewers, were both picky and
gentle. That’s about all you can ask. And Steve filled out my PHP holes. He caught
one particularly nasty issue that I think vastly improved the book. You don’t realize
this, but you owe him a real debt of thanks if this book helps you.
——Brett McLaughlin

The Missing Manual Series
Missing Manuals are witty, superbly written guides to computer products that don’t
come with printed manuals (which is just about all of them). Each book features a
handcrafted index and cross-references to specific pages (not just chapters).
Recent and upcoming titles include:

Access 2010: The Missing Manual by Matthew MacDonald
Adobe Edge Animate: The Missing Manual by Chris Grover
Buying a Home: The Missing Manual by Nancy Conner
CSS3: The Missing Manual, Third Edition, by David Sawyer McFarland
Creating a Website: The Missing Manual, Third Edition, by Matthew MacDonald
David Pogue’s Digital Photography: The Missing Manual by David Pogue
Dreamweaver CS5.5: The Missing Manual by David Sawyer McFarland
Droid 2: The Missing Manual by Preston Gralla
Droid X2: The Missing Manual by Preston Gralla
Excel 2010: The Missing Manual by Matthew MacDonald
Facebook: The Missing Manual, Third Edition by E.A. Vander Veer

viii

The Missing Credits

www.it-ebooks.info


FileMaker Pro 12: The Missing Manual by Susan Prosser and Stuart Gripman
Flash CS5.5: The Missing Manual by Chris Grover
Galaxy S II: The Missing Manual by Preston Gralla
Galaxy Tab: The Missing Manual by Preston Gralla
Google Apps: The Missing Manual by Nancy Conner
Google SketchUp: The Missing Manual by Chris Grover
HTML5: The Missing Manual by Matthew MacDonald
iMovie ’11 & iDVD: The Missing Manual by David Pogue and Aaron Miller
iPad: The Missing Manual, Fifth Edition by J.D. Biersdorfer
iPhone: The Missing Manual, Sixth Edition by David Pogue
iPhone App Development: The Missing Manual by Craig Hockenberry
iPhoto ’11: The Missing Manual by David Pogue and Lesa Snider
iPod: The Missing Manual, Eleventh Edition by J.D. Biersdorfer and David Pogue
JavaScript & jQuery: The Missing Manual by David Sawyer McFarland
Kindle Fire: The Missing Manual, Second Edition by Peter Meyers
Living Green: The Missing Manual by Nancy Conner
Mac OS X Snow Leopard: The Missing Manual by David Pogue
Mac OS X Lion: The Missing Manual by David Pogue
Microsoft Project 2010: The Missing Manual by Bonnie Biafore
Motorola Xoom: The Missing Manual by Preston Gralla
Netbooks: The Missing Manual by J.D. Biersdorfer
NOOK Tablet: The Missing Manual by Preston Gralla
Office 2010: The Missing Manual by Nancy Connor, Chris Grover, and Matthew
MacDonald
Office 2011 for Macintosh: The Missing Manual by Chris Grover
Palm Pre: The Missing Manual by Ed Baig
Personal Investing: The Missing Manual by Bonnie Biafore
Photoshop CS6: The Missing Manual by Lesa Snider
Photoshop Elements 11: The Missing Manual by Barbara Brundage
PowerPoint 2007: The Missing Manual by E.A. Vander Veer
Premiere Elements 8: The Missing Manual by Chris Grover

The Missing Credits

www.it-ebooks.info

ix


QuickBase: The Missing Manual by Nancy Conner
QuickBooks 2013: The Missing Manual by Bonnie Biafore
Quicken 2009: The Missing Manual by Bonnie Biafore
Switching to the Mac: The Missing Manual, Snow Leopard Edition by David Pogue
Switching to the Mac: The Missing Manual, Lion Edition by David Pogue
Wikipedia: The Missing Manual by John Broughton
Windows Vista: The Missing Manual by David Pogue
Windows 7: The Missing Manual by David Pogue
Windows 8: The Missing Manual by David Pogue
Word 2007: The Missing Manual by Chris Grover
WordPress: The Missing Manual by Matthew MacDonald
Your Body: The Missing Manual by Matthew MacDonald
Your Brain: The Missing Manual by Matthew MacDonald
Your Money: The Missing Manual by J.D. Roth

x

The Missing Credits

www.it-ebooks.info


Introduction

G

iven that you’re reading this book, the chances are good that you’ve built a
web page in HTML. You’ve styled it by using Cascading Style Sheets (CSS)
and maybe written a little JavaScript to validate your custom-built web
forms. If that wasn’t enough, you’ve learned a lot more JavaScript, threw in some
jQuery, and constructed a whole lot of web pages. Maybe you’ve even moved your
JavaScript into external files, shared your CSS across your entire site, and validated
your HTML with the latest standards.
But now you want more.
Perhaps you’ve become frustrated with your website’s inability to store user information in anything beyond cookies. Maybe you want a full-blown online store, complete
with PayPal integration and details about what items are in stock. Or maybe you’ve
simply caught the programming bug and want to go beyond what HTML, CSS, and
JavaScript can easily give you.
If any of these are the case—and you may find that all of these are the case—learning PHP and MySQL is a great way to take a giant programming step forward. Even
if you’ve never heard of PHP, you’ll find it’s the best way to go from building web
pages to creating full-fledged web applications that store all sorts of information in
databases. This book shows you how to do just that.

1

www.it-ebooks.info


What PHP and
MySQL Can Do

What PHP and MySQL Can Do
PHP can handle payment processing on its own, and it can connect with services
like PayPal and Google Checkout. PHP can store and load images from a database
or a file system and give you the ability to log users in and out as well as control
what they see throughout your application.
Add in MySQL, and you can store your users’ names, addresses, billing data, and even
their preferences regarding the color of their own personal landing page. MySQL
can store just a few bits of data, a few thousand lines of data, or every page access
by every user who ever logs into your application.
And, of course, PHP can easily connect to MySQL. PHP can do everything from
grabbing a user name based on a user ID to storing the details about financial
transactions to actually creating tables and updating their structures, and MySQL
can back-end all that work and store that data. Ultimately, this is the stuff of web
applications; it’s what a web application is.
Obviously, web applications like this aren’t simple. They have a lot of complexity, and
that complexity has to be managed and ultimately tamed into a usable, sensible web
application that you can maintain and your users can enjoy. That’s what this book is
about: building web applications, and doing it with an understanding of what you’re
doing, and why you’re doing it.

What Is PHP?
PHP started out as a set of tools for doing simple web-related tasks. It appeared
on the Web scene way back in 1994. Initially, PHP did nothing more than just track
visits to a particular web page (the online resume of Rasmus Lerdorf—the inventor
of PHP). It was then expanded to interact with databases, as well as provide a tool
set for online guest books and HTML form processing. The next thing you know, it
was hugely popular as an alternative to less web-friendly languages like C.
New versions of PHP started coming out, and an increasing number of web programmers adopted it as their scripting language of choice for web tasks. PHP 3, 4,
and now 5 are now mainstays on the Web. PHP has become fast while remaining
lightweight. And, of course, its ability to easily interact with databases such as MySQL
remains one of its most attractive features.

What Is PHP Like?
PHP is a programming language. It’s like JavaScript in that you spend most of your
time dealing with values and making decisions about which path through your
code should be followed at any given time. But it’s like HTML in that you deal with
output—tags that your users view through the lens of their web browsers. In fact,
PHP in the context of web programming is a bit of a mutt; it does lots of things
pretty well, rather than just doing one single thing. (And, if you’ve ever wondered
why it’s called PHP, see the box on the following page.)

2

PHP & MySQL: The Missing Manual

www.it-ebooks.info


What Is PHP?
FREQUENTLY ASKED QUESTION

Personal Home Page, Indeed
What does PHP stand for?
PHP is an acronym. Originally, it stood for Personal Home Page
Construction Kit , because lots of programmers used it to build
their websites, going much further than what was possible with
HTML, CSS, and JavaScript. But in the last few years, “personal
home page” tends to sound more like something that happens
on one of those really cheap hosting sites, rather than a highpowered programming language.

So now, PHP stands for PHP: Hypertext Preprocessor. If that
sounds geeky, it is. In fact, it’s a bit of a programmer joke: PHP
stands for something that actually contains PHP within itself.
That makes it a recursive acronym, meaning that it references
itself. You don’t have to know what a recursive acronym is;
that won’t be on the quiz. Just be warned that PHP’s recursive
acronym won’t be the last weird and slightly funny thing you’ll
run across in the PHP language.

PHP Is All About the Web
If you came here for web programming, you’re in the right place. Although you can
write PHP programs that run from a command line (check out Figure I-1 for an example), that’s not really where it excels. The PHP programs you write run within your
website, part and parcel with your HTML forms, web sessions, and browser cookies.
For example, PHP is great at integrating with your website’s existing authentication
system, or letting you create one of your own.

Figure I-1

Sure, you can run PHP programs from a Terminal
window or a command shell in Windows. But most
of the time, you won’t. PHP is perfectly suited to the
Web, and that’s where you’ll spend most of your time.

You’ll spend a lot of time not just handing off control to an HTML page, but actually
writing the HTML you’re already familiar with right into your PHP scripts. Lots of
times, you’ll actually write some PHP and then write some HTML, all in the same
PHP file, as in the following example:
require '../../scripts/database_connection.php';
// Get the user ID of the user to show
$user_id = $_REQUEST['user_id'];
// Build the SELECT statement
$select_query = "SELECT * FROM users WHERE user_id = " . $user_id;

Introduction

www.it-ebooks.info

3


What Is PHP?

// Run the query
$result = mysql_query($select_query);
// Assign values to variables
?>






User Profile