Back to description
We assume that since you’ve spent your hard-earned money to purchase this book, you undoubtedly know the enormous benefits... more
We assume that since you’ve spent your hard-earned money to purchase this book, you undoubtedly know the enormous benefits of using Apache, MySQL, and PHP (AMP) together to create and deliver dynamic web sites. But just in case you found this book on your desk one Monday morning with a sticky note from your boss reading “Learn this!,” this chapter looks at what makes the “AMP” combination so popular. This chapter also walks you through installing and configuring all three components of the AMP platform on Windows (installation and configuration for Linux-based platforms can be found in Appendix I).
... less
This chapter discusses the basics of PHP and starts you on your way to creating your first complete web site. The site will... more
This chapter discusses the basics of PHP and starts you on your way to creating your first complete web site. The site will feature movie reviews, and your visitors will be able to find information about a particular movie after you complete your web site. Perhaps more importantly, you will be well on your way to being able to program in PHP.
This chapter covers the following basic PHP commands and structures:
Using echo to display text
echo
Constants and variables
Using a URL to pass variable values
Sessions and cookies
HTML forms
if/else statements
if
else
Includes
Functions
Arrays and foreach
foreach
while and do/while
while
do
Using classes and methods with object-oriented programming (OOP)
By the end of this chapter, if you actually try all the “Try It Out” exercises, you will have created a simple login form, given your users the option to either see a review of your favorite movie or see a list of your top favorite movies, and offered them a numbered list of the movies based on how many they want to see. You can even alphabetize the list for them, if you so desire.
So now that you’ve done some really cool stuff with PHP in Chapter 2, such as using includes and functions, it’s time to... more
So now that you’ve done some really cool stuff with PHP in Chapter 2, such as using includes and functions, it’s time to make your web site truly dynamic and show users some real data. You may or may not have had experience with using or configuring databases before, so we’ll take a look at what MySQL is and how PHP can tap into it. We will also show you what a MySQL database looks like in terms of the different tables and fields, and give you some quickie shortcuts to make your life much easier. (You can thank us later for those.)
By the end of this chapter, you will be able to:
Understand what a MySQL database is
View data contained in the MySQL database
Connect to the database from your web site
Pull specific information out of the database, right from your web site
Use third-party software to easily manage tables
Use the source web site to troubleshoot problems you may encounter
Although some of this information is expanded upon in later chapters, this chapter lays the groundwork for the more complex issues.
Now that you can successfully marry PHP and MySQL to produce dynamic pages, what happens when you have rows and rows of data... more
Now that you can successfully marry PHP and MySQL to produce dynamic pages, what happens when you have rows and rows of data that you need to display? You need to have some mechanism for your viewers to easily read the data, and it needs to be presented in a nice, neat, organized fashion. The easiest way to do this is to use tables.
This chapter covers the following:
Creating a table to hold the data from the database
Creating column headings automatically
Populating the table with the results of a basic MySQL query
Populating the table with the results of more complex MySQL queries
Making the output user-friendly
An interactive web site requires user input, which is generally gathered through forms. As in the paper-based world, the... more
An interactive web site requires user input, which is generally gathered through forms. As in the paper-based world, the user fills in a form and submits its content for processing. In a web application, the processing isn’t performed by a sentient being; rather, it is performed by a PHP script. Thus, the script requires some sort of coded intelligence.
When you fill in a paper form, you generally use a means to deliver its content (the postal service is one example) to a known address (such as a mail-order bookstore). The same logic applies to online forms. The data from an HTML form is sent to a specific location and processed.
The form element is rather simple in HTML. It states where and how it will send the contents of the elements it contains once submitted. It is after that point that PHP comes into play. PHP uses a set of simple yet powerful expressions that, when combined, provide you with the means to do virtually anything you want. The PHP script receives the data from the form and uses it to perform an action such as updating the contents of a database, sending an e-mail, testing the data format, and so on.
In this chapter, you begin to build a simple application that allows you to add, edit, or delete members of a data set (in this instance, the data will be movies, actors, and directors). This chapter welcomes you into a world of PHP/MySQL interaction by covering the following:
Creating forms using buttons, text boxes, and other form elements
Creating PHP scripts to process HTML forms
Passing hidden information to the form-processing script via hidden form controls and a URL query string
Retrieving data from a database is all well and good when you’ve first fed the database some data. But databases don’t generate... more
Retrieving data from a database is all well and good when you’ve first fed the database some data. But databases don’t generate their own content, and only a few get fed data by other systems, such as integrated systems. What this means is that you have to feed your system with data that comes from PHP. For our purposes here, and from what you’ve seen in previous chapters, all interaction with the database uses SQL. You already know the basic SQL syntax to put your own data in a table and retrieve it for users to see. But now, let’s look at the other side of the equationdata processing.
This chapter covers database editing, including:
Adding entries, which is quite simplebut you will find that adding entries in a relational database is yet another exercise
Deleting entries without corrupting the database structure and referential integrity
Modifying entries to replace some existing fields with new content in an existing record
Now that you’ve been rocking and rolling with manipulating and displaying data using PHP, why stop there? Did you know that... more
Now that you’ve been rocking and rolling with manipulating and displaying data using PHP, why stop there? Did you know that PHP can also manipulate and create images on the fly? It can, with a little help from the GD library. GD loosely stands for “Graphics Draw,” but the industry generally refers to it in short as the GD library.
Enabling your PHP setup to use the GD library
Allowing your users to upload their own images
Retrieving information about an image, such as size or file type
Creating a new image
Copying an image or a portion of an image
Creating thumbnails (smaller versions of images)
Creating black-and-white versions of images
Adding watermarks and captions to images
If you plan to accept user input on your site, you have to be prepared for mistakes. Incorrect input could be simple human... more
If you plan to accept user input on your site, you have to be prepared for mistakes. Incorrect input could be simple human error or a deliberate attempt to circumvent the purpose (or security) of your web application. The most common human errors include basic typographical errors and format errorssuch as showing a year as two digits when a full four-digit year was requested or needed. Erroneous input sent deliberately could be from a user who doesn’t want to provide his or her e-mail address, or from an attacker intentionally trying to corrupt your database with polluted values. No matter what the source, your script needs to be able to handle incorrect input. There are many ways to do so, but perhaps the most popular is to identify the bad data and return the user to the form with an appropriate error message. This chapter covers user input validation, including:
Validating simple string values
Validating integer values
Validating formatted text input
You will probably be spending a fair amount of time contemplating errors in your code, as do most web developers. No matter... more
You will probably be spending a fair amount of time contemplating errors in your code, as do most web developers. No matter how good you are, how well you code, how long you have been coding, or how hard you try, you will encounter times when you have errors in your code.
It is of the utmost importance that you know how to handle your errors and debug your own code. Being able to efficiently and properly debug your code is an invaluable time saver, and in web development, $time == $money!
Luckily, PHP provides you with many ways to isolate and resolve most, if not all, of these unwanted errors. PHP also allows you to capture the errors and create your own custom error functions or pages. These features are useful when debugging your code and when notifying your webmaster about errors that seem to be happening to your applications as users are running them. Not only can you use PHP code to trap errors and customize the error messages, you can use the Apache web server to help do this.
You created a very nice movie review site by following along with the previous chapters, but now the handholding is over,... more
You created a very nice movie review site by following along with the previous chapters, but now the handholding is over, my friend. It’s time for us to push you out of the nest and let you begin to fly on your own. So, in this chapter, you will have the opportunity to create your own databases and your own web site.
We show you how to put together a comic book appreciation web site, but you can take the concepts we teach you and branch off to create that online auction or antique car site you have always dreamed about doing.
This chapter covers the basics of creating your own database. The topics discussed here include:
Planning the design of your database
Database normalization
Creating your database
Creating and modifying tables in your database
Building web pages to access your data with PHP
So far, the chapters in this book have walked you through the creation of a comprehensive web site. You have designed your... more
So far, the chapters in this book have walked you through the creation of a comprehensive web site. You have designed your site so that users can add and modify data that is stored in databases. You have built dynamic pages for your users, ensuring that they have a rich and unique experience when they visit your web site. You are even displaying helpful error messages in case something goes wrong. But now it’s time to get a little more interactive with your users, with e-mail. We are not talking about standard e-mailwe’re talking about sending out e-mails using PHP.
Why would you want a server-side scripting language to send out e-mails? Perhaps you want to create a feedback form used for submitting information to an administrator’s e-mail address, as introduced in Chapter 9. Maybe you want certain errors to be automatically e-mailed to the webmaster. Perhaps you would like to create an application that allows users to send their friends and family electronic postcards. (Nod your head in vigorous agreement to the latter, here, because that is exactly what you are going to do!)
Specifically, this chapter covers:
Sending a basic e-mail
Sending an HTML-formatted e-mail
Using multipart messages
Sending images
Receiving confirmation
In this chapter, you’ll learn how to implement user logins and profiles and how to personalize your web pages using PHP’s... more
In this chapter, you’ll learn how to implement user logins and profiles and how to personalize your web pages using PHP’s session and cookie functions. You will create a useful login and personalization application that can easily be integrated into other applications you’ve created in this book thus far.
With Apache’s support for additional per-directory configuration files and PHP’s support for sessions, you can prevent hackers and the general public from stumbling onto your sensitive files. Session and cookie functions are probably two of the most important and useful functions you will encounter in the entire PHP programming language, because of the ability they give you to identify an individual viewing a page and restrict or grant access to certain content. You wouldn’t want just anyone nosing about in your important files, and you certainly wouldn’t want a malicious visitor changing information displayed on your web site in any way he or she desired.
Specifically, you learn how to do the following in this chapter:
Restrict access to files and directories via htpasswd
htpasswd
Use PHP to accomplish the same functionality as with htpasswd, but with more control and flexibility
Store user and admin information in a database and utilize database-driven logins
Create a registration system with required and optional fields for users to sign up
Use cookies to preserve login information between sessions
Modify a navigation system depending on whether a user has logged in or not
For whatever reason, people seem to get bored easily. One of your jobs as the administrator of a web site is not only to... more
For whatever reason, people seem to get bored easily. One of your jobs as the administrator of a web site is not only to figure out how to get as many people to visit your site as possible, but to keep them coming back.
There are many different avenues for people to learn about your site, such as word of mouth, advertising, and search engines. To keep your users at your site, experts suggest making your site easy to navigate, making sure your pages load quickly, and giving users a personal experience. Getting your users to keep coming back as new ones learn about your site is how you grow your web site over time.
Ah, yes . . . mailing lists. Two small and innocent words that never meant anyone harm. That is, until someone decided to... more
Ah, yes . . . mailing lists. Two small and innocent words that never meant anyone harm. That is, until someone decided to put the two together, and junk mail was born. But mailing lists are used for more than just junk mail or spam. After all, how are you going to receive your Quilting Monthly newsletter unless your name and address are on a mailing list?
In a world of e-mail communication, a mailing list is the perfect way for you to communicate with all of your users about your new web site. Maybe you want to send out a monthly newsletter or just send out important announcements. Whatever the reason, you will occasionally need to send e-mails to many people, and you will need a relatively easy way to do so when that time comes. Do not fret, because we plan on helping you with just that in this chapter.
Specifically, this chapter discusses the following:
Creating a mailing list
Administering a mailing list
Spam
Opt-in and opt-out
Some of us cringe when we hear the word “e-commerce” and the phrase “selling over the Internet.” Perhaps we’ve had a bad... more
Some of us cringe when we hear the word “e-commerce” and the phrase “selling over the Internet.” Perhaps we’ve had a bad experience ourselves, or the thought of opening an online store is just too overwhelming. Even though this is the part of the book that all geeks out there probably dread reading, we’re here to show you that e-commerce is nothing to fear and that pretty much anyone can do it.
However, the fact that anyone can do it doesn’t mean it’s always done the right way. Done the wrong way, your site can look downright cheesy. Done the right way, your site can look professional and inviting and become an excellent resource for your visitors and potential customers. There are definite guidelines for selling things over the web, and we want to make sure you do things the right way.
Selling things from your web site can not only put some extra cash in your pocket, but it can enhance your relationship with your web site visitors as well, even if e-commerce is not your site’s primary function. In the case of your comic book fan site, offering pertinent items can make your site more interactive and interesting. It can bring in new visitors who may not have known about your site before, and keep visitors coming back to see what new items you have for sale. True comic book fans will appreciate the niche of items you are providing, especially if some of the items are unique or hard to come by.
This chapter discusses the following:
Creating a simple shopping-cart script
Ideas to improve your script
The basics of e-commerce
People are social beings and don’t like to be isolated. Throughout our brief history as civilized human beings, we have consistently... more
People are social beings and don’t like to be isolated. Throughout our brief history as civilized human beings, we have consistently tried to maintain some sort of connection to others, whether it be the family unit, clans, chess clubs, or AA meetings. With the advent of the computer, many geeks found themselves shut in a room for long periods of time, becoming the modern equivalent of the social outcast. (How many of us have joked about not knowing what the sun looks like?) The development of the electronic bulletin board made it possible for computer geeks to communicate and once again take part in the social aspect of humanitywithout ever having to look at each other’s faces.
The bulletin board system, or BBS for short, is an electronic meeting area, also referred to as a forum. A traditional forum is a gathering place where people can meet and discuss different topics, and that is a very apt definition for a BBS. However, we want to expand upon it a little further, for use in the computer world. By our definition (and the way we’ll use it in this chapter), a forum is a way to talk to other people with a common interest. A bulletin board is the location in which the forum exists, and a bulletin board may house multiple forums. You might visit a book-based BBS to find different forums for science fiction, nonfiction, authors, and more.
The cool thing about being a web developer is that sometimes you get to act like Big Brother and keep close watch on what... more
The cool thing about being a web developer is that sometimes you get to act like Big Brother and keep close watch on what your visitors are doing. Although it may seem voyeuristic to some, analyzing what goes on at your site can give you valuable information that will enable you to make your site better. To perform this analysis, you have to first gather the data necessary for the analysis, and to do that you need a log.
A log is a simply a text file saved on your server. It is updated by a logging application on the server every time something happens, such as when a particular file is requested by someone or when an error occurs. When the event happens, a line of text is appended to the end of the file, essentially “logging in” the activity. Here are three basic types of logs:
Access Logs track every hit on your web server.
Error Logs track every error or warning.
Custom Logs track whatever information you tell them to.
Some examples of the types of information you can glean from logs include:
What IP addresses your visitors are using so you can get a geographical location for your most common visitors; this may help with geographical demographic research.
What browsers your visitors are using, either just for your own curiosity or so you can make sure you don’t implement any special browser-specific rendering features on your site that only a small portion of your viewership would be able to take advantage of
What times and days your visitors are visiting, so you can schedule maintenance during slow times or special promotional events during busier times
What pages are the most popular on your site, so you can gauge the success or failure of certain pages and prune your web site of any dead weight
Whether the volume of your traffic is increasing, so you can determine if your site is either becoming more well known or stagnating itself into oblivion
If you’re using user authentication on your site, what users are logging in when, and what their activity is, so you can see who your MVPs are and perhaps offer them special web site features (or maybe a beer at the local bar)
As you may have guessed, this chapter is all about logs. It will cover the following:
What logs look like and what information they contain
Where you can find them on your system
What resources exist that you can use to help analyze the data
How you can use the information to improve your site
Nothing is more frustrating than thinking you have all your t’s crossed and your i’s dotted only to have your program produce... more
Nothing is more frustrating than thinking you have all your t’s crossed and your i’s dotted only to have your program produce completely perplexing and unwanted results and blow up on you with a string of errors that you do not understand.
You may find comfort in knowing that many developers experience the same types of obstacles. With this chapter, we hope to shed light on some problems you may encounter and suggest a few troubleshooting strategies.
This appendix supplies answers to the exercises you were given at the end of most of the chapters you read. Keep in mind... more
This appendix supplies answers to the exercises you were given at the end of most of the chapters you read. Keep in mind that, as is always the case in programming, there is more than one way to solve a problem, and these are just recommendations. If you were able to accomplish the given task some other way, then congratulate yourself (and why not even treat yourself to a movie?). You’re well on your way to becoming a truly diverse programmer!
This appendix lists some quick PHP reference notes for your use. Consider the information in this appendix to be your “cheat... more
This appendix lists some quick PHP reference notes for your use. Consider the information in this appendix to be your “cheat sheet” to the topics covered throughout this book. For complete information on PHP’s syntax, see www.php.net/manual/en/langref.php.
www.php.net/manual/en/langref.php
For your convenience, we have listed many (but not all) of PHP’s functions in this appendix to serve as a quick reference... more
For your convenience, we have listed many (but not all) of PHP’s functions in this appendix to serve as a quick reference. PHP has numerous other functions available to you, and you can find a complete listing in the manual at its web site, www.php.net/manual/en/funcref.php. Each table presented here lists the function’s signature in a format similar to that used in the official PHP documentation and a brief description of what the function does. Functions that are deprecated and should no longer be used are not listed here.
Please note that some functions are designed to work only on Linux, and some only on Windows. If you encounter otherwise unexplained errors in your code, we recommend checking the function’s documentation to ensure that it is available and fully compatible with your platform.
This appendix contains a listing of data types that are available in MySQL. Visit http://dev.mysql.com/doc/refman/5.1/en/data-type-overview... more
This appendix contains a listing of data types that are available in MySQL. Visit http://dev.mysql.com/doc/refman/5.1/en/data-type-overview.html for a complete discussion on each data type.
This appendix lists some quick reference notes for your use. These topics are covered in more depth in Chapter 3 and on the... more
This appendix lists some quick reference notes for your use. These topics are covered in more depth in Chapter 3 and on the MySQL web site at www.mysql.com.
Many software programs are available that you can use to enter all your code. They each have different features, some that... more
Many software programs are available that you can use to enter all your code. They each have different features, some that you might view as better than others, depending on your needs and personal preferences. We’ve put together the following chart to help you compare apples with apples. It lists some of the more popular editors alphabetically and compares them against some common text editor features.
Many people like to run their own servers out of their homes or offices, and that is a feasible solution for hosting, if... more
Many people like to run their own servers out of their homes or offices, and that is a feasible solution for hosting, if you have the time and network resources. But sometimes hosting your own web site can lead to more problems than it’s worth. You need to think about backup power, keeping security holes patched, performing regular maintenance and upgrades, and many other issues. And keep in mind that not only do you need to have a web server running, but you also need to have something to manage your domain records as well, a Domain Name System (DNS) server.
With third-party hosting solutions, you can have trained IT professionals who make sure your web server stays up and running 24 hours a day, at an affordable price. It’s their job to make sure your site is secure and always available for viewing.
PHP is a terrific programming language. It is relatively easy to learn, especially if you are already familiar with other... more
PHP is a terrific programming language. It is relatively easy to learn, especially if you are already familiar with other programming languages. You can build some excellent interactive web pages that access databases, authenticate users, and provide dynamic, up-to-date content for your visitors in no time at all.
So, let’s say you just finished creating your company’s web site. It’s perfectusers are being served up-to-the-minute content, and you have set up a complex content management system (CMS) that enables designated employees in the company to create new content. It’s efficient, it’s pretty, and you feel pretty darned good about it.
As you sit here thumbing through these final pages of the book and wondering what final nuggets of useful information we can share with you, we present you with a scenario: You have just finished a tough assignment assigned to you by your IT manager. She congratulates you on a job well done and engages you in general chit-chatyou know, the usual. As she gets up to leave, she stops in the doorway and casually mentions something that is about to completely overload your work schedule. . . .
“Oh, by the way, the accounting department is switching to an Ingres database to support their accounting software. It’s pretty slick. And since we’ll be using Ingres in accounting, we’ve decided all of our databases should be standardized on Ingres throughout the rest of the company, for conformance. That’s not going to be a problem, is it?”
Every developer has had something like this happen at one point or another, so you are not alone. One of the wonderful things about PHP is that it supports a very wide variety of different databases:
dBase
DB++
FrontBase
filePro
Firebird/InterBase
Informix
IBM DB2 (IBM DB2, Cloudscape, and Apache Derby)
Ingres Database (Ingres II)
MaxDB
mSQL
Microsoft SQL Server
MySQL
Oracle OCI8
Ovrimos SQL
Paradox File Access
PostgreSQL
SQLite
Sybase
That’s quite an impressive list, isn’t it? And there’s a pretty good chance that if a new database were to come around, then someone would write functions that would enable PHP to work with it. Database integration has always been one of PHP’s strong points.
However, the first point of contention here is that each database extension offers a different set of functions. mysql_query() is used to execute a database query against MySQL, but it cannot execute a query against Ingres II. When you change your back-end database solution, you must also update your code to use the appropriate functions.
The second point of contention is that most, but not all, of the extensions for the databases listed earlier follow the same general naming conventions for their functions. You would use the ingres_query() function to execute a query against Ingres II, but Oracle, for example, doesn’t even have a _query() function. You have to use ora_parse() on the SQL statement and then run ora_exec().
You must also consider that there may be some specific functions you are using in MySQL that have no equivalent function in your new database. Perhaps you are even using very specific SQL statements in MySQL that are not supported in other databases, or are executed in a different way. Flexibility and complexity often come along as a pair.
Wouldn’t it be cool if there were a way to write your code more abstractly, so that when you run a function such as get_query_results(), it would be smart enough to know what type of database you are connecting to and perform all of the necessary steps to retrieve the data? That’s what the PHP Data Objects (PDO) extension attempts to doprovide a seamless experience when using PHP to communicate across different databases. PDO provides a data-abstraction layer so that you can use the same set of functions to work with a database, regardless of what database back end your company is using.
That’s great! So why didn’t we share this with you sooner? The sad fact is that some hosting providers may not make PDO available to their customers. And while we strongly urge you to use the latest version of PHP for increased stability, security, and speed, many hosting companies still use older versions of PHP to support legacy applications. You will be trapped into using what is offered to you, unless you are hosting your own server.
It was only after much deliberation and discussion that we chose to continue showing you the mysql_* functions in this edition. PDO is the latest and the greatest, but mysql_* is the lowest common denominator, and we wanted to make this book relevant for the largest audience possible. We encourage you to learn both ways, to increase your knowledge of PHP, so that you can apply either solution depending on your needs. We also chose to present PDO to you towards the end of the book, after you’ve had some experience with objected-oriented programming, because PDO uses OOP syntax. So, let’s take a good look at PDO requirements and get started using it.
In Chapter 1, you learned how to install and configure Apache, MySQL, and PHP on a Windows-based system, but the trio can... more
In Chapter 1, you learned how to install and configure Apache, MySQL, and PHP on a Windows-based system, but the trio can run on other platforms as well! In fact, it is very popular to run AMP on Linux (many people add an L to AMP when running the applications on Linux, for the moniker LAMP). We felt it was just as important to provide you with installation instructions under Linux as well, but putting them in Chapter 1 would have been overwhelming, so we decided to present them separately in this appendix.
Purchase Before purchasing this product, please be sure you have met all software and system requirements, and that you understand any limits placed upon its use.
Return Policy Wrox Chapters on Demand are non-returnable and non-refundable.
Reader Software Wrox Chapters on Demand are offered as PDFs, and they must be viewed using the Adobe Reader. If you do not have the Reader installed, it can be downloaded for free at Adobe.com.
Test Download As Wrox Chapters on Demand purchases are non-returnable, it is advisable that you test your system and software configurations with a free sample download before you place an order.
Usage Rights for a Wrox Chapter on Demand File Any Wrox Chapter on Demand product you purchase from this site will come with certain restrictions that allow Wiley to protect the copyrights of its products. After you purchase and download this title, you:
If you have any questions about these restrictions, you may contact Customer Care at (877) 762-2974 (8 a.m. - 5 p.m. EST, Monday - Friday). If you have any issues related to Technical Support, please contact us at 800-762-2974 (United States only) or 317-572-3994 (International) 8 a.m. - 8 p.m. EST, Monday - Friday).