Introduction

You’ve built a web page in HTML. You’ve even styled it with Cascading Style Sheets (CSS) and written a little JavaScript to validate your custom-built web forms. But that wasn’t enough, so you learned a lot more JavaScript, threw in some jQuery, and constructed a whole lot of web pages. 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.

Maybe 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’s 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 these are the case!—then 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.

What Is PHP?

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 below.)

PHP Is All About the Web

If you came here for web programming, you’re in the right place. While you can write PHP programs that run from a command line (check out Figure 1 for an example), that’s not really where PHP excels.

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

PHP comes ready to work with HTML forms and web sessions and browser cookies. It’s great at integrating with your website’s existing authentication system, or letting you create one of your own. 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. 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:

<?php

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;

// Run the query
$result = mysql_query($select_query);

// Assign values to variables
?>

<html>
  <!-- All your HTML and inline PHP -->
</html>

The result? Pages that are both full of HTML and have dynamic content, like Figure 2.

This page is as much PHP as HTML. It looks up your visitor’s name in the database and displays it dynamically. The menu creates a Show Profile option specific to this user. But there’s still lots and lots of HTML. This is PHP at its best: combining the HTML and even JavaScript that you know with the PHP you’re about to learn.
Figure 2. This page is as much PHP as HTML. It looks up your visitor’s name in the database and displays it dynamically. The menu creates a Show Profile option specific to this user. But there’s still lots and lots of HTML. This is PHP at its best: combining the HTML and even JavaScript that you know with the PHP you’re about to learn.

JavaScript Is Loose, PHP Is…Less So

If you’ve written some JavaScript—and if you’re checking out this book, that’s probably the case—then you know that JavaScript lets you do just about anything you want. You can occasionally leave out semicolons; you can use brackets, or not; you can use the var keyword, or not. That sort of looseness is both great for getting things working quickly, and at the same time, frustrating. It makes finding bugs tricky at times, and working across browsers can be a nightmare.

PHP is not quite so loose as JavaScript, so it makes you learn a little more structure and tighten up your understanding of what’s going on as your program is interpreted. That’s a good thing, as it’ll end up making you tighten up your JavaScript skills, too. And, perhaps best of all, PHP’s stodgy consistency makes it easier to learn. It gives you firm rules to hang on to, rather than lots of “You can do this…or this…or this…”

So get ready. There’s lots to learn, but everything you learn gives you something to build on. And PHP lets you know right away when there’s a problem. You won’t need to pop open an Error Console or keep an eye out for Internet Explorer’s tiny yellow warning triangle like you do with JavaScript.

PHP Is Interpreted

PHP code comes in the form of scripts, which are plain text files you write. The PHP interpreter is a piece of software on your web server that reads that file and makes sense of it, giving the Web server HTML output and directions about where to go next, or how to interpret a user’s form entry. Your text file is interpreted, one line at a time, every time that file is accessed.

This scheme is different from languages like Java or C++, which are compiled. In those languages, you write in text files, but then run a command that turns those text files into something else: class files, binary files, pieces of unreadable code that your computer uses.

The beauty of an interpreted language like PHP—and JavaScript, for that matter—is that you write your code and go. You don’t need a bunch of tools or steps. You write PHP. Test it out in the browser. Write some more. It’s fast, and that usually means it’s pretty fun.

What Is MySQL?

MySQL is a database. It stores your information, your users’ information, and anything else you want to stuff into it. There’s actually a lot more nuance to MySQL—and SQL, the language in which you’ll interact with MySQL (but better to save that for Chapter 3—when you’ve got a little PHP and context under your belt).

For now, think of MySQL as a warehouse where you can store things to be looked up later. Not only that, MySQL provides you a really fast little imp that runs around finding all that stuff you stuck in the warehouse whenever it’s needed. By the time you’re through this this book, you’ll love that imp…er…MySQL. It’ll do work that you could never do on your own, and it’ll do that work tirelessly and quickly.

About This Book

PHP is a web-based language, not a program that comes in a box. And there are literally tens (hundreds?) of thousands of websites that have bits of PHP instruction on them. That’s great, right? Well, not so much. Those websites aren’t all current. Some are full of bugs. Some have more information in the comment trails—scattered amongst gripes, complaints, and lambasting from other programmers—as they do in the main page. It’s no easy matter to find what you’re looking for.

The purpose of this book, then, is to serve as the manual that should have been included when you download PHP. It’s the missing PDF, if you will (or maybe the missing eBook, if you’re a Kindle or Nook or iPad person). In this book’s pages, you’ll find step-by-step instructions for getting PHP running, writing your first program…and your second program…and eventually building a web application from scratch. In addition, you’ll find clear evaluations of the absolutely critical parts of PHP that you’ll use every day, whether you’re building a personal weblog or a corporate intranet.

Note

This book periodically recommends other books, covering topics that are too specialized or tangential for a manual about PHP and MySQL. Careful readers may notice that not every one of these titles is published by Missing Manual parent company O’Reilly Media. If there’s a great book out there that doesn’t happen to be published by O’Reilly, this book will still let you know about it.

PHP & MySQL: The Missing Manual is designed to accommodate readers at every technical level. The primary discussions are written for advanced-beginner or intermediate Web authors and programmers. Hopefully, you’re comfortable with HTML and CSS, and maybe even know a bit of JavaScript. But if you’re new to all this Web stuff, take heart: special boxes called “Up to Speed” provide the introductory information you need to understand the topic at hand. If you’re an advanced user, on the other hand, keep your eye out for similar boxes called “Power Users’ Clinic.” They offer more technical tips, tricks, and shortcuts for the experienced computer fan.

Macintosh and Windows

PHP and MySQL work almost precisely the same in their Macintosh and Windows versions. And even more importantly, you’ll do most of your work by uploading your scripts and running your database code against a web server. That means that your hosting provider gets to deal with operating system issues. You get to focus on your code and information.

In the first few chapters, you’ll get your system set up to code and deal with PHP scripts. But you’ll soon forget about whether you’re on Mac or Windows. You’ll just be writing code, the same way you write HTML and CSS.

FTP: It’s Critical

One piece of software you won’t forget you’re using is a good FTP program. Most PHP programmers don’t sit on a remote server typing into a command-line editor like vi or emacs.

Note

AUTHOR’S NOTE Typing in a command-line editor is actually exactly how I work. But then, I’m a dinosaur, a throwback to days when you had to watch commercials to see primetime TV, and you’d miss emails because your pocket didn’t buzz every time your boss whisked you a command through the ether.

Today, for most of you, a good text editor and a good graphical FTP client are much better choices. Seriously, my addiction owns me, and I so badly want to :wq! it.

Chapter 1 will point you at several great editors, and the fancier ones will have FTP built right in. But a program like Cyberduck (www.cyberduck.ch) is great, too. You can write a script, throw it online, and test it all with a few mouse clicks. So go ahead and get that FTP program downloaded, configured for your web server, and fired up. You’re gonna need it.

About the Outline

PHP & MySQL: The Missing Manual is divided into four parts, each containing several chapters:

  • Part 1: PHP and MySQL Basics. In the first three chapters, you’ll install PHP, get it running on your computer, write your first few PHP programs, and learn to do a few basic things like collect user information via a web form and work with text. You’ll also install MySQL and get thoroughly acquainted with the structure of a database.

  • Part 2: Dynamic Web Pages. These are the chapters where you start to build the basics of a solid web application. You’ll add a table in which you can store users and their information, and get a grasp of how easily you can manipulate text. From URLs and emails to Twitter handles, you’ll use regular expressions and string handling to bend letters, numbers, and slashes to your will.

  • Part 3: From Web Pages to Web Applications. With a solid foundation, you’re ready to connect your web pages into a more cohesive unit. You’ll add custom error handling so that your users won’t get confused when things go wrong, and your own debugging to help you find problems. You’ll also store references to users’ images of themselves, store the images themselves in a database, and learn which approach is best in which situations.

  • Part 4: Security and the Real World. In even the simplest of applications, logging in and logging out is critical. You’ll build an authentication system, and then deal with passwords (which are important, but a bit of a pain). You’ll then work with cookies and sessions, and use both to create a group-based authorization system for your web application.

At the Missing Manual website (www.missingmanuals.com/cds/phpmysqlmm), you’ll find every single code example, from every chapter, in the state it was shown for that chapter.

About the Online Resources

As the owner of a Missing Manual, you’ve got more than just a book to read. Online, you’ll find example files so you can get some hands-on experience, as well as tips, articles, and maybe even a video or two. You can also communicate with the Missing Manual team and tell us what you love (or hate) about the book. Head over to www.missingmanuals.com, or go directly to one of the following sections.

Missing CD

This book doesn’t have a CD pasted inside the back cover, but you’re not missing out on anything. Go to www.missingmanuals.com/cds/phpmysqlmm to download code samples, code samples, and also, some code samples. Yup, there are a lot of them. Every chapter has a section of code for that chapter. And you don’t just get completed versions of the book’s scripts. You’ll get a version that matches up with each chapter, so you’ll never get too confused about exactly how your version of a script or web page should look.

And so you don’t wear down your fingers typing long web addresses, the Missing CD page also offers a list of clickable links to the websites mentioned in this book.

Registration

If you register this book at oreilly.com, you’ll be eligible for special offers—like discounts on future editions of PHP & MySQL: The Missing Manual. Registering takes only a few clicks. To get started, type www.oreilly.com/register into your browser to hop directly to the Registration page.

Feedback

Got questions? Need more information? Fancy yourself a book reviewer? On our Feedback page, you can get expert answers to questions that come to you while reading, share your thoughts on this Missing Manual, and find groups for folks who share your interest in PHP, MySQL, and web applications in general. To have your say, go to www.missingmanuals.com/feedback.

Errata

In an effort to keep this book as up-to-date and accurate as possible, each time we print more copies, we’ll make any confirmed corrections you’ve suggested. We also note such changes on the book’s website, so you can mark important corrections into your own copy of the book, if you like. Go to http://tinyurl.com/phpmysql-mm to report an error and view existing corrections.

Safari® Books Online

Safari® Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly.

With a subscription, you can read any page and watch any video from our library online. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features.

O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com.

Get PHP & MySQL: The Missing Manual now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.