Errata

Programming PHP

Errata for Programming PHP

Submit your own errata for this product.

The errata list is a list of errors and their corrections that were found after the product was released.

The following errata were submitted by our customers and have not yet been approved or disproved by the author or editor. They solely represent the opinion of the customer.

Color Key: Serious technical mistake Minor technical mistake Language or formatting error Typo Question Note Update

Version Location Description Submitted by Date submitted
n/a
Section 2.4.13. Miscellaneous Operators

The description for the "Execution" operator says this:

====================
Execution ('...')

The backtick operator executes the string contained between the backticks as a shell command and returns the output. For example:

$listing = 'ls -ls /tmp';
echo $listing;
====================

The execution operator is backticks, not single-quotes. That should read:


====================
Execution (`...`)

The backtick operator executes the string contained between the backticks as a shell command and returns the output. For example:

$listing = `ls -ls /tmp`;
echo $listing;
====================

Mark Pettit  Apr 29, 2011 
n/a
Section 2.4.8. Comparison Operators (and others)

The section about comparison operators starts out like this:

======================
The comparison operators are:


equality (==) operator= (equals sign):== (equal to) operatorEquality (==)

If both operands are equal, this operator returns true; otherwise, it returns false.
======================

What is all that extra text after "equality (==) operator"? This stuff:

= (equals sign):== (equal to) operatorEquality (==)

It seems completely pointless. There are a bunch of places in this section that have the same kind of problem.

Mark Pettit  Apr 29, 2011 
Printed Page 12
first line

the action part (now: action="<?php $PHP_SELF; ?>") at least needs an echo, thus: action="<?php echo $PHP_SELF; ?>" and better use _SERVER['PHP_SELF'] instead of $PHP_SELF.

This holds also for the example on page 15.

Anonymous  Dec 12, 2008 
13
code sample at bottom of page, 4th code line from bottom

Change "execut" to "execute"

Anonymous  Jan 30, 2009 
Printed Page 13-14
First line of Example 1-4

Both opening php marks of the example 1-4 are incomplete:
<?
instead of
<? php

Michela  Dec 21, 2009 
Printed Page 14
code, 2nd line from top

It seems that "colspan=7" should be changed to "colspan=4", since only 4 columns are spanned by the title (see figure on pg. 13).

Anonymous  Jan 30, 2009 
Printed Page 15
Example 1-5

I have carefully typed in this example, and cannot get any text to show up in the button graphic. When I added echo statements to the code to print out various values at the time the image is displayed, here is what I got:

Value of x and y are: 47.5 and 14
Value of dx and dy are: 0 and 0
Values in tsize [0 to 5] are: -1 -1 -1 -1 -1 -1
String in message was: asdf

That is the correct message string, but I suppose everything else is wrong due to the values in tsize. A copy of the tsize assignment statement is as follows:

Note that I added ".ttf" to the "times" string, and copied the times.ttf file into the LocalHost directory. Without that, I was only got invalid font file name errors from the imagettfbbox and InageTTFText commands.

$font = 'times.ttf';
$size = 12;
$msg = $_GET['message'];
$im = ImageCreateFromPNG('09_button.png');
$tsize = imagettfbbox($size,0,$font,$_GET['messasge']);

Since I am new to PHP, I am at a loss as to where to look, beyond verifying that each character from the example was faithfully reproduced in the code I executed. So, I don't know if this is a problem with the book's example? Or with my implementation of PHP? or with the support library I may (or may not) have? Any suggestions would be appreciated.

David Watkins  Mar 25, 2009 
Printed Page 25
Table 2-2

I'm reading the edition 11/04 of the book.
The "escape sequences" { } [ ] actually does not exist, for example

<?php echo "{}[]"; ?>

just displays (PHP 5.2):

{}[]

There is only one exception reported by the manual www.php.net:

"Again, if you try to escape any other character, the backslash will be printed too!
Before PHP 5.1.1, backslash in {$var} hasn't been printed."

Since I'm running PHP 5.2, I can't verify this sentence.

Anonymous   
Printed Page 26
4th and 5th lines from the bottom

Replace 0.314*101 with 0.314*10^1 (or make ^1 a superscript 1)
Replace 17.0*10-3 with 17.0*10^(-3) (or make ^(-3) a superscript -3)

Anonymous   
Printed Page 27
middle

The program code and sample output are intermixed

same holds for pages 28,29,30,32,33,34,35

Anonymous  Dec 12, 2008 
Printed Page 27
First code example on the page

if (int($a *1000) == int($b * 1000)) {

To my knowledge there exisis no Funktion int() in PHP. I think the the code should be changed to

if (intval($a *1000) == intval($b * 1000)) {

Best regard
Burkhard Maier

Anonymous  Oct 24, 2009 
Printed Page 30
approximately middle of page

The code:
printf("Hello,%s\n", $ed->name);

is incorrect for this pure php example.

Anonymous  Jan 17, 2010 
Printed Page 32
Under heading Variable Variables

$foo = 'bar';
$$foo = 'baz';

There is an extra dollar sign with $$foo.
There is no variable $bar, so the entire section makes NO sense.

Anonymous  Jan 17, 2010 
Printed Page 33
first line

The operator ".=" is used, but it is not described until p48

Anonymous   
Printed Page 33
All

Missing pages 33-48.

Anonymous   
Printed Page 39
example at the bottom of the page

The second line from the bottom has

"9 Lives." - 1 // 8 (float)

The type here is in fact an integer, as the following output shows:

Script started on Sun 09 Sep 2007 03:54:35 PM CDT
$ php --version
PHP 5.1.4 (cli) (built: Jul 14 2006 11:04:03)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies
$ php
<?
echo gettype("9 Lives." - 1); . "
";
echo gettype("9. Lives" - 1) . "
";
?>
integer
double
$ exit

Script done on Sun 09 Sep 2007 03:56:09 PM CDT

The example presumably demonstrates the rule stated a few lines prior: "If the string contains a period (.) or upper- or lowercase e, evaluating it numberically produces a floating-point number." Taken literally, this implies that "9. Lives" - 1 should evaluate to a floating-point number, but it seems this is not the case. Perhaps the text should read "If the number at the start of the string contains a period ...", etc.

Anonymous   
Printed Page 41
paragraph below table 2-5

Text reads:
AS illustrated in Table 2-6, incrementing "z" or "Z" wraps it back to "a" or "Z" and....
should be:
AS illustrated in Table 2-6, incrementing "z" or "z" wraps it back to "aa" or "AA" and....

(tested in PHP5 environment)

Anonymous   
Printed Page 42-44
entire page

The definition list of the comparison operators doesn't make sense (formatting problem?)

For example: the definition tag for the equality operator reads:

"equality (=) operator= (equals sign):== (equal to) operatorEquality (==)"

Why not just: "equality (=)"? If this layout is intentional, there is no explanation for
why it is thus. (When we get to the section "Logical operators" on p.45, the tags change
to what one would intuitively expect ("Logical AND (&&, and)")

Anonymous   
Printed Page 42
Table 2-7

In the fourth row of the table (First operand = String that is not entirely numeric, Second operand = Number), the comparison type should be "Numeric", not "Lexicographic".

Anonymous  Nov 16, 2009 
45
middle of page, under heading "Logical OR..."

This is a minor formatting issue. This sentence:

"The || and or operators differ only in their precedence."

should not be formatted in the monospace code font, but rather normal text font (see the Logical AND section on same page for comparison).

Anonymous  Jan 30, 2009 
Printed Page 53
Last code fragment

$j was not defined in the code fragment, leading to errors when you run it.

Anonymous   
Printed Page 64
Line 8

Replace "reflexive" with "inverses".

Anonymous   
Printed Page 70
Example 3-6

$count was never defined in the code fragment. Correction:

function count_list(){
if(func_num_args() == 0){
return false;
}

else {
$count = 0;
for ($i = 0; $i < func_num_args();$ i++){
$count += func_get_arg($i);
}
return $count;
}
}

Anonymous   
Printed Page 79
chart on bottom

Most of the Specifiers should be lower-case letters. Also, there is a difference between "e" and "f" as listed below.

(From PHP.net -> http://ca3.php.net/manual/en/function.sprintf.php)
b - the argument is treated as an integer, and presented as a binary number.
c - the argument is treated as an integer, and presented as the character with that ASCII value.
d - the argument is treated as an integer, and presented as a (signed) decimal number.
e - the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
f - the argument is treated as a float, and presented as a floating-point number (locale aware).
F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
o - the argument is treated as an integer, and presented as an octal number.
s - the argument is treated [as] and presented as a string.
u - the argument is treated as an integer, and presented as an unsigned decimal number.
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

The examples on page 80 all seem to work, although using unspecified variables ($day, $month, $year) is somewhat confusing.
Am also hard-pressed to find what a "double" and a "double with precision" are - are these terms explained anywere in the book?

Anonymous   
Printed Page 81
Middle of page

The calls of print_r on true, false, and NULL have comments indicating that
is printed. This is not correct. No
is printed for any of the calls. So print_r(true) results in the output of a single 1, nothing more, and print_r(false) and print_r(NULL) produce no output at all.

Anonymous   
Printed Page 83
line 6

The word "charset" should be "charlist".

Anonymous   
Printed Page 83
second code example

Because there are no leading or trailing tabs in $record, the effect of calling trim with a charlist is exactly the same as calling trim without a charlist. So the example fails to illustrate the point that it is intended to show.

Anonymous   
Printed Page 83
second code sample from top

This example should be rewritten:

$record = " Fred\tFlintstone\t35\tWilma \n";
$record = trim($record, " \r\n\0\x0B");
// $record is "Fred\tFlintstone\t35\tWilma"

As it stands, the " \r\n\0\x0B" (charset argument) could be omitted and would give the same results. Only leading/trailing tabs are removed automatically, not inner tabs, so the charset argument is unnecessary. As a better example, some tabs should be added to the beginning or end of the $record variable. So a possible fix is to change the first line to:
$record = " \tFred\tFlintstone\t35\tWilma\t \n";

Anonymous  Jan 31, 2009 
Printed Page 83
tab separated data example at top of page

The example shows how to specify the characters to be removed by Trim by supplying a charset, and demonstrates how to exclude the tab character from the trimming action.

However, since there are no tabs at either the head or tail of the string, wouldn't the result be ths same if you did not specify the charset, and just used the default charset in the trim command?

I am assuming that if you used trim with the default character set, it would NOT remove the tabs embedded in the middle of the string, any more than it would remove blanks embedded in the string. However, your example seems to imply that it is necessary to exclude tabs from the charset in order to leave them embedded in the string (thus my confusion).

Perhaps a better example would be one that only removed the newline character and left the blanks on both ends of the string?

David Watkins  Mar 25, 2009 
Printed Page 85
3/4 down the page

In the example on flipping the translation table in order to convert from text-with-entites back to the original text, the output is wrong:

Einst ?rzende Neubauten

should read

Einst?rzende Neubauten

Anonymous   
Printed Page 86
"Extracting meta tags" section

The first sentence of this section is misleading and should be changed:

"If you have the HTML for a web page in a string, the get_meta_tags() function returns an array of the meta tags in that page."

should read something like

"If you have the URL of a web page in a string, ...", etc.

As originally written, it sounds as though one is supposed to put the HTML markup for the page in the string.

Anonymous   
Printed Page 87
example at the bottom of the page

The output shown in the last two lines of the page is incorrect. One actually gets

"It's never going to work," she cried,
as she hit the backslash () key.

That is, one gets the original value of $string except with the backslash in the parentheses removed.

A casual reader might thing that after calling addslashes on $string, the contents of $string actually changes to what is output by the line

echo addslashes($string);

If this were indeed the case, then the quoted output for

echo stripslashes($string);

would in fact be correct, since stripslashes would then simply be undoing what addslashes did to string. But this is not how these functions work. They do not alter the value of their arguments in place. In this example, the value of $string remains unchanged.

To correct this example, one could simply replace the line

echo addslashes($string);

with the two lines

$string = addslashes($string);
echo $string;

leaving everything else the same.

Anonymous   
Printed Page 90
code that spans pages 90-91

The code is missing the word "like" in two places. The output has the word "like", but this is inconsistent with the code that produces it.
These two lines should be changed:

print "soundex: $known sounds $query<br>";
print "metaphone: $known sounds $query<br>";

To:

print "soundex: $known sounds like $query<br>";
print "metaphone: $known sounds like $query<br>";

Anonymous  Jan 31, 2009 
Printed Page 95
2nd sample code section

The program code and sample output are intermixed: The third line is

print_r($a);Array

There should be a line break before "Array".

Anonymous   
95
second code sample from top

Small formatting issue. This line:

print_r($a);Array

Should be:

print_r($a);
Array

("Array" on new line, since it's output.)

Anonymous  Jan 31, 2009 
Printed Page 97
Decomposing URLs

missing a closing quote:
$bits = parse_url('http://me:secret@example.com/cgi-bin/board?user=fred);

Bud Koch  Jan 21, 2009 
97
4.7.4.4. section: Decomposing URLs, code sample after "for example:"

Missing single quote (') before right parenthsis at end of this line:
$bits=parse_url('http://me:secret@example.com/cgi-bin/board?user=fred);

Also missing final close parenthesis at end of Array output in Safari version (but not the book version, oddly enough).

Anonymous  Feb 01, 2009 
Printed Page 100
First paragraph.

The last sentence of the paragraph states "[^]] matches any character that is not a closing bracket". This is true only if one is using Perl-compatible regular expressions. When using POSIX-style regular expressions, the first "]" in "[^]]" is treated as the closing bracket of the character class, and so "[^]]" matches any two-character sequence in which the first character is not "" and the second character is "]".

Anonymous   
Printed Page 101
Subpatterns

I tried the example

ereg('([0-9]+)', 'You have 42 magic beans', $captured);

The function does return true as written in the book. The problem is with the var $captured. If you perform var_dump you have the following:
array(2) { [0]=> string(2) "42" [1]=> string(2) "42" }

Shouldn't index 0 (zero) contain the whole string? "The zeroth element of the array is set to the entire string being matched against."

Since POSIX-style does use of the Unix locale system I tried it also on Windows and get the same results for $captured var.

Anonymous   
Printed Page 103
last line

And once more a serious error in the captured array: Correctors, read the manual page again please. captured[0] contains the matching parts not the string in question!

Anonymous  Dec 17, 2008 
Printed Page 103
last line of the page


original line:
ereg('y(.*)e$', 'Sylvie', $a); // returns true, $a is array('Sylvie', 'lvi')

should be
ereg('y(.*)e$', 'Sylvie', $a); // returns true, $a is array('ylvie', 'lvi')

Bud Koch  Jan 21, 2009 
Printed Page 106
Bottom of the page

On the bottom of the page (and in the header of the next page) we can see 2 patters:

1) '/([[:alpha:]]+)s+1/'
2) '/([[:alpha:]]+)s+1)/x'

I guess the problem is in the statement: "These two patterns are the same, but one is much easier to read".

They are not the same. As instructed in the book the 2nd one will strip whitespaces before matching. If so, it will not find repeated words.

Example:

$pattern1 = '/([[:alpha:]]+)s+1/';
$pattern2 = '/([[:alpha:]]+s+1)/x';

$str = 'Look for a word word again.';

if(preg_match($pattern1, $str))
echo 'true';
else
echo 'false';

You'll have different results for $pattern1 and $pattern2

Anonymous   
Printed Page 111
top of page, first complete sentence

Missing the word "to" in this sentence where shown:

You need an additional set of capturing parentheses [to] do that.

Anonymous  Feb 02, 2009 
Printed Page 112
last sentence on the page

The last sentence states "The cut never changes the outcome of the match; it simply makes it fail faster."

This may be true of the pattern in this example, but it is not true in general. For example,

/(?>d+)5foo/

does not match the string '12345foo', but

/(d+)5foo/

does.

Anonymous   
117
code at top of page

In this code (p 117-118):

$to_find = '/usr/local/etc/rsync.conf';
$re = preg_quote($filename, '/');
if (preg_match("/$re", $filename)) {
// found it!
}

The $filename variable in the preg_quote function should be changed to $to_find:

$re = preg_quote($to_find, '/');

Anonymous  Feb 03, 2009 
Printed Page 118
first line

The closing regular expression is missing:

"/$re" should be "/$re/".

Anonymous   
Printed Page 132
top

The function calls made should be

add_up(0,2)
add_up(4,3)
add_up(13,5)
add_up(38,7)

Anonymous   
Printed Page 132-3
Example 5-2

This example seems out of place. The discussion immediately before and after the example is all about the 'in_array' function, but the example does not use this function at all! (It does use the 'empty' function, which hasn't been discussed up to this point.)

Anonymous   
Printed Page 132
Top of page

The 3 sample function calls listed at the top of the page are incorrect. When I inserted echo statements into the function, it indicated that the actual function calls were:

add_up ( , 2)
add_up (4, 3)
add_up (13, 5)
add_up (38, 7)

In fact, this is the only way the result could be correctly computed.

The example in the book would be correct if the array were (3, 5, 7) and the seeded initial value was 2, for a total of 85 (not 87 as indicated in the text).

David Watkins  Apr 01, 2009 
Printed Page 132
Example 5-2

It is very confusing to have a section of text discussing the in_array function, and embedded in that text is an example that does not use the function. In fact, the example cannot use the function, as the in_array function does not perform the kind of check required by the example. So, while the example does fit into the general topic of "Searching for Values" covered in this section of the book, it does not illustrate the use of the in_array function that is discussed immediately before and immediately after the example. The example should be separated from the in_array discussion, with some language indicating "here is another way to search for values..."

David Watkins  Apr 01, 2009 
Printed Page 133
Second code example

The second line of the second code block reads:

$k = array_search($person, 'Wilma');

The order of the arguments is incorrect. The search term should come first, the array
to search should come second. The corrected code is:

$k = array_search('Wilma', $person);

The order is *correctly* referenced on page 391.

Anonymous   
Printed Page 135-6
Example 5-3

Like Example 5-2, this example uses $submitted where it needs to use $_POST['submitted']. Similarly for $sort_type. A simple fix would be to call "extract($_POST)" before either of these two variables is used.

Anonymous   
Printed Page 135-136
Example 5-3 Sorting Arrays

In order to get this example to work, I had to make the following two changes.

1) Prior to the "if ($submitted)..." statement, insert:
$sort_type = $_POST['sort_type'];

2) Change the "if ($submitted)..." statement, to:
if ($_POST['submitted'])

Additionally, in the "form" statement, the action="index.php" clause only works if the file you create for this program is named "index.php". That would be helpful information for those of us who are new to PHP and HTML.

David Watkins  Apr 01, 2009 
Printed Page 135
example 5-3 sorting arrays

just learning PHP, so its hared to say, but line 18 gives me an error about 'submitted' not being defined. also, the 'submit' button doesn't seemed to call anything. i'm sure to you all this is a trivial thing, but to a newbie its fatal.


<?php
function user_sort($a,$b){
//smarts is all-important,so sort it first
if ($b =='smarts') {
return 1;
} else if ($a == 'smarts') {
return -1;
}

return ($a ==$b)?0 :(($a <$b)?-1 :1);
}

$values = array('name' => 'Buzz Lightyear',
'email_address' => 'buzz@starcommand.gal',
'age' => 32,
'smarts' => 'some');

if ($submitted) {
if ($sort_type == 'usort' || $sort_type == 'uksort' ||
$sort_type == 'uasort') {
$sort_type($values,'user_sort');
} else {
$sort_type($values);
}
}
?>

<form action="index.php">

<p>
<input type="radio" name="sort_type" value="sort" checked="checked"/>
Standard sort<br />
<input type="radio" name="sort_type" value="rsort" /> Reverse sort<br />
<input type="radio" name="sort_type" value="usort" /> User-defined sort<br />
<input type="radio" name="sort_type" value="ksort" /> Key sort<br />
<input type="radio" name="sort_type" value="krsort" />Reverse key sort<br />
<input type="radio" name="sort_type" value="uksort" />User-defined key sort<br />
<input type="radio" name="sort_type" value="asort" /> Value sort<br />
<input type="radio" name="sort_type" value="arsort" />Reverse value sort<br />
<input type="radio" name="sort_type" value="uasort" />User-defined value sort<br />
</p>

<p align="center">
<input type="submit" value="Sort" name="submitted" />
</p>
</form>

Anonymous  Dec 16, 2010 
Printed Page 142
Last paragraph

Output from Example 5-4: there is one too many 'Exiting' output message. The last is
one 'Exiting' output message line should be removed. After 'Entering first (...)'
there should only be the exiting messages from first() and third().

Anonymous   
Printed Page 146
The line just before the "tip" icon that starts "// outputs:"

The output is wrong. It should read "Barney and Fred are best friends."

Anonymous   
Printed Page 147
Second sentence of the second paragraph.

A missing comma makes this sentence easy to mis-read.

The sentence currently reads "For instance, if you call $rasmus->birthday() inside the birthday() method, $this holds the same value as $rasmus." It sounds here as though $rasmus->birthday() is being called inside the birthday() method, that is, that somehow $rasmus->birthday() is being called recursively. I'm sure this is not the intended meaning. A comma just before "inside" (possibly with the word "then" added) would clarify the meaning: "For instance, if you call $rasmus->birthday(), then inside the birthday() method, $this holds the same value as $rasmus." In addition, the comma after "method" should perhaps be eliminated.

Anonymous   
Printed Page 152
code example just before the "Destructors" heading

It is very confusing that this example uses PHP4-style contructors ("function Person(...) {...}" and "function Employee(...) {...}" when only PHP5-style contructors ("__contruct") are mentioned in the text.

Anonymous   
Printed Page 152
3rd and 4th paragraph

3rd paragraph:
"A constructor is [..] called __construct()."

Then follows an example showing exactly this.

4th paragraph then suddenly uses the class name as a constructor:

class Person(..) {
...
function Person(..)

No single explanation that both are valid (is it?)

Anonymous  Oct 21, 2008 
Printed Page 153
1st paragraph

PHP's destructor method is called __destruct(), not __destructor().
See http://www.php.net/language.oop5.decon .

Anonymous   
Printed Page 156
Example 6-2, function get_inherited_methods.

When a class has no parent class, presumably it has no inherited methods. But as defined, this function ("get_inherited_methods") incorrectly returns ALL of the class's methods in such a case.

Anonymous   
Printed Page 157
Example 6-2, function get_child_classes

The line

if (substr($class, 0, 2) == '_ _') {

probably contains a typo, since the substr can never by longer than two characters and thus the condition can never be true since '_ _' contains three characters. Presumably the compared-to string should be '__' (no space).

Anonymous   
Printed Page 157
Example 6-2, function get_child_classes

This may be a configuration-dependent problem, but I found that many of the built-in classes returned by get_declared_classes couldn't be instantiated by the call

$child = new $class

and attempting to do so threw an exception (for example, "DOMAttr::__construct() expects at least 1 parameter, 0 given").

In any case, I had to wrap this line in a try-catch block to get this example to work.

Anonymous   
Printed Page 161
Example 6-3.

The first function is the constructor and should therefore be called:

function __construct($filename) {

not

function Log($filename) {

Anonymous   
Printed Page 161
Example 6-3.

The first line of the declaration of the fifth function in class Log reads "function _ _wakeup() {". It should read "function __wakeup() {" (no space between the two underscores). Similarly for the sleep function.

Anonymous   
Printed Page 172,173,174
Temperature conversion coding examples (7-3, 7-4 and 7-5)

In all three examples of the temperature conversion code, in the 'input' statement for the 'submit' button, the button text should be declared as "value" instead of "name". If the example is entered as shown in the text, the button is displayed with "Submit Query", and the text "Convert to Celsius!" does not appear.

David Watkins  Apr 02, 2009 
Printed Page 177
Line 9 and Line 12

The "value" text for the Thinking and Shopper checkboxes is incorrect. On line 9, the Thinking checkbox, the value text should be "thinking" instead of "feeling". On line 12, the Shopper checkbox, the value text should be "prodigal" instead of "thrifty".

David Watkins  Apr 02, 2009 
Printed Page 178
3rd line of code after "// create HTML for identically named checkboxes

printf('%s <input type="checkbox" name="%s[]" vlaue="%s" ',
$label, $name, $value);

There is no: "/>"

Anonymous   
Printed Page 180
Example 7-9,

The example is missing a statement. At the beginning, where the local PHP variables are set to their $_POSTed values, the following statement should be added:

$status = $_POST['status'];

Without this statement, the value the user sets in the status checkbox is not "sticky" from one form usage to the next.

Also, on page 181, in the form declaration for the name input line, the
type=text
should be
type="text"

David Watkins  Apr 02, 2009 
Printed Page 195
Example 7-15

The code of example 7-15 does not work. It should contain $_COOKIE['bgcolor'], but it doesn't.

Here is a working example:

<?php
if ($_POST['bgcolor']) {
setcookie ('bgcolor', $_POST['bgcolor'], time () + (60 * 60 * 24 * 7));
} // if
$bgcolor = $_POST['bgcolor'];
if (empty ($bgcolor)) $bgcolor = $_COOKIE['bgcolor'];
if (empty ($bgcolor)) $bgcolor = 'gray';
?>

<html>
<head>
<title>Color Selector</title>
</head>
<body bgcolor="<?= $bgcolor ?>">

<form action="<?= $PHP_SELF ?>" method="POST">
<select name="bgcolor">
<option value="gray">Gray</option>
<option value="white">White</option>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="red">Red</option>
</select>

<input type="submit" />
</form>

</body>
</html>

Anonymous   
Printed Page 204
last paragraph

LAST CODE EXAMPLE ON THE PAGE:
Wrong:
$row = $result->fetchrow(DB_FETCHMODE_ASSOC);
should be:
$row = $result->fetchrow(DB_FETCHMODE_OBJECT);

Anonymous   
Printed Page 205
bottom

$movies = array (...);
shoud say
$books = array (...);

Anonymous   
Printed Page 206
Bottom of page

Last line says:
"$db->insertMultiple($compiled, $books);"

Last line should have said:
"$responses = $db->executeMultiple($compiled, $books);"

Anonymous   
Printed Page 207
2nd-to-last paragraph: the sample code with sample output

This example is supposed to demonstrate the "getCol" method which was just introduced in the preceding paragraph. But "getAll" is written instead. In other words, the line

$titles = $db->getAll("Select title FROM books ORDER BY pub_year ASC");

should read

$titles = $db->getCol("Select title FROM books ORDER BY pub_year ASC");

(Using "getAll" would make "$titles" an array of arrays and "$title" an array. This would make the output something like

Array
Array
Array

).

Anonymous   
Printed Page 207
last line of text

"movies" should be "books"
"movie" should be "book"

Anonymous   
Printed Page 219
End of example code, just before </body> tag

Missing </form> end tag.

Anonymous   
Printed Page 220
in example 8-6

Need to define $cat_id

Insert this line after "require_once('db_login.php');"
$cat_id = $_REQUEST['cat_id'];

Anonymous   
Printed Page 247
chapter codes files...

while submitting this, i noticed newer chpt 10 code files that match the code as written in the book, and work, but only for ex.10-1 through 10-7; 10-8 through 10-14 have not been updated, and don't work.

Stephen Wille  Dec 18, 2010 
Printed Page 265
Bottom of the Page Example 11-2 Start element handler

The foreach loop starts on the bottom of the page and continues on to the top of the next page as follows:

The lines marked with -> are the ones that I ended up changing.

function start_element($inParser, $inName, &$inAttributes)
{
-> foreach($inAttributes as $key)
{
-> $value=$inAttributes[$key];
-> $attributes[]="<font color=\"gray\">$key=\"$value\"</font>";
}
echo '&lt;<b>'.$inName.'</b>.join(' ',$attributes).&gt;';
}
I'm using PHP5 and I had a couple of problems getting this to work. I changed the first line to:

foreach($inAttributes as $key => $value)

removed the second line:

$value=$inAttributes[$key];

and changed the third line to:

$attributes[]='<font color="gray">'.$key.'="'.$value.'"</font>';

So the whole thing was changed to this.

function start_element($inParser, $inName, &$inAttributes)
{
foreach($inAttributes as $key => $value)
{
$attributes[]='<font color="gray">'.$key.'="'.$value.'"</font>';
}
echo '&lt;<b>'.$inName.'</b>.join(' ',$attributes).&gt;';
}

Interestingly enough I looked at this code several times and brushed it off as too complicated to mess with. In the end, I dug into it and it helps a lot to understand how the parser works. Which has lead to other insights that I hadn't expected. Thanks.

It would be helpful to be more clear that as you progress through the description of the various handlers leading up to this example that the function handlers that you are creating are supposed to be used in the example.


Anonymous  Oct 12, 2008 
Printed Page 275
bottom of function BookList

In 3rd line from end of function BookList, $x receives the result
of the function join(). The call to function join passes in an
empty string as the first parameter and an array of lines of a file
as the second parameter (the result of the call to the file() function).
However, the join reference on page 444 says that join() should expect
an array as its first parameter and string as its second. I think that
either the call to join on 275 or the reference info on 444 is reversed.

I just looked up join and implode on php.net. It says the parameters
can be in either order, so I guess this isn't really a mistake. However,
to save people the confusion, it would be great if you could make a note
of this is the join documentation on 444 and the implode documentation
on 438, or just change the example on 275 to be consistent with your
own documentation.

Anonymous   
Printed Page 275
chapter 11

no updated code files for chapter 11. exercise [11-1.php] worked, but [11-10.php] gives 3 fatal errors.

Stephen Wille  Dec 20, 2010 
Printed Page 276
Function: cdata

The if/else in the function "cdata" uses "===",
should this be "=="?

Anonymous   
Printed Page 277
1st paragraph (1st code sample)

When I run the sample code below:

$parser = new domdocument();
$rootNode = $parser->load('books.xml');

processNodes($rootNode);

function processNodes($node) {
$children = $node->children;

foreach ($children as $child) {
if ($child->nodeType == XML_TEXT_NODE) {
echo $child->noteValue;
}
elseif ($child->nodeType == XML_ELEMENT_NODE) {
processNodes($child);
}
}
}

I get the following PHP Warning error:

Invalid argument supplied for foreach() in websiteswebappslearnPHPProgPHP2Ch11-
XMLParseXML-DOM2.php on line 10

Any suggestions?

Anonymous   
Printed Page 277
top

The DOM XML example is completely broken and does not run. Not even the syntax is right:

echo $child->noteValue;
should be:
echo $child->nodeValue;

Anonymous   
Printed Page 277
Code in DOM section

Broken, old syntax, typos, you name it....
Corrections are commented on

$parser = new DomDocument();
$rootNode = $parser->load('BookList.xml');
processNodes($parser);
// $parser, NOT $rootNode which only holds load() successTRUE/FALSE

function processNodes($node) {
$children = $node->childNodes;
// childNodes, NOT children

foreach ($children as $child) {
if ($child->nodeType == XML_TEXT_NODE) {
echo $child->nodeValue;
// nodeValue, NOT noteValue

}
else if ($child->nodeType == XML_ELEMENT_NODE) {
processNodes($child);
}
}
}

Anonymous   
Printed Page 277
8th line from the bottom

foreach ($document->library->book as $book)

should be

foreach ($document->book as $book)

Anonymous   
Printed Page 277
8th line from the bottom



foreach ($document->library->book as $book)

should be

foreach ($document->book as $book)

Anonymous  Jun 13, 2008 
Printed Page 280
top

Example 11-12:

<xsl:value-of select="teaser"/> is not necessary because the XML document (example 11-11)
does not contain any <teaser> elements.

Anonymous   
Printed Page 299
eval example doesn't work

Here is a working eval example:

<html>
<head>
<title>Here is the entry to my computer!</title>
</head>
<body>
<h2>Execute code</h2>
(e.g.: include ('/etc/passwd'); )
<br/>
<?php
$code = $_POST['code'];
// echo ("Code: '$code'");
// echo ("<br/>");
if ($code) {
echo ("<p>");
echo ("Executing code...");
echo ("<br/>");
eval (stripslashes ($code));
echo ("</p>");
} // if
?>
<br/>
<form action="<?= $PHP_SELF ?>" method="POST">
<input type="text" name="code" />
<input type="submit" name="Execute Code" />
</form>
</body>
</html>

Anonymous   
Printed Page 308
top

return str_replace ('...', '...', $contents);
should be:
return str_replace ('...', '...', $text);

Anonymous   
Printed Page 344
Line 3

The line ends with

&s_len)

but it should end with

&s_len, &d)

to avoid a segmentation fault.

Anonymous   
Printed Page 373
top

"Open the Control Panels folder, and double-click on the ODBC Data Sources icon."

Under Windows XP there is no ODBC Data Sources icon in the Control Panel folder.
However, there is a 'Administrative Tools' icon. If you open the 'Administrative
Tools' folder, you see the ODBC Data Sources icon.

Anonymous   
Printed Page 391
Bottom of page

I Minutes, including a leading zero if necessary; e.g. "00" thought "59"

s/b

i Minutes, including a leading zero if necessary; e.g. "00" thought "59"

Anonymous  Jul 06, 2009 
Printed Page 406-407
Under "date"

All date() formatting is shown in upper case, which is incorrect. For example, "D" is defined as "Day of the month as two digits"; on the next line, "D" is defined again, this time as "Name of the day of the week as three-letter abbreviation". The second is correct, the first is wrong...it should read "d "Day of the month as two digits". The same applied to ALL the listed example. None of the lower case examples are shown, and half of the upper case examples are incorrectly defined.

Anonymous  Jan 17, 2010 
Printed Page 407
Most of the page

What happened to the capitalisation? This list is not very helpful because it omits which letter should or should not be capitalised.

Anonymous   
Printed Page 407
first "z" in list of format characters

Replace 'from "1" through' by 'from "0" through'.

Anonymous   
Printed Page 420
last entry

Upper/lower case problem, caused by the spelling checker, similar to what was already
found with the date() function also occurs with e.g. the 'mode'-parameter of the
fopen() function.

Anonymous   
Printed Page 420
within spec of "fopen" command

The parameters should ALL be in lower case.
e.g in the book "R - Open the file for reading..."
should be "r - Open the file for reading..."

It's the same case for "W" and "A".
I have just spent an hour trying to figure out an error that was the result of this!

The same case problem is on page 406-407 in relation to the date command. Half of
those parameters should be in lower case, but in the book they are all uppercase.

Anonymous   
Printed Page 438
third function on page (implode)

In the function definition, the parameters are reversed.
Should be:
string implode(string separator, array strings)

Anonymous   
Printed Page 444
last function on page (join)

In the function definition, the parameters are reversed.
Should be:
string join(string separator, array strings)

Anonymous   
Printed Page 471
shell_exec() entry

Is: "Executes command via the shell and returns the last line of output from the command ..."
Should be: "... returns the output from the command ..."

"the last line" describes the exec() function, not shell_exec()

Anonymous   
Printed Page 474-475
str_ireplace & str_replace

The signatures use the variable 'string' but the descriptions mistakenly use 'subject' as well as 'string' to refer to 'string'.

Christian Campbell  Sep 07, 2010 
Printed Page 516
column 1

The php statements include_once, require and require_once are omitted from the index
(should refer to pp57-58

Anonymous   
Printed Page 523
Colophon paragraph 1

The animal on the covers is not, in fact, a common cuckoo, as the common cuckoo is not crested. It is probably a roadrunner (Geococcyx californianus).

Anonymous