Head First PHP & MySQL

Book description

If you're ready to create web pages more complex than those you can build with HTML and CSS, Head First PHP & MySQL is the ultimate learning guide to building dynamic, database-driven websites using PHP and MySQL. Packed with real-world examples, this book teaches you all the essentials of server-side programming, from the fundamentals of PHP and MySQL coding to advanced topics such as form validation, session IDs, cookies, database queries and joins, file I/O operations, content management, and more.

Head First PHP & MySQL offers the same visually rich format that's turned every title in the Head First series into a bestseller, with plenty of exercises, quizzes, puzzles, and other interactive features to help you retain what you've learned.

  • Use PHP to transform static HTML pages into dynamic web sites
  • Create and populate your own MySQL database tables, and work with data stored in files
  • Perform sophisticated MySQL queries with joins, and refine your results with LIMIT and ORDER BY
  • Use cookies and sessions to track visitors' login information and personalize the site for users
  • Protect your data from SQL injection attacks
  • Use regular expressions to validate information on forms
  • Dynamically display text based on session info and create images on the fly
  • Pull syndicated data from other sites using PHP and XML
Throughout the book, you'll build sophisticated examples -- including a mailing list, a job board, and an online dating site -- to help you learn how to harness the power of PHP and MySQL in a variety of contexts. If you're ready to build a truly dynamic website, Head First PHP & MySQL is the ideal way to get going.

Publisher resources

View/Submit Errata

Table of contents

  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. MakeMeElvis.com 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

Product information

  • Title: Head First PHP & MySQL
  • Author(s): Lynn Beighley, Michael Morrison
  • Release date: December 2008
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9780596006303