In this hour, you willlearn How to define and call functions How to pass values to functions and receive values in return How to call a function dynamically using a string stored in a va
Trang 11: How would you use an if statement to print the string "Youth message" to the
browser if an integer variable, $age, is between 18 and 35? If $age contains any othervalue, the string "Generic message" should be printed to the browser
A1:
$age = 22;
if ( $age >= 18 && $age <= 35 ) {
print "Youth message<BR>\n";
if ( $age >= 18 && $age <= 35 ) {
print "Youth message<BR>\n";
} elseif ( $age >= 1 && $age <= 17 ) {
print "Child message<BR>\n";
Trang 2Review the syntax for control structures Think about how the techniques you've learned will help you
in your scripting Perhaps some of the script ideas you develop will be able to behave in differentways according to user input, or will loop to display an HTML table Start to build the control
structures you will be using Use temporary variables to mimic user input or database queries for thetime being
[ Team LiB ]
Trang 3[ Team LiB ]
Hour 6 Working with Functions
Functions are at the heart of a well-organized script, making code easy to read and reuse No largeproject would be manageable without them Throughout this hour, we will investigate functions anddemonstrate some of the ways in which they can save you from repetitive work In this hour, you willlearn
How to define and call functions
How to pass values to functions and receive values in return
How to call a function dynamically using a string stored in a variable
How to access global variables from within a function
How to give a function a "memory"
How to pass data to functions by reference
How to create anonymous functions
How to verify that a function exists before calling it
[ Team LiB ]
Trang 4If you needed to bake a single cake, you would probably do it yourself If you needed to bake
thousands of cakes, you would probably build or acquire a cake-baking machine Similarly, whendeciding whether to create a function, the most important factor to consider is the extent to which itcan save you from repetition
A function is a self-contained block of code that can be called by your scripts When called, thefunction's code is executed You can pass values to functions, which will then work with them Whenfinished, a function can pass a value back to the calling code
[ Team LiB ]
Trang 5[ Team LiB ]
Calling Functions
Functions come in two flavors—those built in to the language and those you define yourself PHP hashundreds of built-in functions The very first script in this book, which appears in Hour 3, "Installingand Configuring PHP," consists of a single function call:
print "Hello Web!";
In this example, we call the print() function, passing it the string "Hello Web!" The functionthen goes about the business of writing the string A function call consists of the function name
(print in this case) followed by parentheses If you want to pass information to the function, youplace it between these parentheses A piece of information passed to a function in this way is called
an argument Some functions require that more than one argument be passed to them Arguments insuch cases must be separated by commas:
some_function( $an_argument, $another_argument);
print() is typical in that it returns a value Most functions give you some information back whenthey've completed their task—they usually at least tell whether their mission was successful
print() returns a Boolean
The abs() function, for example, requires a signed numeric value and returns the absolute value ofthat number Let's try it out in Listing 6.1
print() is not a typical function in that it does not requireparentheses in order to run successfully:
print("Hello Web!");
and
print "Hello Web!";
are equally valid This is an exception All other functions requireparentheses, whether or not they accept arguments
Trang 6Listing 6.1 Calling the Built-in abs() Function
In this example, we assign the value -321 to a variable $num We then pass that variable to the
abs() function, which makes the necessary calculation and returns a new value We assign this tothe variable $newnum and print the result
Put these lines into a text file called abs.php, and place this file in your Web server document root.When you access this script through your Web browser, it produces the following:
321
In fact, we could have dispensed with temporary variables altogether, passing our number straight to
abs(), and directly printing the result:
print( abs( -321 ) );
We used the temporary variables $num and $newnum, though, to make each step of the process asclear as possible Sometimes you can make your code more readable by breaking it up into a greaternumber of simple expressions
You can call user-defined functions in exactly the same way that we have been calling built-in
functions
[ Team LiB ]
Trang 7[ Team LiB ]
Defining a Function
You can define a function using the function statement:
function some_function( $argument1, $argument2 ) {
// function code here
}
The name of the function follows the function statement and precedes a set of parentheses Ifyour function requires arguments, you must place comma-separated variable names within theparentheses These variables will be filled by the values passed to your function Even if your functiondoesn't require arguments, you must nevertheless supply the parentheses
The naming rules for functions are similar to the naming rules forvariables, which you learned in Hour 4, "The Building Blocks of PHP."
Names cannot include spaces, and they must begin with a letter or
an underscore
Listing 6.2 declares a function
Listing 6.2 Declaring a Function
Trang 8The script in Listing 6.2 simply outputs the string "HELLO" wrapped in an HTML <h1> element.Put these lines into a text file called bighello.php, and place this file in your Web server
document root When you access this script through your Web browser, it should look like Figure 6.1
Figure 6.1 Output of Listing 6.2
We declare a function bighello() that requires no arguments Because of this, we leave theparentheses empty bighello() is a working function but is not terribly useful Listing 6.3 creates
a function that requires an argument and actually does something helpful with it
Listing 6.3 Declaring a Function That Requires Arguments
11: printBR("This is a new line");
12: printBR("This is yet another line");
13: ?>
14: </body>
Trang 915: </html>
Put these lines into a text file called printbr.php, and place this file in your Web server documentroot When you access this script through your Web browser, it should look like Figure 6.2
Figure 6.2 A function that prints a string with an appended <br> tag.
In line 7, the printBR() function expects a string, so we place the variable name $txt betweenthe parentheses when we declare the function Whatever is passed to printBR() will be stored in
$txt Within the body of the function, in line 8, we print the $txt variable, appending a <br>
element and a newline character to it
When we want to write a line to the browser, such as in line 10, 11, or 12, we can call printBR()
instead of the built-in print(), saving us the bother of typing the <br> element
[ Team LiB ]
Trang 10[ Team LiB ]
Returning Values from User-Defined Functions
In the previous example, we output an amended string to the browser within the printBR()
function Sometimes, however, you will want a function to provide you with a value that you canwork with yourself If your function has transformed a string that you have provided, you may wish
to get the amended string back so that you can pass it to other functions A function can return avalue using the return statement in conjunction with a value The return statement stops theexecution of the function and sends the value back to the calling code
Listing 6.4 creates a function that returns the sum of two numbers
Listing 6.4 A Function That Returns a Value
7: function addNums( $firstnum, $secondnum ) {
8: $result = $firstnum + $secondnum;
Notice in line 7 that addNums() should be called with two numeric arguments (line 11 shows those
to be 3 and 5 in this case) These are stored in the variables $firstnum and $secondnum.Predictably, addNums() adds the numbers contained in these variables together and stores theresult in a variable called $result
Trang 11The return statement can return a value or nothing at all How we arrive at a value passed by
return can vary The value can be hard-coded:
return 4;
It can be the result of an expression:
return ( $a/$b );
It can be the value returned by yet another function call:
return ( another_function( $an_argument ) );
[ Team LiB ]
Trang 12[ Team LiB ]
Dynamic Function Calls
It is possible to assign function names as strings to variables and then treat these variables exactly
as you would the function names themselves Listing 6.5 shows a simple example of this
Listing 6.5 Calling a Function Dynamically
A string identical to the name of the sayHello() function is assigned to the
$function_holder variable on line 10 Once this is done, we can use this variable in conjunctionwith parentheses to call the sayHello() function We do this on line 11
Put these lines into a text file called sayhello.php, and place this file in your Web server
document root When you access this script through your Web browser, it produces the following:
hello
Why would we want to do this? In the example, we simply make more work for ourselves by
assigning the string "sayHello" to $function_holder Dynamic function calls are usefulwhen you want to alter program flow according to changing circumstances We might want our script
to behave differently according to a parameter set in a URL's query string, for example We canextract the value of this parameter and use it to call one of a number of functions
[ Team LiB ]
Trang 13[ Team LiB ]
Variable Scope
A variable declared within a function remains local to that function In other words, it will not beavailable outside the function or within other functions In larger projects, this can save you fromaccidentally overwriting the contents of a variable when you declare two variables with the samename in separate functions
Listing 6.6 creates a variable within a function and then attempts to print it outside the function
Listing 6.6 Variable Scope: A Variable Declared Within a Function Is
Unavailable Outside the Function
Put these lines into a text file called scopetest.php, and place this file in your Web server
document root When you access this script through your Web browser, it should look like Figure 6.3
Figure 6.3 Output of Listing 6.6
Trang 14The value of the variable $testvariable is not printed This is because no such variable existsoutside the test() function Note that the attempt in line 10 to access a nonexistent variable doesnot cause an error.
Similarly, a variable declared outside a function will not automatically be available within it
Accessing Variables with the global Statement
From within a function, it is not possible by default to access a variable that has been defined
elsewhere If you attempt to use a variable with the same name, you will only set or access a localvariable Let's put this to the test in Listing 6.7
Listing 6.7 Variables Defined Outside Functions Are Inaccessible from Within a Function by Default
Trang 15As you might expect, the meaningOfLife() function does not have access to the $life variable
in line 7; $life is empty when the function attempts to print it On the whole, this is a good thing;
it saves us from potential clashes between identically named variables, and a function can alwaysdemand an argument if it needs information about the outside world Occasionally, however, youmay want to access an important global variable from within a function without passing it in as anargument This is where the global statement comes into its own Listing 6.8 uses global torestore order to the universe
Listing 6.8 Accessing Global Variables with the global Statement
Trang 16Figure 6.5 Successfully accessing a global variable from within a
function using the global keyword.
By placing global in front of the $life variable when we declare it in the meaningOfLife()
function (line 9), we make it refer to the global $life variable declared outside the function (line7)
You will need to use the global statement for every function that you want to access for a
particular global variable
Be careful, though If we manipulate the contents of the variable within the function, $life will bechanged for the script as a whole
Trang 17You can declare more than one variable at a time with the global statement by simply separatingeach of the variables you wish to access with commas.
global $var1, $var2, $var3;
Usually, an argument is a copy of whatever value is passed by thecalling code; changing it in a function has no effect beyond the functionblock Changing a global variable within a function, on the other hand,changes the original and not a copy Use the global statementsparingly
[ Team LiB ]
Trang 18Let's assume that we want a function to keep track of the number of times it has been called Why?
In our examples, the function is designed to create numbered headings in a script that dynamicallybuilds online documentation
We could, of course, use the global statement to do this We have a crack at this in Listing 6.9
Listing 6.9 Using the global Statement to Remember the Value of a
Variable Between Function Calls
Trang 19Figure 6.6 Using the global statement to keep track of the number of
times a function has been called.
This does the job We declare a variable, $num_of_calls, in line 7, outside the function
numberedHeading() We make this variable available to the function using the global
This is where the static statement can be useful If you declare a variable within a function inconjunction with the static statement, the variable remains local to the function, and the function
"remembers" the value of the variable from execution to execution Listing 6.10 adapts the code fromListing 6.9 to use the static statement
Listing 6.10 Using the static Statement to Remember the Value of a
Variable Between Function Calls
Trang 20numberedHeading() has become entirely self-contained When we declare the
$num_of_calls variable on line 8, we assign an initial value to it This assignment is made whenthe function is first called on line 12 This initial assignment is ignored when the function is called asecond time on line 14 Instead, the code remembers the previous value of $num_of_calls Wecan now paste the numberedHeading() function into other scripts without worrying about globalvariables Although the output of Listing 6.10 is exactly the same as that of Listing 6.9 (try it andsee!), we have made the code more elegant
[ Team LiB ]
Trang 21[ Team LiB ]
More About Arguments
You've already seen how to pass arguments to functions, but there's more to cover yet In thissection, you'll look at a technique for giving your arguments default values and explore a method ofpassing variables by reference rather than by value This means that the function is given an "alias"
of the original value rather than a copy of it
Setting Default Values for Arguments
PHP gives you a nifty feature to help build flexible functions Until now, we've said that some
functions "demand" one or more arguments By making some arguments optional, you can renderyour functions a little less autocratic
Listing 6.11 creates a useful little function that wraps a string in an HTML font element We want togive the user of the function the chance to change the font element's size attribute, so we
demand a $size argument in addition to the string (line 7)
Listing 6.11 A Function Requiring Two Arguments
7: function fontWrap( $txt, $size ) {
8: print "<font size=\"$size\"
9: face=\"Helvetica,Arial,Sans-Serif\">
10: $txt</font>";
11: }
12: fontWrap("A heading<br>",5);
13: fontWrap("some body text<br>",3);
14: fontWrap("some more body text<BR>",3);
15: fontWrap("yet more body text<BR>",3);
16: ?>
17: </body>
18: </html>
Put these lines into a text file called fontwrap.php, and place this file in your Web server
document root When you access this script through your Web browser, it should look like Figure 6.7
Trang 22Figure 6.7 A function that formats and outputs strings.
Useful though this function is, we really only need to change the font size occasionally Most of thetime we use the default value of 3 By assigning a value to an argument variable within the functiondefinition's parentheses, we can make the $size argument optional If the function call doesn'tdefine an argument for this, the value we have assigned to the argument is used instead Listing 6.12uses this technique to make the $size argument optional
Listing 6.12 A Function with an Optional Argument
7: function fontWrap( $txt, $size=3 ) {
8: print "<font size=\"$size\"
9: face=\"Helvetica,Arial,Sans-Serif\">
10: $txt</font>";
11: }
12: fontWrap("A heading<br>",5);
13: fontWrap("some body text<br>");
14: fontWrap("some more body text<br>");
15: fontWrap("yet more body text<br>");
Trang 23Passing Variable References to Functions
When you pass arguments to functions, they are stored as copies in parameter variables Any
changes made to these variables in the body of the function are local to that function and are notreflected beyond it This is illustrated in Listing 6.13
Listing 6.13 Passing an Argument to a Function by Value
Trang 2411 A copy of the contents of $orignum is stored in the variable $num Although we increment
$num by 5, this has no effect on the value of $orignum When we print $orignum, we find thatits value is still 10 By default, variables passed to functions are passed by value In other words,local copies of the values of the variables are made
We can change this behavior by creating a reference to our original variable You can think of areference as a signpost that points to a variable In working with the reference, you are manipulatingthe value to which it points
Listing 6.14 shows this technique in action When you pass an argument to a function by reference,
as in line 11, the contents of the variable you pass ($orignum) are accessed by the argumentvariable and manipulated within the function, rather than just a copy of the variable's value (10).Any changes made to an argument in these cases will change the value of the original variable Youcan pass an argument by reference by adding an ampersand to the argument name in the functiondefinition, as shown in line 7
Listing 6.14 Using a Function Definition to Pass an Argument to a
Put these lines into a text file called addfive2.php, and place this file in your Web server
document root When you access this script through your Web browser, it produces the following:
15
[ Team LiB ]
Trang 25[ Team LiB ]
Creating Anonymous Functions
It is possible to create functions on the fly during script execution Because such functions are notthemselves given a name, but are stored in variables or passed to other functions, they are known asanonymous functions PHP provides the create_function() function for creating anonymousfunctions create_function() requires two string arguments The first argument should contain
a comma-delimited list of argument variables, exactly the same as the argument variables you wouldinclude in a standard function declaration The second argument should contain the function body.Listing 6.15 creates a simple anonymous function to add two numbers together
Listing 6.15 A Simple Anonymous Function
Trang 26Note that we use single quotes when passing arguments to create_function() That saves usfrom having to escape the variable names within the arguments We could have used double quotes,but the function call would have been a little more involved:
$my_anon = create_function("\$a, \$b", "return \$a+\$b;");
So what is the use of anonymous functions? In practical terms, you will probably only use them whenyou need to pass callback functions to built-in functions A callback function is generally written bythe user and is designed to be invoked (usually repeatedly) by the function to which it is passed
The second argument to create_function() is the function body
Don't forget to end the last statement in this string with a semicolon
The interpreter will complain and your anonymous function will not beexecuted if you omit it
[ Team LiB ]
Trang 27[ Team LiB ]
Testing for the Existence of a Function
You have seen that we do not always know that a function exists before we try to invoke it If ourcode were to work with a function name stored in a variable, for example, it would be useful to beable to test whether or not the function exists before we attempt to call it Furthermore, differentbuilds of the PHP engine may include different functionality If you are writing a script that may berun on multiple servers, you might want to verify that key features are available You might writecode that will use MySQL if MySQL-related functions are available, but simply log data to a text fileotherwise
You can use function_exists() to check for the availability of a function
function_exists() requires a string representing a function name It will return true if thefunction can be located and false otherwise
Listing 6.16 shows function_exists() in action, and illustrates some of the other topics wehave covered in this hour
Listing 6.16 Testing for a Function's Existence
8: function tagWrap( $tag, $txt, $func="" ) {
9: if ( ! empty( $txt ) && function_exists( $func ) ) {
Trang 2824:
25: print tagWrap('i', 'make me italic and quote me',
26: create_function('$txt', 'return ""$txt"";'));
27: // <i>"make me italic and quote me"</i>
28:
29: ?>
30: </body>
31: </html>
We define two functions, tagWrap() (line 8) and underline() (line 15) The tagWrap()
function accepts three strings: a tag, the text to be formatted, and an optional function name Itreturns a formatted string underline() requires a single argument—the text to be
formatted—and returns the text wrapped in <u> tags
When we first call tagWrap() on line 19, we pass it the character b and the string make me bold Because we haven't passed a value for the function argument, the default value (an emptystring) is used On line 9, we check whether the $func variable contains characters and, if it is notempty, we call function_exists() to check for a function by that name Of course, the $func
variable is empty, so we wrap the $txt variable in <b> tags on line 11 and return the result
We call tagWrap() on line 22 with the string 'i', some text, and a third argument:
"underline" function_exists() finds a function called underline() (line 15), so it callsthis function and passes the $txt argument variable to it before any further formatting is done Theresult is an italicized, underlined string
Finally, on line 25, we call tagWrap(), which wraps text in quotation entities Of course, it would bequicker to simply add the entities to the text to be transformed ourselves, but this illustrates thepoint that function_exists() works as well on anonymous functions as it does on stringsrepresenting function names
Put these lines into a text file called exists.php, and place this file in your Web server documentroot When you access this script through your Web browser, it should look like Figure 6.8
Figure 6.8 Output of Listing 6.16
Trang 29[ Team LiB ]
Trang 31$newstring = "I purchased".numPurchase($somenum)." items.";
[ Team LiB ]
Trang 322: How do you return a value from a function?
A2: You must use the return keyword
3: What would the following code fragment print to the browser?
A3: It would print 50 The tenTimes() function has no access to the global $number
variable When it is called, it will manipulate its own local $number variable
4: What would the following code fragment print to the browser?
Trang 33print $number;
A4: It would print 500 We have used the global statement, which gives the tenTimes()
function access to the $number variable
5: What would the following code fragment print to the browser?
Activity
Create a function that accepts four string variables and returns a string that contains an HTML tableelement, enclosing each of the variables in its own cell
[ Team LiB ]
Trang 34[ Team LiB ]
Hour 7 Learning Basic SQL Commands
This hour takes a break from all that PHP you've been learning and provides a primer on SQL syntax,which you will use to create and manipulate your MySQL database tables This is a very hands-onhour, and it assumes that you are able to issue queries through the MySQL monitor on Windows orLinux/Unix Alternatively, if you use a GUI to MySQL, this hour assumes you know the methods forissuing queries through those interfaces
In this hour, you will learn
The basic MySQL data types
How to use the CREATE TABLE command to create a table
How to use the INSERT command to enter records
How to use the SELECT command to retrieve records
How to use basic functions, the WHERE clause, and the GROUP BY clause in SELECT
expressions
How to select from multiple tables, using JOIN
How to use the UPDATE and REPLACE commands to modify existing records
How to use the DELETE command to remove records
[ Team LiB ]
Trang 35[ Team LiB ]
Learning the MySQL Data Types
Properly defining the fields in a table is important to the overall optimization of your database Youshould use only the type and size of field you really need to use These types of fields (or columns)
are also referred to as data types because it's the type of data you will be storing in those fields.
MySQL uses many different data types, which are broken into three categories: numeric, date andtime, and string types Pay close attention because defining the data type is more important than anyother part of the table creation process
Numeric Data Types
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from adifferent database system, these definitions will look familiar to you The following list shows thecommon numeric data types and their descriptions
The terms signed and unsigned will be used in the list of numeric
data types If you remember your basic algebra, you'll recall that asigned integer is a positive or negative integer, whereas an unsignedinteger is a non-negative integer
INT— A normal-sized integer that can be signed or unsigned If signed, the allowable range isfrom –2147483648 to 2147483647 If unsigned, the allowable range is from 0 to 4294967295.You can specify a width of up to 11 digits
INT and INTEGER are synonymous If it helps you toremember the data type by using INTEGER instead of INT, gofor it
TINYINT— A very small integer that can be signed or unsigned If signed, the allowable range
is from –128 to 127 If unsigned, the allowable range is from 0 to 255 You can specify a width
of up to 4 digits
SMALLINT— A small integer that can be signed or unsigned If signed, the allowable range is
Trang 36from –32768 to 32767 If unsigned, the allowable range is from 0 to 65535 You can specify awidth of up to 5 digits.
MEDIUMINT— A medium-sized integer that can be signed or unsigned If signed, the allowablerange is from –8388608 to 8388607 If unsigned, the allowable range is from 0 to 16777215.You can specify a width of up to 9 digits
BIGINT— A large integer that can be signed or unsigned If signed, the allowable range is from–9223372036854775808 to 9223372036854775807 If unsigned, the allowable range is from 0
to 18446744073709551615 You can specify a width of up to 11 digits
FLOAT(M,D)— A floating-point number that cannot be unsigned You can define the displaylength (M) and the number of decimals (D) This is not required and will default to 10,2, where
2 is the number of decimals and 10 is the total number of digits (including decimals) Decimalprecision can go to 24 places for a FLOAT
DOUBLE(M,D)— A double precision floating-point number that cannot be unsigned You candefine the display length (M) and the number of decimals (D) This is not required and willdefault to 16,4, where 4 is the number of decimals Decimal precision can go to 53 places for a
DOUBLE REAL is a synonym for DOUBLE
DECIMAL(M,D)— An unpacked floating-point number that cannot be unsigned In unpackeddecimals, each decimal corresponds to one byte Defining the display length (M) and the
number of decimals (D) is required NUMERIC is a synonym for DECIMAL
Of all the MySQL numeric data types, you will likely use INT most often You can run into problems ifyou define your fields to be smaller than you actually need; for example, if you define an id field as
an unsigned TINYINT, you won't be able to successfully insert that 256th record if ID is a primarykey (and thus required)
Date and Time Types
MySQL has several data types available for storing dates and times, and these data types are flexible
in their input In other words, you can enter dates that are not really days, such as February
30—February has only 28 or 29 days, never 30 Also, you can store dates with missing information Ifyou know that someone was born sometime in November of 1980, you can use 1980-11-00, where
"00" would have been for the day, if you knew it
The flexibility of MySQL's date and time types also means that the responsibility for date checkingfalls on the application developer MySQL checks only two elements for validity: that the month isbetween 0 and 12 and the day is between 0 and 31 MySQL does not automatically verify that the30th day of the second month (February 30th) is a valid date
The MySQL date and time data types are
DATE— A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31 For example,December 30th, 1973 would be stored as 1973-12-30
DATETIME— A date and time combination in YYYY-MM-DD HH:MM:SS format, between