BUY THIS BOOK
Add to Cart

PDF $20.99

Safari Books Online

What is this?

Looking to Reprint or License this content?


Learning PHP and MySQL
Learning PHP and MySQL By Michele E. Davis, Jon A. Phillips
June 2006
Pages: 376

Cover | Table of Contents


Table of Contents

Chapter 1: Dynamic Content and the Web
There are two types of web pages: static and dynamic. A static site provides hyperlinked text and perhaps a login screen, but beyond that, it doesn't require additional participation from the user. http://www.startribune.com is an example of a static site, except that you do have to register to view articles. http://www.amazon.com is an example of a dynamic web site, because your ordering data is logged, and Amazon offers recommendations based on your purchasing history when you access their page. In other words, dynamic means that the user interacts more with the web site, beyond just reading pages, and the web site responds accordingly.
Creating dynamic web pages—even a few years ago—meant writing a lot of code in the C or Perl languages, and then calling and executing those programs through a process called a Common Gateway Interface (CGI). Having to create executable files doesn't sound like much fun, and neither does learning a whole new complicated language. Well, thankfully, PHP and MySQL make creating dynamic web sites simpler, easier, and faster.
PHP is a programming language designed to generate web pages interactively on the computer serving them, called a web server . Unlike HTML, where the web browser uses tags and markup to generate a page, PHP code runs between the requested page and the web server, adding to and changing the basic HTML output. For example, PHP code could be used to display a counter of visitors to a site.
PHP, in less than 20 lines of code, can store the IP address from which a page request comes in a separate file, and then display the number of unique IP addresses that visited a particular site. The person requesting the web page doesn't know that PHP generated the page, because the counter text is part of the standard HTML markup language that the PHP code generated.
PHP makes web development easy, because all the code you need is contained within the PHP framework. This means that there's no reason for you to reinvent the wheel each time you sit down to develop a PHP program; that would be something you'd have to do if you were using a compiled language like C.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
PHP and MySQL's Place in Web Development
PHP is a programming language designed to generate web pages interactively on the computer serving them, called a web server . Unlike HTML, where the web browser uses tags and markup to generate a page, PHP code runs between the requested page and the web server, adding to and changing the basic HTML output. For example, PHP code could be used to display a counter of visitors to a site.
PHP, in less than 20 lines of code, can store the IP address from which a page request comes in a separate file, and then display the number of unique IP addresses that visited a particular site. The person requesting the web page doesn't know that PHP generated the page, because the counter text is part of the standard HTML markup language that the PHP code generated.
PHP makes web development easy, because all the code you need is contained within the PHP framework. This means that there's no reason for you to reinvent the wheel each time you sit down to develop a PHP program; that would be something you'd have to do if you were using a compiled language like C.
While PHP is great for developing web functionality, it is not a database. The database of choice for PHP developers is MySQL, which acts like a filing clerk for PHP-processed user information. MySQL automates the most common tasks related to storing and retrieving specific user information based on your supplied criteria.
Take our Amazon example; the recommendations Amazon offers you can be stored in a MySQL database, along with your prior order information.
MySQL is easily accessed from PHP, and they're commonly used together as they work well hand in hand. An added benefit is that PHP and MySQL run on various computer types and operating systems, including Mac OS X, Windows-based PCs, and Linux.
There are several factors that make using PHP and MySQL together a natural choice:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Components of a PHP Application
In order to process and develop dynamic web pages, you'll need to use and understand several technologies. There are three main components to creating dynamic web pages: a web server, a server-side programming language, and a database. It's a good idea to have an understanding of the three basic components for web development using PHP. Start with some rudimentary understanding of the history and purpose of Apache (your web server), PHP (your server-side programming language), and MySQL (your database). This can help you understand how they fit into the web development picture.
Remember that dynamic web pages pull information from several sources simultaneously, including Apache, PHP, MySQL, and Cascading Style Sheets (CSS), which we'll talk about later.
PHP grew out of a need for people to develop and maintain web sites containing dynamic client-server functionality. In 1994, Rasmus Lerdorf created a collection of open source Perl scripts for his personal use, and these eventually were rewritten in C and turned into what PHP is today. By 1998, PHP was released in its third version, turning it into a web development tool that could compete with similar products such as Microsoft's Active Server Pages (ASP) or Sun's Java Server Pages (JSP).
The real beauty of PHP is its simplicity coupled with its power, as well as it being an interpreted language, rather than a compiled one.
Compiled languages create a binary .exe file, while interpreted languages work directly with the source code when executing as opposed to creating a standalone file.
PHP is ubiquitous and compatible with all major operating systems. It is also easy to learn, making it an ideal tool for web-programming beginners. Additionally, you get to take advantage of a community's effort to make web development easier for everyone. The creators of PHP developed an infrastructure that allows experienced C programmers to extend PHP's abilities. As a result, PHP now integrates with advanced technologies like XML, XSL, and Microsoft's COM. At this juncture, PHP 5.0 is being used.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Integrating Many Sources of Information
In the early days of the Web, life was simple. There were files that contained HTML and binary files such as images. Several technologies have since been developed to organize the look of web pages. For example, Cascading Style Sheets (CSS) pull presentation information out of your HTML and into a single spot so that you can make formatting changes across an entire set of pages all at once; you don't have to manually change your HTML markup one HTML page at a time.
You can potentially have information coming from HTML files that reference CSS, PHP templates, and a MySQL database all at once. PHP templates make it easier to change the HTML in a page when it contains fields populated by a database query. We'll briefly discuss each of these information sources.
MySQL is a relational database management system that stores data in separate tables rather than putting all the data in one spot. This adds flexibility, as well as speed. The SQL part of MySQL stands for Structured Query Language, which is the most common language used to access every type of database in existence. Just to give you a taste of what your code will look like, Example 1-1 is an example of MySQL code called from PHP for deleting a user from the MySQL database.
Example 1-1. A PHP function to delete a user from the user_name database table
<?php

// A function to delete a user from the site_user table based on
//the $user_name parameter.
// An open database connection is assumed

function remove_user($user_name){
    // Remove a User
    // This is the SQL command
    $sql_delete = "DELETE FROM `site_user` WHERE `User`='$user'";
    $success = mysql_query($sql_delete) or die(mysql_error());

    // print the page header
    print('
        <html>
            <head>
                <title>Remove User</title>
                <link rel="stylesheet" type="text/css" href="user_admin.css" />
            </head>
            <body>
                <div class="user_admin">');

    // Check to see if the deletion was sucessful
    if ($success){
        // Tell the user it was sucessful
        print("The account for $user_name was deleted successfully.");
    }
    else {
        // Tell the user it was not sucessful
        print("User $user could not be deleted. Please try again later.");
    }

    // Print the page footer
    print('</div></body></html>');
}

?>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Requesting Data from a Web Page
How all of these pieces integrate together can be tricky to understand. If a web server detects PHP code, it determines whether the file is a PHP file, and if so, turn over the processing of the page to the PHP interpreter without any additional participation by the web browser. But if you include an external CSS file, your browser issues a separate request for that file before viewing the page.
This processing of the PHP on the server is called server-side processing. When you request a web page, you trigger a whole chain of events. Figure 1-2 illustrates this interaction between your computer and the web server (host of the web site).
Figure 1-2: While the user only types in a URL and hits Enter, there are several steps that occur behind the scenes to handle that request
Here's the breakdown of Figure 1-2:
  1. You enter a web page address in your browser's location bar.
  2. Your browser breaks apart that address and sends the name of the page to the web server. For example, http://www.phone.com/directory.html would request the page directory.html from www.phone.com.
  3. A program on the web server, called the web server process, takes the request for directory.html and looks for this specific file.
  4. The web server reads the directory.html file from the web server's hard drive.
  5. The web server returns the contents of directory.html to your browser.
  6. Your web browser uses the HTML markup that was returned from the web server to build the rendition of the web page on your computer screen.
The HTML file called directory.html (requested in Figure 1-2) is called a
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 1 Questions
Question 1-1.
What three components do you need to create a dynamic web page?
Question 1-2.
What does Apache use to load extensions?
Question 1-3.
What is the current stable release of PHP?
Question 1-4.
What does the SQL part of MySQL stand for?
Question 1-5.
What are angle brackets (< >) used for?
Question 1-6.
What does the PHP Interpreter do?
See the Appendix for the answers to these questions.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Installation
Developers working with PHP and MySQL often find it convenient to work on a local computer rather than a web server. In general, it is also safer to create and test your applications on a local—preferably private—computer and then deploy them to a public server where others can enjoy your work. Typically, you need to install Apache, PHP, and MySQL on the local computer, while your ISP handles installation on the public server.
Developing your construct on your local computer is the recommended way to learn, since you can interact with all of the components on your own machine and not risk causing problems on a production server. That way, if there are problems in the local environment, you can fix them immediately without exposing them to your site's visitors. Working with your files locally means that you don't have to FTP them to a server, you don't have to be connected to the Internet, and you know exactly what's installed since you did it yourself.
There are three components to install:
  • Apache
  • PHP
  • MySQL
You will install the programs in that order. All our examples will be from the installation perspective of a PC with Windows installed, with notes for the Macintosh.
First, Apache needs to be installed and operational before PHP and MySQL can be installed, or else they won't work correctly. Plus, there wouldn't be any use for the coding application and database without the Apache web server. A web server delivers web pages, has an IP address, and might have a domain name. For example, if you enter http://www.oreilly.com/ in your browser, this sends a request to the server whose domain name is oreilly.com. The server fetches the page named index.html and sends it to your browser.
Any computer can be turned into a web server by installing server software and connecting the machine to the Internet, which is why you need to install Apache.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing Locally
Developing your construct on your local computer is the recommended way to learn, since you can interact with all of the components on your own machine and not risk causing problems on a production server. That way, if there are problems in the local environment, you can fix them immediately without exposing them to your site's visitors. Working with your files locally means that you don't have to FTP them to a server, you don't have to be connected to the Internet, and you know exactly what's installed since you did it yourself.
There are three components to install:
  • Apache
  • PHP
  • MySQL
You will install the programs in that order. All our examples will be from the installation perspective of a PC with Windows installed, with notes for the Macintosh.
First, Apache needs to be installed and operational before PHP and MySQL can be installed, or else they won't work correctly. Plus, there wouldn't be any use for the coding application and database without the Apache web server. A web server delivers web pages, has an IP address, and might have a domain name. For example, if you enter http://www.oreilly.com/ in your browser, this sends a request to the server whose domain name is oreilly.com. The server fetches the page named index.html and sends it to your browser.
Any computer can be turned into a web server by installing server software and connecting the machine to the Internet, which is why you need to install Apache.
  1. Download the Apache 2.0.5 Win32 binary. It's downloadable from http://httpd.apache.or/download.cgi. The file that you save to your desktop is called apache2_0.55-win32-x86-no_ssl.msi.
    If you are on Mac OS X, you already have Apache installed. Open up System Preferences, select the Sharing panel, and click to activate Personal Web Sharing (which is actually Apache). Mac OS X 10.2, 10.3, and 10.4 all come with different versions of Apache, but each works perfectly fine.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Working Remotely
Although we recommend you start out working locally, you can use an ISP account as long as it supports PHP and MySQL.
You need login information to the remote server, and you may need to use your ISP's web-based tool to create your database.
To transfer your files and directories, you need to activate a File Transfer Protocol (FTP) account at your ISP, usually through your account control panel. Once you have an FTP login, you upload your HTML and PHP files using a FTP client.
While your computer likely has the command-line version of the FTP client available from the command prompt, it can be cryptic to use. Graphical FTP clients make using FTP much easier. FTP Voyager, available from http://sourceforge.net/projects/filezilla/, is one FTP client you can use to upload files to your ISP. Your initial login screen looks similar to Figure 2-25. Fetch is a good FTP program for the Macintosh.
Figure 2-25: FTP Voyager initial screen
After connecting, you see a dialog similar to Figure 2-26, but you do not see the identical screen as this FTP Voyager screen. You can drag and drop the .php file you created. Remember, for your PHP file to run you need to save it with an extension of .php instead of .html; otherwise, it won't run, because the web server needs to know it's a PHP file in order to run the PHP interpreter.
Figure 2-26: FTP Voyager directory listing
PHP files must be accessed through a web server since your web browser doesn't have the ability to interpret the PHP code. A PHP interpreter is used to process the PHP files.
You're ready to start learning all about basic facts, integration, and how to get your dynamic web page up and running as quickly and smoothly as possible. In the next chapter, we'll give you basic information about PHP and simple coding principles that apply to using PHP.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2 Questions
Question 2-1.
What three components must be installed to create a dynamic web site?
Question 2-2.
What OS has Apache installed already?
Question 2-3.
Where should you create a PHP directory for downloads?
Question 2-4.
What does the hash (#) sign mean?
Question 2-5.
How do you work remotely?
Question 2-6.
How do you transfer files to your ISP?
Question 2-7.
How must PHP files be accessed?
See the Appendix for the answers to these questions.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Exploring PHP
With PHP, MySQL, and Apache installed, you're ready to begin writing code. Unlike many languages, PHP doesn't require complex tools such as compilers and debuggers. In fact, you'll soon see that you can enter PHP directly into your existing HTML documents, and with just a few tweaks, you'll be off and running.
In this chapter, we'll start by showing you how PHP handles simple text, and then move on to basic decision making. Some really cool things you can do include showing an image based on the current user's browser, or perhaps printing a warning message if the user is browsing from an operating system that makes your web site look crummy. All this and more is possible with PHP, which makes these tricks easy and simple.
It's simple to output text using PHP; in fact, handling text is one of PHP's specialties. We'll begin with detailing where PHP is processed, some of the basic functions to output text, and from there go right into printing text based on a certain condition being true.
You'll want to be able to spit out text easily and often. PHP will let you do that, though you'll need to use proper PHP syntax when creating the code. Otherwise, your browser assumes that everything is HTML and outputs the PHP code directly to the browser, and then everything looks like text and code mixed up. This will certainly confuse your users! You can use whatever text editor you like to write your PHP code, including Notepad or DevPHP (http://sourceforge.net/projects/devphp/).
Our examples will demonstrate how similar HTML markup and PHP code look and what you can do to start noticing the differences between them.
Example 3-1 is a simple HTML file that we'll use for an example.
Example 3-1. All you need to start with PHP is a simple HTML document
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <p>I sure wish I had something to say.</p>
    </body>
</html>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
PHP and HTML Text
It's simple to output text using PHP; in fact, handling text is one of PHP's specialties. We'll begin with detailing where PHP is processed, some of the basic functions to output text, and from there go right into printing text based on a certain condition being true.
You'll want to be able to spit out text easily and often. PHP will let you do that, though you'll need to use proper PHP syntax when creating the code. Otherwise, your browser assumes that everything is HTML and outputs the PHP code directly to the browser, and then everything looks like text and code mixed up. This will certainly confuse your users! You can use whatever text editor you like to write your PHP code, including Notepad or DevPHP (http://sourceforge.net/projects/devphp/).
Our examples will demonstrate how similar HTML markup and PHP code look and what you can do to start noticing the differences between them.
Example 3-1 is a simple HTML file that we'll use for an example.
Example 3-1. All you need to start with PHP is a simple HTML document
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        <p>I sure wish I had something to say.</p>
    </body>
</html>
Nothing is special here; just your plain vanilla HTML file. However, you can enter PHP right into this file; for example, let's use PHP's echo command to output some text in Example 3-2.
Example 3-2. Adding some PHP code to the HTML file
<html>
    <head>
        <title>Hello World</title>
    </head>
    <body>
        echo("<p>Now I have something to say.</p>");
    </body>
</html>

Section 3.1.1.1: Separating PHP from HTML

This looks pretty simple, but there are some problems. There's no way to tell in this file which part is standard HTML and which part is PHP and therefore must be handled differently. To fix this, surround your PHP code in
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Coding Building Blocks
To write programs in PHP that do something useful, you'll need to understand blocks of reusable code called functions or methods, and then how to temporarily store information that cannot be executed in variables. We talk about evaluations, which are basically things that allow your code to make intelligent decisions based on mathematical principles and user input.
Since you haven't done any programming, we understand that variables are a new concept. A variable stores a value, such as the text string "Hello World!" or the integer value 1. A variable can then be reused throughout your code, instead of having to type out the actual value over and over again for the entire life of the variable, which can be frustrating and tedious. Figure 3-2 shows a newly created variable that has been assigned a value of 30.
Figure 3-2: A variable holding a value
In PHP, you define a variable with the following form:
$variable_name = value;
Pay very close attention to some key elements in the form of variables. The dollar sign ($) must always fill the first space of your variable. The first character after the dollar sign must be a letter or underscore. It can't under any circumstances be a number; otherwise, your code will not execute, so watch those typos!
  • PHP variables may only be composed of alphanumeric characters and underscores; for example, a-z, A-Z, 0-9, and _.
  • Variables in PHP are case sensitive. This means that $variable_name and $Variable_Name are different.
  • Variables with more than one word should be separated with underscores; for example, $test_variable.
  • Variables can be assigned values by using the equals sign (=).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3 Questions
Question 3-1.
How does text output in your browser if you don't use PHP syntax?
Question 3-2.
What do you combine with PHP code to create a dynamic web site?
Question 3-3.
How do you add comments to your code?
Question 3-4.
What are the two types of comments?
Question 3-5.
How is a semicolon used in PHP?
Question 3-6.
What does a variable store?
Question 3-7.
How do you define a variable in PHP?
Question 3-8.
Are variables in PHP case-sensitive?
Question 3-9.
How are functions used with a chunk of PHP code?
Question 3-10.
What is PHP_SELF?
Question 3-11.
How do you escape a single quote?
Question 3-12.
What does strcmp do?
Question 3-13.
What combines one or more text strings as a variable?
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: PHP Decision Making
In the last chapter, you started to get a feel for programming with PHP and some code basics. Now it's time to expand your knowledge and ability with PHP. We'll start with expressions and statements. Concepts from Chapter 3 and this chapter lay the foundations for adding your database, MySQL, which will be explored in Chapter 5.
There are several building blocks of coding that you need to understand: statements, expressions, and operators. A statement is code that performs a task. Statements themselves are made up of expressions and operators. An expression is a piece of code that evaluates to a value. A value is a number, a string of text, or a Boolean.
A Boolean is an expression that results in a value of either TRUE or FALSE. For example, the expression 10 > 5 (10 is greater than 5) is a Boolean expression because the result is TRUE. All expressions that contain relational operators, such as the less-than sign (<), are Boolean. The Boolean operators are AND, OR, XOR, NOR, and NOT.
An operator is a code element that acts on an expression in some way. For instance, a minus sign can be used to tell the computer to decrement the value of the expression after it from the expression before it. The most important thing to understand about expressions is how to combine them into compound expressions and statements using operators. So we're going to look at operators used to turn expressions into more complex expressions and statements.
The simplest form of expression is a literal or a variable. A literal evaluates to itself. Some examples of literals are numbers, strings, or constants. A variable evaluates to the value assigned to it. For instance, any of the expressions in Table 4-1 are valid.
Table 4-1: Valid expressions
Example
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Expressions
There are several building blocks of coding that you need to understand: statements, expressions, and operators. A statement is code that performs a task. Statements themselves are made up of expressions and operators. An expression is a piece of code that evaluates to a value. A value is a number, a string of text, or a Boolean.
A Boolean is an expression that results in a value of either TRUE or FALSE. For example, the expression 10 > 5 (10 is greater than 5) is a Boolean expression because the result is TRUE. All expressions that contain relational operators, such as the less-than sign (<), are Boolean. The Boolean operators are AND, OR, XOR, NOR, and NOT.
An operator is a code element that acts on an expression in some way. For instance, a minus sign can be used to tell the computer to decrement the value of the expression after it from the expression before it. The most important thing to understand about expressions is how to combine them into compound expressions and statements using operators. So we're going to look at operators used to turn expressions into more complex expressions and statements.
The simplest form of expression is a literal or a variable. A literal evaluates to itself. Some examples of literals are numbers, strings, or constants. A variable evaluates to the value assigned to it. For instance, any of the expressions in Table 4-1 are valid.
Table 4-1: Valid expressions
Example
Type
1
A numeric value literal
"Becker Furniture"
A string literal
TRUE
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Operator Concepts
PHP has many types of operators. The categories are:
  • Arithmetic operators
  • Array operators
  • Assignment operators
  • Bitwise operators
  • Comparison operators
  • Execution operators
  • Incrementing/decrementing operators
  • Logical operators
  • String operators
The operators are listed as found on http://www.zend.com/manual/language.operators.php. There are some operators we're not going to discuss in order for you to get up and running with PHP as quickly as possible. These include some of the casting operators that we'll just skim the surface of, for now. When working with operators, there are four aspects that are critical:
  • Number of operands
  • Type of operands
  • Order of precedence
  • Operator associativity
The easiest place to start is by talking about the operands.
Depending on which operator you are using, it may take different numbers of operands. Many operators are used to combine two expressions into a more complex single expression; these are called binary operators. Binary operators include addition, subtraction, multiplication, and division.
Other operators take only one operand; these are called unary operators. Think of the negation operator (-) that multiplies a numeric value by -1. The auto-increment and -decrement operators described in Chapter 3 are also unary operators.
A ternary operator takes three operands. The shorthand for an if statement, which we'll talk about later when discussing conditionals, takes three operands.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Conditionals
Since we've been talking about variables, we should also mention conditionals, which, like variables, form a building block in our foundation of PHP development. They alter a script's behavior according to the criteria set in the code. There are three primary elements of conditionals in PHP:
  • if
  • switch
  • ? : : (shorthand for an if statement)
PHP also supports a conditional called a switch statement. The switch statement is useful when you need to take different action based on the contents of a variable that may be set to one of a list of values.
The if statement offers the ability to execute a block of code, if the supplied condition is TRUE; otherwise, the code block doesn't execute. The type of condition can be any expression, including tests for nonzero, null, equality, variables, and returned values from functions.
No matter what, every single conditional you create includes a conditional clause. If a condition is true, the code block in curly brackets ({}) is executed. If not, PHP ignores it and moves to the second condition and continues through as many clauses as you write until PHP hits an else, then it automatically executes that block.
Figure 4-2 demonstrates how an if statement works. The else block always needs to come last and be treated as if it's the default action. This is similar to the semicolon (;), which acts as the end of a sentence. Common true conditions are:
  • $var, if $var has a value other than the empty set (0), an empty string, or NULL
  • isset ($var), if $var has any value other than NULL, including the empty set or an empty string
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Looping
Now change the flow of your PHP program based on comparisons, but if you want to repeat a task until a comparison is FALSE, you will need to use looping. Each time the code in the loop executes, it is called an iteration. It's useful for many common tasks such as displaying the results of a query by looping through the returned rows. PHP provides the while, for, and while . . . do constructs to perform loops.
Each of the loop constructs requires two basic pieces of information. First, when to stop looping is defined just like the comparison in an if statement. Second, the code to perform is also required and specified either on a single line or within curly braces. A logical error would be to omit the code in the loop, causing an infinite loop.
The code is executed as long as the expression evaluates to TRUE. To avoid an infinite loop, which would loop forever, your code should affect the expressions so that it becomes FALSE. When this happens, the loop stops, and execution continues with the next line of code, following the logical loop.
The while loop takes the expression followed by the code to execute. Figure 4-3 illustrates how a while loop processes.
Figure 4-3: How a while loop executes
The syntax is for a while loop is:
while (expression)
{
  code to
 execute;
}
An example is shown in Example 4-14.
Example 4-14. A sample while loop that counts to 10
<?php
$num = 1;

while ($num <= 10){
    print "Number is $num<br />\n";
    $num++;
}

print 'Done.';
?>
Example 4-14 produces:
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
Number is 10
Done.
Before the loop begins, the variable $num is set to 1. This is called initializing a counter variable. Each time the code block executes, it increases the value in
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4 Questions
Question 4-1.
What is a statement?
Question 4-2.
What is a code element that acts on an expression?
Question 4-3.
What does an operator combine?
Question 4-4.
What is the plus (+) sign?
Question 4-5.
What is a binary operator?
Question 4-6.
What is a ternary operator?
Question 4-7.
Do mathematical operators take letters as operands?
Question 4-8.
What type of operand is an Array Index?
Question 4-9.
If you use two ampersands (&&) instead of one (&), will you get an error?
Question 4-10.
What does isset() do?
Question 4-11.
Write a switch statement that adds, subtracts, multiplies, or divides x using the action variable.
Question 4-12.
What does the break keyword do?
Question 4-13.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Functions
To write programs in PHP that contain more than just a couple of pages of code and are still organized enough to be useful, you need to understand functions. Functions provide a way to eliminate repeating the same lines of code over and over in your programs. Functions work by assigning a name to a chunk of code, called a function name. Then you execute the code by calling that name.
There are hundreds of built-in functions in PHP. For example, print_r is a function that prints readable information about a variable in plain English rather than code.
If given a string, integer, or float, the value itself is printed with the print_r function. If given an array, values are shown as keys and elements. A similar format is used for objects. With the advent of PHP 5.0, print_r and var_export show protected and private properties of objects.
Functions run the gamut from aggregate_info to imap_ping through pdf_open_image. Since there are so many, we can only cover some basics in this chapter, but we'll give you enough information that you'll be using functions like a pro in no time at all. You can search http://www.php.net for an exhaustive list of functions.
Specifically, we'll go over the following:
  • How to create a function, give it a name, and execute that function
  • How to send values to a function and use them in the function
  • How to return values from a function and use them in your code
  • How to verify a function exists before you try using it
When to split out code into a function is a bit of a judgment call. Certainly, if you find yourself repeating several lines of code over and over, it makes sense to pull that code into its own function. That will make your code easier to read and also prevent you from having to make a lot of changes if you decide to do something different with that block of code, as it's then only in one spot, not numerous places where you'd have to search and replace to change it.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Calling Functions
Functions that are built into PHP can be called from any PHP script. When you call functions, you are executing the code inside them, except the code is reusable and more maintainable. One built-in function, shown in Example 5-2, is phpinfo. It returns configuration and technical information about your PHP installation.
Example 5-2. Displaying information about the PHP environment
<?php
    phpinfo();
?>
The function helps you diagnose common problems and issues. You may find that this is one of the most helpful places to look when checking to see whether you meet the requirements of a PHP script. Figure 5-2 shows only part of the information contained on this page. If a function call doesn't work, this page helps diagnose whether PHP is compiled with the necessary modules.
Figure 5-2: Information about PHP displayed in the browser
To call a function, write the name of the function followed by an opening parenthesis (, the parameters, and then a closing parenthesis ), followed by a semicolon (;). It would look like this: function_name ( parameters );. Function names aren't case sensitive, so calling phpinfo is the same as calling PhpInfo. As shown in Example 5-3, this is what calling a function looks like: md5($mystring);.
Most functions have return values that you'll either use in a comparison or store in a variable. A great place to start is the md5 function. md5 is a one-way hash function used to verify the integrity of a string, similar to a checksum. md5 converts a message into a fixed string of digits, called a message digest. You can then perform a hashcheck, comparing the calculated message digest against a message digest decrypted with a public key to verify that the message was not tampered with. Example 5-3 creates a 128-bit long md5 signature of the string "mystring".
Example 5-3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining Functions
There are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement:
function some_function([arguments]) { code to execute }
The brackets ([ ]) mean optional. The code could also be written with optional_arguments in place of [ arguments ]. The function keyword is followed by the name of the function. Function names abide by the same rules as other named objects such as variables in PHP. A pair of parentheses must come next. If your function has parameters, they're specified within the parentheses. Finally, the code to execute is listed between curly brackets, as seen in the code above.
You can define functions anywhere in your code and call them from virtually anywhere. Scope rules apply. The scope of a variable is the context within which it's defined. For the most part, all PHP variables have only a single scope. A single scope spans included and required files as well. The function is defined on the same page or included in an include file. Functions can have parameters and return values that allow you to reuse code.
To create your own function that simply displays a different hello message, you would write:
<?php
function hi()
{
  echo ("Hello from function-land!");
}
//Call the function
hi();
?>
which displays:
Hello from function-land!
The hi function doesn't take any parameters, so you don't list anything between the parentheses. Now that you've defined a simple function, let's mix in some parameters.
Parameters provide a convenient way to pass information to a function when you call it without having to worry about variable scope. In PHP, you don't have to define what type of data a parameter holds—only the name and number of parameters must be specified.
An example of a function is strtolower, which converts your string "Hello world!" to lowercase. It takes a parameter of the type string, which is a data type (described in a previous chapter). There's also another function
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object-Oriented Programming
Object-Oriented programming follows the same goals that we discussed when introducing functions, principally to make reusing code easier. It uses classes to group functions and variables together as an object. It may help to think of objects as little black boxes that can do work without you knowing exactly how it's done.
They still use functions, but they get a new name when defined in classes. They're called methods. The class works as a blue print for creating objects of that type. Variables can still be defined in methods, but they gain the new ability to be defined as part of the class itself.
When a new object is created from a class, it is called an instance of that class. Any variables that are defined in the class get separate storage space in each instance. The separate storage for variables provides the instance of an object with the ability to remember information between method executions. Figure 5-3 demonstrates the relationship between a class and its components.
Figure 5-3: A class can contain methods and attributes (variables)
If you're new to the concepts of OO programming, don't worry about understanding everything right away. We'll work with a class in Chapter 7, so it's good enough just to know how to call the methods. In fact, anything that can be done with objects can be done with plain functions. It's just a matter of style and personal preference.
Classes are typically stored in separate files for reuse. Although we show the class, it isn't required. Let's build an object called Cat that has three methods: meow, eat, and purr. The class construct defines a class. It takes the name of the class immediately after it. Class names follow the same naming rules as variables and functions. The code that makes up the class is placed between curly brackets. This example creates the Cat class without defining any methods or variables.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5 Questions
Question 5-1.
What's wrong with this function call?
<?php

// define a function
function Response {
echo "Have a good day!<br /><br />";
}

// driving to work
echo "Are you going to merge? <br />";
Response;

// at the office
echo "I need a status report on all your projects in the next 10 minutes for
my management meeting.<br />";
Response;

// at the pub after work
echo "Did Bill get everything he needed today? He was sure crabby!<br />";
Response;
?>
Question 5-2.
Define a function called toast that takes minutes as a parameter. The function prints "done."
Question 5-3.
Call the toast function with 5 as a parameter.
Question 5-4.
What's the difference between using include() and require()?
Question 5-5.
What is a function called when it is part of a class?
See the Appendix for the answers to these questions.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Arrays
Content preview·