You are previewing Head First PHP & MySQL.

Head First PHP & MySQL

Cover of Head First PHP & MySQL by Michael Morrison... Published by O'Reilly Media, Inc.
  1. Head First PHP & MySQL
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Advance Praise for Head First PHP & MySQL
  5. Praise for Head First HTML with CSS & XHTML
  6. Praise for Head First JavaScript
  7. Author(s) of Head First PHP & MySQL
  8. How to Use This Book: Intro
    1. Who is this book for?
    2. Who should probably back away from this book?
    3. We know what you’re thinking
    4. We know what your brain is thinking
    5. Metacognition: thinking about thinking
    6. Here’s what WE did:
    7. Here’s what YOU can do to bend your brain into submission
    8. Read Me
    9. The technical review team
    10. Acknowledgments
    11. Safari Books Online
  9. 1. Add Life to your Static Pages: It’s Alive
    1. HTML is static and boring
    2. PHP brings web pages to life
    3. Dogs in space
    4. A form helps Owen get the whole story
    5. Forms are made of HTML
    6. The HTML form has problems
    7. HTML acts on the CLIENT
    8. PHP acts on the SERVER
    9. PHP scripts run on the server
    10. Use PHP to access the form data
    11. PHP scripts must live on a server!
    12. Get your PHP scripts to the server
    13. The server turns PHP into HTML
    14. Deconstructing Owen’s PHP script
    15. A few PHP rules to live code by
    16. Finding the perfect variable name
    17. Variables are for storing script data
    18. $–POST is a special variable that holds form data
    19. $–POST transports form data to your script
    20. Creating the email message body with PHP
    21. Even plain text can be formatted... a little
    22. Newlines need double-quoted strings
    23. Assemble an email message for Owen
    24. Variables store the email pieces and parts
    25. Sending an email message with PHP
    26. Owen starts getting emails
    27. Owen starts losing emails
    28. Your PHP & MySQL Toolbox
  10. 2. Connecting to MySQL: How it fits together
    1. Owen’s PHP form works well. Too well...
    2. MySQL excels at storing data
    3. Owen needs a MySQL database
    4. Create a MySQL database and table
    5. The INSERT statement in action
    6. Use SELECT to get table data
    7. Let PHP handle the tedious SQL stuff
    8. PHP lets data drive Owen’s web form
    9. Connect to your database from PHP
    10. Insert data with a PHP script
    11. Use PHP functions to talk to the database
    12. Get connected with mysqli_connect()
    13. Build the INSERT query in PHP
    14. Query the MySQL database with PHP
    15. Close your connection with mysqli–close()
    16. $–POST provides the form data
    17. Owen needs help sifting through his data
    18. Owen’s on his way to finding Fang
  11. 3. Create and Populate a Database: Creating your own data
    1. The Elvis store is open for business
    2. Elmer needs an application
    3. Visualize Elmer’s application design
    4. It all starts with a table
    5. Make contact with the MySQL server
    6. Create a database for Elmer’s emails
    7. Create a table inside the database
    8. We need to define our data
    9. Take a meeting with some MySQL data types
    10. Create your table with a query
    11. Getting the cart table in front of the horse database
    12. USE the database before you use it
    13. DESCRIBE reveals the structure of tables
    14. Elmer’s ready to store data
    15. Create the Add Email script
    16. The other side of Elmer’s application
    17. The nuts and bolts of the Send Email script
    18. First things first, grab the data
    19. mysqli_fetch_array() fetches query results
    20. Looping for a WHILE
    21. Looping through data with while
    22. You’ve got mail...from Elmer!
    23. Sometimes people want out
    24. Removing data with DELETE
    25. Use WHERE to DELETE specific data
    26. Minimize the risk of accidental deletions
    27. is a web application
    28. Your PHP & MySQL Toolbox
  12. 4. Realistic and Practical Applications: Your Application on the Web
    1. Elmer has some irritated customers
    2. Protecting Elmer from... Elmer
    3. Demand good form data
    4. The logic behind Send Email validation
    5. Your code can make decisions with IF
    6. Testing for truth
    7. IF checks for more than just equality
    8. The logic behind Send Email validation
    9. PHP functions for verifying variables
    10. Test multiple conditions with AND and OR
    11. Form users need feedback
    12. Ease in and out of PHP as needed
    13. Use a flag to avoid duplicate code
    14. Code the HTML form only once
    15. A form that references itself
    16. Point the form action at the script
    17. Check to see if the form has been submitted
    18. Some users are still disgruntled
    19. Table rows should be uniquely identifiable
      1. What Elmer’s table contains now:
      2. What Elmer’s table should contain:
    20. Primary keys enforce uniqueness
    21. The five rules of primary keys:
    22. From checkboxes to customer IDs
    23. Loop through an array with foreach
    24. Your PHP & MySQL Toolbox
  13. 5. Working with Data Stored in Files: When a database just isn’t enough
    1. Virtual guitarists like to compete
      1. Text can’t be trusted
    2. The proof is in the rockin’ picture
    3. The application needs to store images
    4. Planning for image file uploads in Guitar Wars
    5. The high score database must be ALTERed
    6. How do we get an image from the user?
    7. Insert the image filename into the database
    8. Find out the name of the uploaded file
    9. Where did the uploaded file go?
    10. Create a home for uploaded image files
    11. Shared data has to be shared
    12. Shared script data is required
    13. Think of require_once as “insert”
    14. Timing Order is everything with high scores
    15. Honoring the top Guitar Warrior
    16. Format the top score with HTML and CSS
    17. Only small images allowed
    18. File validation makes the app more robust
    19. Plan for an Admin page
      1. These pages are for users:
      2. This page is only for the administrator:
    20. Generate score removal links on the Admin page
    21. Scripts can communicate with each other
    22. Of GETs and POSTs
    23. GET, POST, and high score removal
    24. Isolate the high score for deletion
    25. Control how much you delete with LIMIT
    26. Your PHP & MySQL Toolbox
  14. 6. Securing your Application: Assume they’re all out to get you
    1. The day the music died
    2. Where did the high scores go?
    3. Securing the teeming hordes
    4. Protecting the Guitar Wars Admin page
    5. HTTP authentication requires headers
    6. Take control of headers with PHP
    7. Authenticating with headers
      1. OK, so maybe Guitar Wars is NOT secure
    8. Create an Authorize script
    9. Guitar Wars Episode II : Attack of the High Score Clones
    10. Subtraction by addition
    11. Security requires humans
    12. Plan for moderation in Guitar Wars
    13. Make room for approvals with ALTER
    14. Unapproved scores aren’t worthy
    15. The million-point hack
    16. Everything in moderation... ?
    17. How exactly did she do it?
    18. Tricking MySQL with comments
    19. The Add Score form was SQL injected
    20. Protect your data from SQL injections
    21. A safer INSERT (with parameters)
    22. Form validation can never be too smart
    23. Cease fire!
    24. Your PHP & MySQL Toolbox
  15. 7. building personalized web apps: Remember me?
    1. They say opposites attract
    2. Mismatch is all about personal data
    3. Mismatch needs user log-ins
      1. Username
      2. Password
    4. Come up with a user log-in gameplan
    5. Prepping the database for log-ins
    6. Constructing a log-in user interface
    7. Encrypt passwords with SHA()
    8. Decrypting Comparing passwords
      1. Making room for the encrypted password
    9. Authorizing users with HTTP
    10. Logging In Users with HTTP Authentication
    11. A form for signing up new users
    12. Give users a chance to sign up
    13. Sometimes you just need a cookie
    14. What’s in a cookie?
    15. Bake Use cookies with PHP
    16. Rethinking the flow of log-ins
    17. A cookie-powered log-in
    18. Navigating the Mismatch application
    19. Logging out means deleting cookies
    20. Sessions aren’t dependent on the client
    21. The life and times of sessions
    22. Keeping up with session data
    23. Renovate Mismatch with sessions
    24. Log out with sessions
    25. Complete the session transformation
    26. Users aren’t feeling welcome
    27. Sessions are short-lived...
    28. ... but cookies can last forever!
    29. Sessions + Cookies = Superior log-in persistence
  16. 8. Eliminate Duplicate Code: Sharing is caring
    1. Mismatch is in pieces
    2. Rebuilding Mismatch from a template
    3. Rebuild Mismatch with templates
    4. Mismatch is whole again... and much better organized
  17. 9. Control your Data, Control your World: Harvesting data
    1. Making the perfect mismatch
    2. Mismatching is all about the data
    3. Break down the Mismatch data
      1. Categories
      2. Topics
      3. Responses
    4. Model a database with a schema
    5. Wire together multiple tables
    6. Foreign keys in action
    7. Tables can match row for row
    8. One row leads to many
    9. Matching rows many-to-many
    10. Build a Mismatch questionnaire
    11. Get responses into the database
    12. We can drive a form with data
    13. Speaking of efficiency...
    14. Generate the Mismatch questionnaire form
    15. The data is now driving the form
    16. Strive for a bit of normalcy
    17. When normalizing, think in atoms
    18. Why be normal, really?
    19. Three steps to a normal database
    20. Altering the Mismatch database
    21. So is Mismatch really normal?
    22. A query within a query within a query...
    23. Let’s all join hands tables
    24. Connect the with dots
    25. Surely we can do more with inner joins
    26. Simplifying ON with USING
    27. Nicknames for tables and columns
    28. Joins to the rescue
    29. Love is a numbers game
    30. Five steps to a successful mismatch
    31. Prepare for the mismatch search
    32. Compare users for “mismatchiness”
    33. All we need is a FOR loop
    34. Finishing the mismatching
    35. Your PHP & MySQL Toolbox
  18. 10. String and Custom Functions: Better living through functions
    1. A good risky job is hard to find
    2. The search leaves no margin for error
    3. SQL queries can be flexible with LIKE
    4. Explode a string into individual words
    5. implode() builds a string from substrings
    6. Preprocess the search string
    7. Replace unwanted search characters
    8. The query needs legit search terms
    9. Copy non-empty elements to a new array
    10. Sometimes you just need part of a string
    11. Extract substrings from either end
    12. Multiple queries can sort our results
    13. Functions let you reuse code
    14. Build a query with a custom function
    15. SWITCH makes far more decisions than IF
    16. Give build_query() the ability to sort
    17. We can paginate our results
    18. Get only the rows you need with LIMIT
    19. Control page links with LIMIT
    20. Keep track of the pagination data
    21. Set up the pagination variables
    22. Revise the query for paginated results
    23. Generate the page navigation links
    24. Putting together the complete Search script
    25. The complete Search script, continued...
    26. Your PHP & MySQL Toolbox
  19. 11. Regular Expressions: Rules for replacement
    1. Risky Jobs lets users submit resumes
    2. Decide what your data should look like
    3. Formulate a pattern for phone numbers
    4. Match patterns with regular expressions
    5. Build patterns using metacharacters
    6. Fine-tune patterns with character classes
    7. Check for patterns with preg_match()
    8. Standardize the phone number data
    9. Get rid of the unwanted characters
    10. Matching email addresses can be tricky
    11. Domain suffixes are everywhere
    12. Use PHP to check the domain
    13. Email validation: putting it all together
    14. Your PHP & MySQL Toolbox
  20. 12. Visualizing your Data... and More!: Drawing dynamic graphics
    1. Guitar Wars Reloaded: Rise of the Machines
    2. No input form is safe
    3. We need to separate man from machine
    4. We can defeat automation with automation
    5. Generate the CAPTCHA pass-phrase text
    6. Visualizing the CAPTCHA image
    7. Inside the GD graphics functions
    8. The GD graphics functions continued...
    9. Drawing text with a font
    10. Generate a random CAPTCHA image
    11. Returning sanity to Guitar Wars
    12. Add CAPTCHA to the Add Score script
    13. Five degrees of opposability
    14. Charting mismatchiness
    15. Storing bar graph data
    16. From one array to another
    17. Build an array of mismatched topics
    18. Formulating a bar graphing plan
    19. Crunching categories
    20. Doing the category math
    21. Bar graphing basics
    22. Draw and display the bar graph image
    23. Individual bar graph images for all
    24. Mismatch users are digging the bar graphs
    25. Your PHP & MySQL Toolbox
  21. 13. Syndication and Web Services: Interfacing to the world
    1. Owen needs to get the word out about Fang
    2. Push alien abduction data to the people
    3. RSS pushes web content to the people
    4. RSS is really XML
    5. From database to newsreader
    6. Visualizing XML RSS
    7. Dynamically generate an RSS feed
    8. Link to the RSS feed
    9. A picture video is worth a thousand million words
    10. Pulling web content from others
    11. Syndicating YouTube videos
    12. Make a YouTube video request
    13. Owen is ready to build a REST request
    14. YouTube speaks XML
    15. Deconstruct a YouTube XML response
    16. Visualize the XML video data
    17. Access XML data with objects
    18. From XML elements to PHP objects
    19. Drill into XML data with objects
    20. Not without a namespace!
    21. Fang sightings are on the rise
    22. Lay out videos for viewing
    23. Format video data for display
    24. Your PHP & MySQL Toolbox
  22. A. Leftovers: The Top Ten Topics (we didn’t cover)
    1. #1. Retrofit this book for PHP4 and mysql functions
    2. #2. User permissions in MySQL
    3. #3. Error reporting for MySQL
    4. #4. Exception handling PHP errors
    5. #4. Exception handling PHP errors (cont.)
    6. #5. Object-oriented PHP
    7. #5. Object-oriented PHP (cont.)
      1. So two big advantages of using Object Oriented PHP are:
    8. #6. Securing your PHP application
    9. #6. Securing your PHP application (cont.)
    10. #7. Protect your app from cross-site scripting
    11. #7. Protect your app from cross-site scripting (cont.)
      1. Validate everything
      2. Built-in PHP functions can help
      3. Data is guilty until proven innocent
    12. #8. Operator precedence
    13. #9. What’s the difference between PHP 5 and PHP 6
      1. More Unicode support
    14. #9. What’s the difference between PHP 5 and PHP 6 (cont.)
      1. OO refinements, XML support, and other changes
    15. #10. Reusing other people’s PHP
      1. Drupal
      2. phpBB
      3. Coppermine Gallery
      4. WordPress
  23. B. Set up a Development Environment: A place to play
    1. Create a PHP development environment
    2. Find out what you have
    3. Do you have a web server?
    4. Do you have PHP? Which version?
    5. Do you have MySQL? Which version?
    6. Start with the Web Server
    7. Apache installation... concluded
    8. PHP installation
    9. PHP installation steps
    10. PHP installation steps... concluded
    11. Installing MySQL
      1. Instructions and Troubleshooting
    12. Steps to Install MySQL on Windows
      1. Download your installer
      2. Pick a destination folder
      3. Click “Install” and you’re done!
    13. Enabling PHP on Mac OS X
    14. Steps to Install MySQL on Mac OS X
    15. Moving from production to a live site
    16. Dump your data (and your tables)
    17. Prepare to use your dumped data
    18. Move dumped data to the live server
    19. Connect to the live server
  24. C. Extend your PHP: Get even more
    1. Extending your PHP
      1. If you’re using Windows, you’re in luck
    2. And on the Mac...
  25. Index
  26. About the Authors
  27. Copyright
O'Reilly logo

How to Use This Book: Intro

image with no caption

In this section we answer the burning question: “So why DID they put that in a PHP & MySQL book?”

Who is this book for?

If you can answer “yes” to all of these:

  1. Are you a web designer with HTML or XHTML experience and a desire to take your web pages to the next level?

  2. Do you want to go beyond simple HTML pages to learn, understand, and remember how to use PHP and MySQL to build web applications?

  3. Do you prefer stimulating dinner party conversation to dry, dull, academic lectures?

this book is for you.

Who should probably back away from this book?

If you can answer “yes” to any of these:

  1. Are you completely unfamiliar with basic programming concepts like variables and loops?

    (But even if you’ve never programmed before, you’ll probably be able to get the key concepts you need from this book.)

  2. Are you a kick-butt PHP web developer looking for a reference book?

  3. Are you afraid to try something different? Would you rather have a root canal than mix stripes with plaid? Do you believe that a technical book can’t be serious if it creates an alien abduction database?

this book is not for you.

image with no caption

[Note from marketing: this book is for anyone with a credit card.]

We know what you’re thinking

“How can this be a serious PHP and MySQL book?”

“What’s with all the graphics?”

“Can I actually learn it this way?”

We know what your brain is thinking

image with no caption

Your brain craves novelty. It’s always searching, scanning, waiting for something unusual. It was built that way, and it helps you stay alive.

So what does your brain do with all the routine, ordinary, normal things you encounter? Everything it can to stop them from interfering with the brain’s real job—recording things that matter. It doesn’t bother saving the boring things; they never make it past the “this is obviously not important” filter.

How does your brain know what’s important? Suppose you’re out for a day hike and a tiger jumps in front of you, what happens inside your head and body?

Neurons fire. Emotions crank up. Chemicals surge.

And that’s how your brain knows...

This must be important! Don’t forget it!

But imagine you’re at home, or in a library. It’s a safe, warm, tiger-free zone. You’re studying. Getting ready for an exam. Or trying to learn some tough technical topic your boss thinks will take a week, ten days at the most.

Just one problem. Your brain’s trying to do you a big favor. It’s trying to make sure that this obviously non-important content doesn’t clutter up scarce resources. Resources that are better spent storing the really big things. Like tigers. Like the danger of fire. Like how to quickly hide the browser window with the YouTube video of space alien footage when your boss shows up.

image with no caption

And there’s no simple way to tell your brain, “Hey brain, thank you very much, but no matter how dull this book is, and how little I’m registering on the emotional Richter scale right now, I really do want you to keep this stuff around.”

image with no caption

Metacognition: thinking about thinking

If you really want to learn, and you want to learn more quickly and more deeply, pay attention to how you pay attention. Think about how you think. Learn how you learn.

Most of us did not take courses on metacognition or learning theory when we were growing up. We were expected to learn, but rarely taught to learn.

But we assume that if you’re holding this book, you really want to learn how to build database-driven web sites with PHP and MySQL. And you probably don’t want to spend a lot of time. If you want to use what you read in this book, you need to remember what you read. And for that, you’ve got to understand it. To get the most from this book, or any book or learning experience, take responsibility for your brain. Your brain on this content.

The trick is to get your brain to see the new material you’re learning as Really Important. Crucial to your well-being. As important as a tiger. Otherwise, you’re in for a constant battle, with your brain doing its best to keep the new content from sticking.

image with no caption

So just how DO you get your brain to treat PHP & MySQL like it was a hungry tiger?

There’s the slow, tedious way, or the faster, more effective way. The slow way is about sheer repetition. You obviously know that you are able to learn and remember even the dullest of topics if you keep pounding the same thing into your brain. With enough repetition, your brain says, “This doesn’t feel important to him, but he keeps looking at the same thing over and over and over, so I suppose it must be.”

The faster way is to do anything that increases brain activity, especially different types of brain activity. The things on the previous page are a big part of the solution, and they’re all things that have been proven to help your brain work in your favor. For example, studies show that putting words within the pictures they describe (as opposed to somewhere else in the page, like a caption or in the body text) causes your brain to try to makes sense of how the words and picture relate, and this causes more neurons to fire. More neurons firing = more chances for your brain to get that this is something worth paying attention to, and possibly recording.

A conversational style helps because people tend to pay more attention when they perceive that they’re in a conversation, since they’re expected to follow along and hold up their end. The amazing thing is, your brain doesn’t necessarily care that the “conversation” is between you and a book! On the other hand, if the writing style is formal and dry, your brain perceives it the same way you experience being lectured to while sitting in a roomful of passive attendees. No need to stay awake.

image with no caption

But pictures and conversational style are just the beginning...

Here’s what WE did:

image with no caption

We used pictures, because your brain is tuned for visuals, not text. As far as your brain’s concerned, a picture really is worth a thousand words. And when text and pictures work together, we embedded the text in the pictures because your brain works more effectively when the text is within the thing the text refers to, as opposed to in a caption or buried in the text somewhere.

We used redundancy, saying the same thing in different ways and with different media types, and multiple senses, to increase the chance that the content gets coded into more than one area of your brain.

We used concepts and pictures in unexpected ways because your brain is tuned for novelty, and we used pictures and ideas with at least some emotional content, because your brain is tuned to pay attention to the biochemistry of emotions. That which causes you to feel something is more likely to be remembered, even if that feeling is nothing more than a little humor, surprise, or interest.

image with no caption

We used a personalized, conversational style, because your brain is tuned to pay more attention when it believes you’re in a conversation than if it thinks you’re passively listening to a presentation. Your brain does this even when you’re reading.

We included more than 80 activities, because your brain is tuned to learn and remember more when you do things than when you read about things. And we made the exercises challenging-yet-do-able, because that’s what most people prefer.

image with no caption

We used multiple learning styles, because you might prefer step-by-step procedures, while someone else wants to understand the big picture first, and someone else just wants to see an example. But regardless of your own learning preference, everyone benefits from seeing the same content represented in multiple ways.

We include content for both sides of your brain, because the more of your brain you engage, the more likely you are to learn and remember, and the longer you can stay focused. Since working one side of the brain often means giving the other side a chance to rest, you can be more productive at learning for a longer period of time.

image with no caption

And we included stories and exercises that present more than one point of view, because your brain is tuned to learn more deeply when it’s forced to make evaluations and judgments.

We included challenges, with exercises, and by asking questions that don’t always have a straight answer, because your brain is tuned to learn and remember when it has to work at something. Think about it—you can’t get your body in shape just by watching people at the gym. But we did our best to make sure that when you’re working hard, it’s on the right things. That you’re not spending one extra dendrite processing a hard-to-understand example, or parsing difficult, jargon-laden, or overly terse text.

image with no caption

We used people. In stories, examples, pictures, etc., because, well, because you’re a person. And your brain pays more attention to people than it does to things.

Here’s what YOU can do to bend your brain into submission

So, we did our part. The rest is up to you. These tips are a starting point; listen to your brain and figure out what works for you and what doesn’t. Try new things.

image with no caption

Cut this out and stick it on your refrigerator.

  1. Slow down. The more you understand, the less you have to memorize.

    Don’t just read. Stop and think. When the book asks you a question, don’t just skip to the answer. Imagine that someone really is asking the question. The more deeply you force your brain to think, the better chance you have of learning and remembering.

  2. Do the exercises. Write your own notes.

    We put them in, but if we did them for you, that would be like having someone else do your workouts for you. And don’t just look at the exercises. Use a pencil. There’s plenty of evidence that physical activity while learning can increase the learning.

  3. Read the “There are No Dumb Questions”

    That means all of them. They’re not optional sidebars—they’re part of the core content! Don’t skip them.

  4. Make this the last thing you read before bed. Or at least the last challenging thing.

    Part of the learning (especially the transfer to long-term memory) happens after you put the book down. Your brain needs time on its own, to do more processing. If you put in something new during that processing time, some of what you just learned will be lost.

  5. Drink water. Lots of it.

    Your brain works best in a nice bath of fluid. Dehydration (which can happen before you ever feel thirsty) decreases cognitive function.

  6. Talk about it. Out loud.

    Speaking activates a different part of the brain. If you’re trying to understand something, or increase your chance of remembering it later, say it out loud. Better still, try to explain it out loud to someone else. You’ll learn more quickly, and you might uncover ideas you hadn’t known were there when you were reading about it.

  7. Listen to your brain.

    Pay attention to whether your brain is getting overloaded. If you find yourself starting to skim the surface or forget what you just read, it’s time for a break. Once you go past a certain point, you won’t learn faster by trying to shove more in, and you might even hurt the process.

  8. Feel something.

    Your brain needs to know that this matters. Get involved with the stories. Make up your own captions for the photos. Groaning over a bad joke is still better than feeling nothing at all.

  9. Write a lot of code!

    There’s only one way to learn to program: writing a lot of code. And that’s what you’re going to do throughout this book. Coding is a skill, and the only way to get good at it is to practice. We’re going to give you a lot of practice: every chapter has exercises that pose problems for you to solve. Don’t just skip over them—a lot of the learning happens when you solve the exercises. We included a solution to each exercise—don’t be afraid to peek at the solution if you get stuck! (It’s easy to get snagged on something small.) But try to solve the problem before you look at the solution. And definitely get it working before you move on to the next part of the book.


    PHP and MySQL let you build real-world web applications - don’t forget to upload them and try them out on a real web server.

Read Me

This is a learning experience, not a reference book. We deliberately stripped out everything that might get in the way of learning whatever it is we’re working on at that point in the book. And the first time through, you need to begin at the beginning, because the book makes assumptions about what you’ve already seen and learned.

We begin by teaching simple programming concepts and database connection basics, then more complicated PHP functions and MySQL statements, and finally more complex application concepts.

While it’s important to create applications that allow users to add data to and retrieve data from your web application, before you can do that you need to understand the syntax of both PHP and MySQL. So we begin by giving you PHP and MySQL statements that you can actually try yourself. That way you can immediately do something with PHP and MySQL, and you will begin to get excited about them. Then, a bit later in the book, we show you good application and database design practices. By then you’ll have a solid grasp of the syntax you need, and can focus on learning the concepts.

We don’t cover every PHP and MySQL statement, function, or keyword.

While we could have put every single PHP and MySQL statement, function, and keyword in this book, we thought you’d prefer to have a reasonably liftable book that would teach you the most important statements, functions, and keywords. We give you the ones you need to know, the ones you’ll use 95 percent of the time. And when you’re done with this book, you’ll have the confidence to go look up that function you need to finish off that kick-ass application you just wrote.

We support PHP 5 and MySQL 5.0.


You can actually use PHP 4 with this book by making a few modifications to the code. Check them out in #1 of Appendix A.

Because so many people still use PHP 4 or 5, we avoid any PHP 4, 5, or 6 specific code wherever possible. We suggest you use PHP 5 or 6 and MySQL 5 or 6 while learning the concepts in this book. In developing this book, we focused on PHP 5 and MySQL 5, while making sure our code was compatible with later versions.

You need a web server that supports PHP.

PHP has to be run through a web server to work correctly. You need Apache or some other web server installed on your local machine or a machine to which you have some access so that you can run MySQL commands on the data. Check out Appendixes ii and iii for instructions on how to install and extend PHP and MySQL.

We use MySQL.

While there’s Standard SQL language, in this book we focus on the particular syntax of MySQL. With only a few syntax changes, the code in this book should work with Oracle, MS SQL Server, PostgreSQL, DB2, and quite a few more Relational Database Management Systems (RDBMSs) out there. You’ll need to look up the particular PHP functions and syntax if you want to connect to these other RDBMSs. If we covered every variation in syntax for every command in the book, this book would have many more pages. We like trees, so we’re focusing on MySQL.

The activities are NOT optional.

The exercises and activities are not add-ons; they’re part of the core content of the book. Some of them are to help with memory, some are for understanding, and some will help you apply what you’ve learned. Don’t skip the exercises. The crossword puzzles are the only thing you don’t have to do, but they’re good for giving your brain a chance to think about the words and terms you’ve been learning in a different context.

The redundancy is intentional and important.

One distinct difference in a Head First book is that we want you to really get it. And we want you to finish the book remembering what you’ve learned. Most reference books don’t have retention and recall as a goal, but this book is about learning, so you’ll see some of the same concepts come up more than once.

The examples are as lean as possible.

Our readers tell us that it’s frustrating to wade through 200 lines of an example looking for the two lines they need to understand. Most examples in this book are shown within the smallest possible context, so that the part you’re trying to learn is clear and simple. Don’t expect all of the examples to be ultra robust, or always complete—they are written specifically for learning, and aren’t necessarily fully-functional.


Several of the examples are full-blown web applications that do some pretty powerful things.

We’ve placed all of the example code and applications on the Web so you can copy and paste parts of them into your text editor or MySQL Terminal, or upload them as-is to your own web server for testing. You’ll find it all at

The Brain Power exercises don’t have answers.

For some of them, there is no right answer, and for others, part of the learning experience of the Brain Power activities is for you to decide if and when your answers are right. In some of the Brain Power exercises, you will find hints to point you in the right direction.

The technical review team

image with no caption

Jereme Allen

image with no caption

David Briggs

image with no caption

Will Harris

image with no caption

Stephanie Liese

image with no caption

Steve Milano

image with no caption

Harvey Quamen

image with no caption

Chris Shiflett

Technical Reviewers:

Jereme Allen is a senior level web developer with experience utilizing state of the art technologies to create web applications. He has nine plus years of experience utilizing PHP, MySQL, as well as various other frameworks, operating systems, programming languages and development software.

David Briggs is a technical author and software localization engineer living in Birmingham, England. When he’s not being finicky about how to guide users through a particularly tricky piece of software, he likes nothing better than to get out in the local park with his wife, Paulette, and Cleo, the family dog.

Will Harris spends his days running an IT department that provides services to 11 companies on 4 continents, and he is the Vice President of the Las Vegas PASS (Professional Association for SQL Server) chapter. At night, he hops into a phone booth and puts on his web 2.0 suit, helping the designers and developers at Powered By Geek ensure that their data platforms are flexible, portable, maintainable, and FAST, using MySQL and Rails. He also enjoys spending time with his wife, Heather, his beautiful children, Mara and Ellie, and his dog, Swiper.

Stephanie Liese is a technical trainer and web developer in Sacramento, California. When she isn’t extolling the virtues of standards compliant code or debugging a CSS layout, you will find her sweating it out in a hot yoga class.

If Steve Milano isn’t slinging code for The Day Job™ or playing punk rock with his band, Onion Flavored Rings, in some unventilated basement, he’s probably at home with his laptop, neglecting feline companion, Ralph, and human companion, Bianca.

Harvey Quamen gave up a computer programming career to join the jet-setting, paparazzi-filled, high profile world of academia. He’s currently an Associate Professor of English and Humanities Computing at the University of Alberta, where he teaches courses on cyberculture, 20th-century literature, and web development—including PHP and MySQL.

Chris Shiflett is the Chief Technology Officer of OmniTI, where he leads the web application security practice and guides web development initiatives. Chris is a thought leader in the PHP and web application security communities—a widely-read blogger at, a popular speaker at industry conferences worldwide, and the founder of the PHP Security Consortium. His books include Essential PHP Security (O’Reilly) and HTTP Developer’s Handbook (Sams).


Our editors:

Many thanks go to Brett McLaughlin for the awesome storyboarding session that got us on the right track, and his ruthless commitment to cognitive learning.

The book would not exist if not for the heroic effort, patience, and persistence of Sanders Kleinfeld. He always managed to catch the balls, or was it cats, we were juggling when we inevitably dropped one (or three!), and we appreciate it. We hope he gets a chance to put his feet up for a couple of days before taking on another project as difficult as this one.

image with no caption

The O’Reilly team:

Thanks to Lou Barr for her phenomenal design skill, making this book such a visual treat.

image with no caption

Thanks also to Brittany Smith for all her hard work at the last minute, and to Caitrin McCullough for getting the example web sites up and running. And to Laurie Petrycki for having faith that we could write another great Head First book.

image with no caption

And more:

image with no caption

Finally, a big thanks goes out to Elvis Wilson for putting together the alien YouTube videos for Chapter 13. Excellent job! Especially seeing as how he’s merely a simple caveman art director.

Safari Books Online

When you see a Safari® icon on the cover of your favorite technology book that means the book is available online through the O’Reilly Network Safari Bookshelf.

Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at

The best content for your career. Discover unlimited learning on demand for around $1/day.