Given 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.
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.
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.
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.)
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 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 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:
<?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> <head> <link href="../css/phpMM.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"><h1>PHP & MySQL: The Missing Manual</h1> </div> <div id="example">User Profile</div> <div id="content"> <div class="user_profile"> <h1><?php echo "{$first_name} {$last_name}"; ?></h1> <p><img src="show_image.php?image_id=<?php echo $image_id; ?>" class="user_pic" /> <?php echo $bio; ?></p> <p class="contact_info">Get in touch with <?php echo $first_name; ?> :</p> <ul> <!-- And so on... lots more HTML here. --> </html>
This script references another script, database_connection.php, and then extracts a userâs ID from the request parameters sent by a web browser. The script uses that ID to search a database for the rest of the userâs information. Then, it builds the data into a web page thatâs created on the fly.
The result? Pages that are both full of HTML and have dynamic content, like Figure 2.
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.
If youâve written some JavaScriptâand if youâre checking out this book, thatâs probably the caseâyou know that JavaScript lets you get away with just about anything. 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 great for getting things working quickly, but at the same time, itâs frustrating. It makes finding bugs tricky at times, and working across browsers can be a nightmare.
PHP is not quite as 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 constructed and then run. Thatâs a good thing, because it will 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 is a lot to learn, but everything you learn gives you something on which to build. 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 the tiny yellow warning triangle in Internet Explorer as you do with JavaScript. More often, youâll get a nasty error that stops you in your tracks and screams, âFix me!â And, over the next couple of hundred pages, youâll be able to do just that: fix the problems youâll run across in typical PHP programs, whether youâve written those programs or someone else has.
PHP code comes in the form of scripts, which are plain-text files that you create and fill with code. Whereas HTML uses lots of angle brackets and keywords like html
, head
, and ul
, PHP uses lots of dollar signs ($) and keywords like mysql_query
and echo
. So, HTML and PHP donât look at all alike. But where they are alike is in the basic underlying format: theyâre both just text. You can open up an HTML document not just in a web browser, but in Notepad or an integrated development environment (IDE) like Eclipse or even a command-line editor like vi or emacs. The same is true for PHP: itâs just text. So, get ready; throughout this book, youâll be typing wordsâalbeit strange ones, with lots of underscoresâand saving those words into text files called scripts.
Once youâve got a script, you let a PHP program interpret that script. The PHP interpreter is a piece of software on your web server that reads your script and makes sense of it, giving the web server output and directions about where to go next or how to handle a userâs form field entries. Your scriptâremember, just a text fileâis interpreted, one line at a time, every time it is accessed.
This is a bit different from languages like Java or C++, which are compiled. In those languages, you also write your code 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 subsequent steps. You write PHP, test it out in the browser, and then write some more. Itâs fast, and that usually means itâs pretty fun.
Thereâs one other big difference between PHP and what you may be used to with HTML, CSS, and JavaScript. Itâs a big difference, too; in fact, this difference is such a big deal that itâs going to affect everything you do when it comes to writing PHP scripts, getting those PHP scripts to run, and checking them out in a web browser.
So whatâs the difference? Itâs this: PHP, unlike HTML or CSS or JavaScript, doesnât run entirely in a browser.
What does that mean? Chapter 1 begins to get into the details, but for now, you just need to know that HTML, JavaScript, and CSS are entirely handled by your web browser software. Whether you use Internet Explorer, Apple Safari, Google Chrome, Mozilla Firefox, or Opera, once you have a browser, you have everything you need. Thatâs why you can write an HTML document, save it with an extension like .html, double-click that file, and voilà : your browser opens (assuming youâve got things set up on your computer the right way) and youâre looking at HTML. You can reference CSS in that HTML file as well as JavaScript, and the same thing happens. Write code, save, and open. Pretty easy stuff.
With PHP, youâll need a bit more than that. The PHP interpreter interacts with your browser but doesnât run in the browser automatically. In other words, you cannot simply double-click a PHP script and expect a browser to pop up and handle things. HTML forms that submit to a PHP script wonât âjust workâ the way that HTML and JavaScript do.
Right now, then, you just need to know two things:
Itâs going to take a little more work to get your PHP programs working. You canât just write and save a script and then open it the way you can HTML. Donât worry; youâll learn exactly how to get PHP working both locallyâon your computerâand remotelyâon a web hosting companyâs servers. But itâs going to take a little more effort.
Itâs not trivial to set up everything you need to run PHP programs on your own computerâespecially once you involve MySQL, too (more on this in just a moment). Thatâs why Internet Service Providers (ISPs) and web hosting companies exist! They take care of that sort of thing. So, although itâs possible to do all your PHP coding on your own machine, itâs a lot more common to write your scripts and then send them to a remote web server. Sound scary? Itâs notâ¦but itâs important. Youâll spend a good bit of time in this book writing code and uploading it to a server.
PHP is different from JavaScript and HTML in some important ways. Youâll get used to those differences, but youâll be a lot less frustrated and confused if you go in knowing that youâll have to do some things differently when it comes to PHP.
MySQL is a database. It stores your information, your usersâ information, and anything else you want to stuff into it. But, beyond its ability to store information, MySQL is popular. In fact, itâs the most popular open-source database system in the world. It has literally millions of users working with it, finding and reporting problems, and testing its limits. And, it has thousands of developers that at some point have helped improved its code base.
MySQL is essentially a warehouse in which you can store things to be looked up later. Not only that, MySQL provides you with a really fast mechanism to find all that stuff you stuck in the warehouse whenever itâs needed. By the time youâre through this book, youâll love MySQL. It will do work that you could never do on your own, and it will do that work tirelessly and quickly.
Itâs also the perfect companion to PHP. Itâs easy to install on any system; it doesnât take up huge resources like larger commercial offerings such as Oracleâs or IBMâs products; and its easy to connect to. In fact, youâll find that PHP and MySQL are perfectly matched, with a ton of easy-to-use functions that let PHP scripts to do just about anything you can imagine with a MySQL database.
Note
Thereâs actually a lot more nuance to MySQLâand SQL, the language in which youâll interact with MySQLâbut itâs better to save that for Chapter 4, when youâve got a little PHP under your belt.
PHP is a web-based language, not a program that comes in a box. Tens of thousands (maybe even hundreds of thousands) of websites have bits of PHP tutorial or 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, therefore, 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 blog 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.
PHP and MySQL work almost precisely the same in their Macintosh and Windows versions. Even more important, 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 has to deal with operating system issues; you get to focus on your code and information.
In the first few chapters, you get your system set up to write code and deal with PHP scripts. Thereafter, you will soon forget about whether youâre on a Macintosh or using a Windows-based computer. Youâll just be writing code, the same way you write HTML and CSS. And remember, youâll soon be uploading your scripts to remote web servers, so your own computer is only part of the solution.
One piece of software thatâs absolutely critical is a good FTP client. No matter how awesome your scripting skills becomeâand theyâre gonna be formidable!âyou have to actually get your scripts to your web hosting server. Thatâs where FTP comes in: itâs the means by which a file on your computer gets placed in just the right location on a remote server.
Note
From the author: 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 points you to several great editors, and the fancier ones will have FTP built right in. If you donât opt for an integrated solution, a dedicated FTP 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 hosting service (which might also be called your ISP), and fired up. Youâre gonna need it.
PHP & MySQL: The Missing Manual is divided into five parts, each containing several chapters:
Part 1. In the first four chapters, you 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 also install MySQL and become thoroughly acquainted with the structure of a database.
Part 2. These are the chapters in which you start to build the basics of a solid web application. You 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 use regular expressions and string handling to bend letters, numbers, and slashes to your will.
Part 3. With a solid foundation, youâre ready to connect your web pages into a more cohesive unit. You add custom error handling so that your users wonât become confused when things go wrong. You also add your own debugging to help you find problems. You also learn how to 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. In even the simplest of applications, logging in and logging out is critical. In this section, you build an authentication system and then deal with passwords (which are important, but a bit of a pain). You then work with cookies and sessions, and use both to create a group-based authorization system for your web application.
Part 5. Although the first several chapters show you how to get PHP and MySQL onto your own Macintosh or Windows-based computer the easy way, using the WampServer software package or the Macâs built-in installation, the two appendixes in this section show you how to install the software manually for full control of all the details.
At the Missing Manual website (www.missingmanuals.com/cds/phpmysqlmm2e), you can find every single code example, from every chapter, in the state it is shown for that chapter.
As the owner of a Missing Manual, youâve got more than just a book to read. Online, you can find example files so that 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.
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/phpmysqlmm2e 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 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 links that you can click to bring you to the websites mentioned in this book.
If you register this book at Oreilly.com (http://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.
Got questions? Need more information? Fancy yourself a book reviewer? On the 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.
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/phpmysql2e-mm to report an error and view existing corrections.
Safari® Books Online is an on-demand digital library that lets you easily search over 24,000 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 the library online. You can 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. You can 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, 2nd Edition 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.