<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Web Wesigning Education</title>
	<atom:link href="http://swebsolution.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://swebsolution.wordpress.com</link>
	<description>Web Wesigning Education</description>
	<lastBuildDate>Fri, 08 May 2009 08:59:39 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='swebsolution.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/99bfa977fa60736e62fa9189a3eb303d?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Web Wesigning Education</title>
		<link>http://swebsolution.wordpress.com</link>
	</image>
			<item>
		<title>Windows Shortcut Keys</title>
		<link>http://swebsolution.wordpress.com/2009/05/08/windows-shortcut-keys/</link>
		<comments>http://swebsolution.wordpress.com/2009/05/08/windows-shortcut-keys/#comments</comments>
		<pubDate>Fri, 08 May 2009 08:59:39 +0000</pubDate>
		<dc:creator>Prakash Sherawat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://swebsolution.wordpress.com/2009/05/08/windows-shortcut-keys/</guid>
		<description><![CDATA[100 Useful Windows Shortcut Keys
Here&#8217;s a list of about 100 shortcut keys for Windows. This list of shortcut keys applies for almost all Windows platform.   If you know any new shortcuts which I have not include in this list, kindly comment below. Thank you and enjoy!    Common Shortcut Keys:

CTRL+C (Copy) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=38&subd=swebsolution&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h5><a href="http://blackzigoth.blogspot.com/2008/07/100-useful-windows-shortcut-keys.html">100 Useful Windows Shortcut Keys</a></h5>
<p>Here&#8217;s a list of about 100 shortcut keys for Windows. This list of shortcut keys applies for almost all Windows platform.   <br />If you know any new shortcuts which I have not include in this list, kindly comment below. Thank you and enjoy!    <br />Common Shortcut Keys:</p>
<ul>
<li>CTRL+C (Copy) </li>
<li>CTRL+X (Cut) </li>
<li>CTRL+V (Paste) </li>
<li>CTRL+Z (Undo) </li>
<li>CTRL+A (Select)</li>
<li>DELETE (Delete) </li>
<li>SHIFT+DELETE (Delete the selected item permanently without placing the item in the Recycle Bin) </li>
<li>CTRL while dragging an item (Copy the selected item) CTRL+SHIFT while dragging an item (Create a shortcut to the selected item) </li>
<li>F2 key (Rename the selected item) </li>
<li>CTRL+RIGHT ARROW (Move the insertion point to the beginning of the next word) </li>
<li>CTRL+LEFT ARROW (Move the insertion point to the beginning of the previous word) </li>
<li>CTRL+DOWN ARROW (Move the insertion point to the beginning of the next paragraph) </li>
<li>CTRL+UP ARROW (Move the insertion point to the beginning of the previous paragraph) </li>
<li>CTRL+SHIFT with any of the arrow keys (Highlight a block of text) </li>
<li>SHIFT with any of the arrow keys (Select more than one item in a window or on the desktop, or select text in a document) </li>
<li>CTRL+A (Select all) </li>
<li>F3 key (Search for a file or a folder) </li>
<li>ALT+ENTER (View the properties for the selected item) </li>
<li>ALT+F4 (Close the active item, or quit the active program) </li>
<li>ALT+ENTER (Display the properties of the selected object) </li>
<li>ALT+SPACEBAR (Open the shortcut menu for the active window) </li>
<li>CTRL+F4 (Close the active document in programs that enable you to have multiple documents open simultaneously) </li>
<li>ALT+TAB (Switch between the open items) </li>
<li>ALT+ESC (Cycle through items in the order that they had been opened) </li>
<li>F6 key (Cycle through the screen elements in a window or on the desktop) </li>
<li>F4 key (Display the Address bar list in My Computer or Windows Explorer) </li>
<li>SHIFT+F10 (Display the shortcut menu for the selected item) </li>
<li>ALT+SPACEBAR (Display the System menu for the active window) </li>
<li>CTRL+ESC (Display the Start menu)</li>
<li>ALT+Underlined letter in a menu name (Display the corresponding menu)     <br />Underlined letter in a command name on an open menu (Perform the corresponding command) </li>
<li>F10 key (Activate the menu bar in the active program) </li>
<li>RIGHT ARROW (Open the next menu to the right, or open a submenu) </li>
<li>LEFT ARROW (Open the next menu to the left, or close a submenu) </li>
<li>F5 key (Update the active window) </li>
<li>BACKSPACE (View the folder one level up in My Computer or Windows Explorer) </li>
<li>ESC(Cancel the current task) </li>
<li>SHIFT when you insert a CD-ROM into the CD-ROM drive (Prevent the CD-ROM from automatically playing)</li>
</ul>
<p>Dialog Box Keyboard Shortcuts:
<ul>
<li>CTRL+TAB (Move forward through the tabs)</li>
<li>CTRL+SHIFT+TAB (Move backward through the tabs)</li>
<li>TAB (Move forward through the options)</li>
<li>SHIFT+TAB (Move backward through the options)</li>
<li>ALT+Underlined letter (Perform the corresponding command or select the corresponding option)</li>
<li>ENTER (Perform the command for the active option or button)</li>
<li>SPACEBAR (Select or clear the check box if the active option is a check box)</li>
<li>Arrow keys (Select a button if the active option is a group of option buttons)</li>
<li>F1 key (Display Help)</li>
<li>F4 key (Display the items in the active list)</li>
<li>BACKSPACE (Open a folder one level up if a folder is selected in the Save As or Open dialog box)</li>
</ul>
<p>Microsoft Natural Keyboard Shortcuts:
<ul>
<li>Windows Logo (Display or hide the Start menu)</li>
<li>Windows Logo+BREAK (Display the System Properties dialog box)</li>
<li>Windows Logo+D (Display the desktop)</li>
<li>Windows Logo+M (Minimize all of the windows)</li>
<li>Windows Logo+SHIFT+M (Restore the minimized windows)</li>
<li>Windows Logo+E (Open My Computer)</li>
<li>Windows Logo+F (Search for a file or a folder)</li>
<li>CTRL+Windows Logo+F (Search for computers)</li>
<li>Windows Logo+F1 (Display Windows Help)</li>
<li>Windows Logo+ L (Lock the keyboard)</li>
<li>Windows Logo+R (Open the Run dialog box)</li>
<li>Windows Logo+U (Open Utility Manager)</li>
<li>Accessibility Keyboard Shortcuts</li>
<li>Right SHIFT for eight seconds (Switch FilterKeys either on or off)</li>
<li>Left ALT+left SHIFT+PRINT SCREEN (Switch High Contrast either on or off)</li>
<li>Left ALT+left SHIFT+NUM LOCK (Switch the MouseKeys either on or off)</li>
<li>SHIFT five times (Switch the StickyKeys either on or off)</li>
<li>NUM LOCK for five seconds (Switch the ToggleKeys either on or off)</li>
<li>Windows Logo +U (Open Utility Manager)</li>
</ul>
<p>Microsoft Natural Keyboard with IntelliType Software Installed
<ul>
<li>Windows Logo+L (Log off Windows)</li>
<li>Windows Logo+P (Starts Print Manager)</li>
<li>Windows Logo+C (Opens Control Panel)</li>
<li>Windows Logo+V (Starts Clipboard)</li>
<li>Windows Logo+K (Opens Keyboard Properties dialog box)</li>
<li>Windows Logo+I (Opens Mouse Properties dialog box)</li>
<li>Windows Logo+A (Starts Accessibility Options (if installed)</li>
<li>Windows Logo+SPACEBAR (Displays the list of Microsoft IntelliType shortcut keys)</li>
<li>Windows Logo+S (Toggles CAPS LOCK on and off)</li>
</ul>
<p>Internet Explorer Shortcut Keys:
<ul>
<li>Alt+Left Arrow (Back a page)</li>
<li>Backspace (Back a page)</li>
<li>Alt+Right Arrow (Forward a page)</li>
<li>F5 (Refresh current page, frame or tab)</li>
<li>F11 (Display the current website in full screen mode. Pressing F11 again will exit this mode.)</li>
<li>ESC (Stop page or download from loading.)</li>
<li>CTRL-or+ (Increase or decrease the font size, pressing &#8216;-&#8217; will decrease and &#8216;+&#8217; will increase)</li>
<li>CTRL+Enter (Quickly complete an address. For example, type Google in the address bar and press CTRL + ENTER to get http://www.Google.com)</li>
<li>CTRL+D (Add a favorite for the page currently opened)</li>
<li>CTRL+I (Display available bookmarks)</li>
<li>CTRL+N (Open new browser Window)</li>
<li>CTRL+P (Print current page/frame)</li>
<li>CTRL+T (Opens a new tab)</li>
<li>CTRL+F4 (Close the currently selected tab)</li>
<li>CTRL+Tab (Moves through each of the open tabs)</li>
<li>Spacebar (Moves down a page at a time)</li>
<li>Shift+Spacebar (Moves up a page at a time)</li>
<li>ALT+Down arrow (Display all previous text entered in a text box and/or available options on drop down menu)</li>
</ul>
<p>Windows Tree Control:
<ul>
<li>Numeric Keypad * (Expands everything under the current selection)</li>
<li>Numeric Keypad + (Expands the current selection)</li>
<li>Numeric Keypad &#8211; (Collapses the current selection)</li>
<li>RIGHT ARROW (Expands the current selection if it is not expanded, otherwise goes to the first child)</li>
<li>LEFT ARROW (Collapses the current selection if it is expanded, otherwise goes to the parent)</li>
</ul>
Posted in Uncategorized  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/swebsolution.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/swebsolution.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/swebsolution.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/swebsolution.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/swebsolution.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/swebsolution.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/swebsolution.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/swebsolution.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/swebsolution.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/swebsolution.wordpress.com/38/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=38&subd=swebsolution&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://swebsolution.wordpress.com/2009/05/08/windows-shortcut-keys/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4fc1b8adaf945b9ecf45239af6e622af?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Prakash Sherawat</media:title>
		</media:content>
	</item>
		<item>
		<title>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP PART-03</title>
		<link>http://swebsolution.wordpress.com/2009/02/28/dreamweaver-cs3-with-css-ajax-and-php-part-03/</link>
		<comments>http://swebsolution.wordpress.com/2009/02/28/dreamweaver-cs3-with-css-ajax-and-php-part-03/#comments</comments>
		<pubDate>Sat, 28 Feb 2009 06:30:13 +0000</pubDate>
		<dc:creator>Prakash Sherawat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://swebsolution.wordpress.com/2009/02/28/dreamweaver-cs3-with-css-ajax-and-php-part-03/</guid>
		<description><![CDATA[Validating a drop-down menu with Spry
Applying a select validation widget is very simple. Highlight the menu object in Design
view, and click the Spry Validation Select button in the Insert bar. The following instructions
use the same form as throughout the rest of the chapter.
Use feedback_spry.php from the preceding exercise, or copy feedback_spry_start.php
from examples/ch09 to workfiles/ch09 and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=35&subd=swebsolution&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><b>Validating a drop-down menu with Spry</b>
<p>Applying a select validation widget is very simple. Highlight the menu object in Design
<p>view, and click the Spry Validation Select button in the Insert bar. The following instructions
<p>use the same form as throughout the rest of the chapter.
<p>Use feedback_spry.php from the preceding exercise, or copy feedback_spry_start.php
<p>from examples/ch09 to workfiles/ch09 and save it as feedback_spry.php.
<p><b>1. </b>In Design view, select the existing drop-down menu, and then click the List Values
<p>button in the Property inspector. The first item (– Select one –) is an invalid choice,
<p>so you need to take a note of its Value (0). Close the List Values dialog box.
<p><b>2. </b>With the menu still selected, click the Spry Validation Select button in the Insert bar.
<p><b>3. </b>In the Property inspector, select the Invalid value checkbox, and replace the default
<p>-1 with 0 in the field alongside. This is the invalid value you confirmed in step 1.
<p>Also select Validate on Change.
<p><b>4. </b>Save the page, and test it in a browser. An alert message should be displayed if you
<p>select nothing or an invalid value.
<p>As with the checkbox group, you can convert &lt;span&gt; tags to &lt;div&gt; tags. Spry isn’t concerned
<p>with the type of element used, but with the class and id attributes.
<p>Styling the alert messages follows the same principles as for a text field in the various validation
<p>widgets. Study the style sheets in the Spry assets folder, or click the Customize this
<p>widget link in the Property inspector to display Dreamweaver help, which explains which
<p>style rules to change.
<p><b>Next, let’s move to the server side . . .</b>
<p>This has been a long chapter, crammed with detail, but it’s an important one. You’ll use
<p>forms time and again when building dynamic sites, and making sure that user input is in
<p>the right format saves endless headaches later on. Spry does a lot to help with validation
<p>and is fairly easy to use, but the Dreamweaver interface could still do with some improvement.
<p>However, it’s important to remember that client-side validation is only half the story.
<p><b>Applying a validation widget to an existing drop-down menu</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>292</b>
<p>Because JavaScript can be turned off in the browser, you also need to check user input on
<p>the server side with PHP.
<p>Moreover, forms are useless without a script capable of processing the data. The next
<p>chapter serves as a crash course in PHP basics for readers new to PHP. Then in Chapter 11,
<p>we get down to the nitty-gritty of server-side programming, using PHP to validate user
<p>input and then send it to your mail inbox.
<p>BUILDING ONLINE FORMS AND VALIDATING INPUT
<p><b>293</b>
<p><b>9</b>
<p>10 <b>INTRODUCING THE BASICS OF PHP</b>
<p>This chapter is a cross between a crash course in PHP and a handy reference. It’s aimed at
<p>readers who are completely new to PHP or who may have dabbled without really getting
<p>to grips with the language. The intention is not to teach you all there is to know but to arm
<p>you with sufficient knowledge to dig into Code view to customize Dreamweaver code with
<p>confidence. Dreamweaver’s automatic code generation does a lot of the hard work for
<p>you, but you need to tweak the code to get the best out of it, and when it comes to sending
<p>an email from an online form, you have to do everything yourself.
<p>By the end of this chapter, you’ll learn about
<p>Writing and understanding PHP scripts
<p>Using variables to represent changing values
<p>Understanding the difference between single and double quotes
<p>Organizing related information with arrays
<p>Creating pages that make decisions for themselves
<p>Using loops and functions for repetitive work
<p>If you’re already comfortable with PHP, just glance at the section headings to see what’s
<p>covered, as you might find it useful to refer to this chapter if you need to refresh your
<p>memory about a particular subject. Then move straight to the next chapter and start
<p>coding.
<p>If you’re new to PHP, don’t try to learn everything at one sitting, or your brain is likely to
<p>explode from information overload. On the first reading, look at the headings and maybe
<p>the first paragraph or two under each one to get a general overview. Also read the section
<p>“Understanding PHP error messages.”
<p><b>Introducing the basics of PHP</b>
<p>PHP is a <b>server-side language</b>. This means that the web server processes your PHP code and
<p>sends only the results—usually as XHTML—to the browser. Because all the action is on the
<p>server, you need to tell it that your pages contain PHP code. This involves two simple steps,
<p>namely:
<p>Give every page a PHP file name extension—the default is .php. Do not use anything
<p>other than .php unless you are told to specifically by your hosting company.
<p>Enclose all PHP code within PHP tags.
<p>The opening tag is &lt;?php and the closing tag is ?&gt;. You may come across &lt;? as a short version
<p>of the opening tag. However, &lt;? doesn’t work on all servers. Stick with &lt;?php, which is
<p>guaranteed to work.
<p><b>Embedding PHP in a web page</b>
<p>When somebody visits your site and requests a PHP page, the server sends it to the PHP
<p>engine, which reads the page from top to bottom looking for PHP tags. XHTML passes
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>296</b>
<p>through untouched, but whenever the PHP engine encounters a &lt;?php tag, it starts
<p>processing your code and continues until it reaches the closing ?&gt; tag. If the PHP code
<p>produces any output, it’s inserted at that point. Then, any remaining XHTML passes
<p>through until another &lt;?php tag is encountered.
<p>PHP doesn’t always produce direct output for the browser. It may, for instance, check the
<p>contents of form input before sending an email message or inserting information into a
<p>database. So some code blocks are placed above or below the main XHTML code. Code
<p>that produces direct output, however, always goes where you want the output to be
<p>displayed.
<p>A typical PHP page uses some or all of the following elements:
<p>Variables to act as placeholders for unknown or changing values
<p>Arrays to hold multiple values
<p>Conditional statements to make decisions
<p>Loops to perform repetitive tasks
<p>Functions to perform preset tasks
<p><b>Ending commands with a semicolon</b>
<p>PHP is written as a series of commands or statements. Each <b>statement </b>normally tells the
<p>PHP engine to perform a particular action, and it must always be followed by a semicolon,
<p>like this:
<p>&lt;?php
<p><i>do this;</i>
<p><i>now do something else;</i>
<p><i>finally, do that;</i>
<p>?&gt;
<p>PHP is not like JavaScript or ActionScript. It won’t automatically assume there should be a
<p>semicolon at the end of a line if you leave it out. This has a nice side effect: you can spread
<p>long statements over several lines and lay out your code for ease of reading. PHP, like
<p>XHTML, ignores whitespace in code. Instead, it relies on semicolons to indicate where one
<p>command ends and the next one begins.
<p><i>To save space, I won’t always surround code samples with PHP tags.</i>
<p><i>You can have as many PHP code blocks as you like on a page, but they</i>
<p><i>cannot be nested inside each other.</i>
<p>INTRODUCING THE BASICS OF PHP
<p><b>297</b>
<p><b>10</b>
<p><b>Using variables to represent changing values</b>
<p>A <b>variable </b>is simply a name that you give to something that may change or that you don’t
<p>know in advance. The <i>name </i>that you give to a variable remains constant, but the <i>value</i>
<p>stored in the variable can be changed at any time.
<p>Although this concept sounds abstract, we use variables all the time in everyday life. When
<p>you meet somebody for the first time, one of the first things you ask is, “What’s your
<p>name?” It doesn’t matter whether the person you’ve just met is Tom, Dick, or Harry, the
<p>word “name” remains constant, but the value we store in it varies for different people.
<p>Similarly, with your bank account, money goes in and out all of the time (mostly out, it
<p>seems), but it doesn’t matter whether you’re scraping the bottom of the barrel or as rich
<p>as Croesus, the amount of money in your account is always referred to as the balance.
<p><b>Naming variables</b>
<p>You can choose just about anything you like as the name for a variable, as long as you keep
<p>the following rules in mind:
<p>Variables always begin with $ (a dollar sign).
<p>The first character after the dollar sign cannot be a number.
<p>No spaces or punctuation are allowed, except for the underscore (_).
<p>Variable names are case sensitive: $name and $Name are not the same.
<p>A variable’s name should give some indication of what it represents: $name, $email, and
<p>$totalPrice are good examples. Because you can’t use spaces in variable names, it’s a
<p>good idea to capitalize the first letter of the second or subsequent words when combining
<p>them (sometimes called <b>camel case</b>). Alternatively, you can use an underscore (e.g.,
<p>$total_price).
<p>Don’t try to save time by using really short variables. Using $n, $e, and $tp instead of
<p>descriptive ones makes code harder to understand. More important, it makes errors more
<p>difficult to spot.
<p><b>Assigning values to variables</b>
<p>Variables get their values from a variety of sources, including the following:
<p>User input through online forms
<p>A database
<p>An external source, such as a news feed or XML file
<p>The result of a calculation
<p>Direct inclusion in the PHP code
<p><i>Although you have considerable freedom in the choice of variable names, you</i>
<p><i>can’t use </i>$this<i>, because it has a special meaning in PHP object-oriented programming.</i>
<p><i>It’s also advisable to avoid using any of the keywords listed at</i>
<p>www.php.net/manual/en/reserved.php<i>.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>298</b>
<p>Wherever the value comes from, it’s always assigned in the same way with an equal sign
<p>(=), like this:
<p>$variable = <i>value</i>;
<p>Because it assigns a value, the equal sign is called the <b>assignment operator</b>. Although it’s an
<p>equal sign, get into the habit of thinking of it as meaning “is set to” rather than “equals.”
<p>This is because PHP uses two equal signs (==) to mean “equals”—something that catches
<p>out a lot of beginners (experienced PHP programmers are not immune to the occasional
<p>lapse, either).
<p>Use the following rules when assigning a value to a variable:
<p>Strings must be enclosed in single or double quotes (the distinction between the
<p>different types of quotes is explained later in the chapter).
<p>Numbers should not be in quotes—enclosing a number in quotes turns it into a
<p>string.
<p>You can also use a variable to assign a value to another variable, for example:
<p>$name = &#8216;David Powers&#8217;;
<p>$author = $name; // both $author and $name are now &#8216;David Powers&#8217;
<p>If the value of $name changes subsequently, it doesn’t affect the value of $author. As this
<p>example shows, you don’t use quotes around a variable when assigning its value to
<p>another. However, as long as you use double quotes, you can embed a variable in a string
<p>like this:
<p>$blurb = &#8220;$author has written several best-selling books on PHP.&#8221;;
<p>The value of $blurb is now “David Powers has written several best-selling books on PHP.”
<p>There’s a more detailed description on the use of variables with double quotes in
<p>“Choosing single or double quotation marks” later in the chapter.
<p><b>Displaying PHP output</b>
<p>The most common ways of displaying dynamic output in the browser are to use echo or
<p>print. The differences between the two are so subtle you can regard them as identical. I
<p>prefer echo, because it’s one fewer letter to type. It’s also the style used by Dreamweaver.
<p>Put echo (or print) in front of a variable, number, or string like this to output it to the
<p>browser:
<p>$name = &#8216;David&#8217;;
<p>echo $name; // displays David
<p>echo 5; // displays 5
<p>echo &#8216;David&#8217;; // displays David
<p>You may see scripts that use parentheses with echo and print, like this:
<p>echo(&#8216;David&#8217;); // displays David
<p>print(&#8216;David&#8217;); // displays David
<p>INTRODUCING THE BASICS OF PHP
<p><b>299</b>
<p><b>10</b>
<p>The parentheses make no difference. Unless you enjoy typing purely for the sake of it,
<p>leave them out.
<p><b>Commenting scripts for clarity and debugging</b>
<p>Even if you’re an expert programmer, code is not always as immediately understandable as
<p>something written in your own human language. That’s where comments can be a lifesaver.
<p>You may understand what the code does five minutes after creating it, but when you
<p>come back to maintain it in six months’ time—or if you have to maintain someone else’s
<p>code—you’ll be grateful for well-commented code.
<p>In PHP, there are three ways to add comments. The first will be familiar to you if you write
<p>JavaScript. Anything on a line following a double slash is regarded as a comment and will
<p>not be processed.
<p><b>// Display the name</b>
<p>echo $name;
<p>You can also use the hash sign (#) in place of the double slash.
<p><b># Display the name</b>
<p>echo $name;
<p>Either type of comment can go to the side of the code, as long as it doesn’t go onto the
<p>next line.
<p>echo $name; <b>// This is a comment</b>
<p>echo $name; <b># This is another comment</b>
<p>The third style allows you to stretch comments over several lines by sandwiching them
<p>between /* and */ (just like CSS comments).
<p><b>/* </b>You might want to use this sort of comment to explain
<p>the whole purpose of a script. Alternatively, it&#8217;s a
<p>convenient way to disable part of a script temporarily.
<p><b>*/</b>
<p>As the previous example explains, comments serve a dual purpose: they not only allow you
<p>to sprinkle your scripts with helpful reminders of what each section of code is for; they can
<p>also be used to disable a part of a script temporarily. This is extremely useful when you are
<p>trying to trace the cause of an error.
<p><i>The important thing to remember about </i>echo <i>and </i>print <i>is that they work only with</i>
<p><i>variables that contain a single value. You cannot use them to display more complex</i>
<p><i>structures that are capable of storing multiple values.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>300</b>
<p><b>Choosing single or double quotation marks</b>
<p>As I mentioned earlier, strings must always be enclosed in single or double quotes. If all
<p>you’re concerned about is what ends up on the screen, most of the time it doesn’t matter
<p>which quotes you use, but behind the scenes, PHP uses single and double quotes in very
<p>different ways.
<p>Anything between single quotation marks is treated as plain text.
<p>Anything between double quotation marks is processed.
<p>Quotation marks need to be in matching pairs. If a string begins with a single quote, PHP
<p>looks for the next single quote and regards that as the end of the string. Since an apostrophe
<p>uses the same character as a single quote, this presents a problem. A similar problem
<p>arises when a string in double quotes contains double quotes. The best way to explain this
<p>is with a practical example.
<p>This simple exercise demonstrates the difference between single and double quotes and
<p>what happens when a conflict arises with an apostrophe or double quotes inside a string.
<p><b>1. </b>Create a new PHP page called quotes.php in workfiles/ch10. If you just want to
<p>look at the finished code, use quotes.php in examples/ch10.
<p><b>2. </b>Switch to Code view, and type the following code between the &lt;body&gt; tags:
<p>&lt;?php
<p>$name = &#8216;David Powers&#8217;;
<p>echo &#8216;Single quotes: The author is $name&lt;br /&gt;&#8217;;
<p>echo &#8220;Double quotes: The author is $name&#8221;;
<p>?&gt;
<p><b>3. </b>Save the page, and load it into a browser. As you can see from the following
<p>screenshot, $name is treated as plain text in the first line, but is processed and
<p>replaced with its value in the second line, which uses double quotes.
<p><i>To display the output on separate lines, you have to include XHTML tags, such as</i>
<p>&lt;br /&gt;<i>, because </i>echo <i>outputs only the values passed to it—nothing more.</i>
<p><b>Experimenting with quotes</b>
<p>INTRODUCING THE BASICS OF PHP
<p><b>301</b>
<p><b>10</b>
<p><b>4. </b>Change the text slightly in lines 3 and 4 of the code, as follows:
<p>echo &#8216;Single quotes: The author<b>&#8217;s name </b>is $name&lt;br /&gt;&#8217;;
<p>echo &#8220;Double quotes: The author<b>&#8217;s name </b>is $name&#8221;;
<p>As you type, the change in Dreamweaver syntax coloring should alert you to a
<p>problem, but save the page nevertheless, and view it in a browser (it’s quotes2.php
<p>in examples/ch10). You should see something like this:
<p>As far as PHP is concerned, an apostrophe and a single quote are the same thing,
<p>and quotes must always be in matching pairs. What’s happened is that the apostrophe
<p>in author&#8217;s has been regarded as the closing quote for the first line; what was
<p>intended as the closing quote of the first line becomes a second opening quote;
<p>and the apostrophe in the second line becomes the second closing quote. All quite
<p>different from what was intended—and if you’re confused, is it any wonder that
<p>PHP is unable to work out what’s meant to be going on?
<p><b>5. </b>To solve the problem, insert a backslash in front of the apostrophe in the first sentence,
<p>like this (see quotes3.php in examples/ch10):
<p>echo &#8216;Single quotes: The author<b>\</b>&#8217;s name is $name&lt;br /&gt;&#8217;;
<p>You should now see the syntax coloring revert to normal. If you view the result in a
<p>browser, it should display correctly like this:
<p><i>The meaning of parse error and other error messages is explained in “Understanding</i>
<p><i>PHP error messages” at the end of the chapter.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>302</b>
<p><b>Using escape sequences in strings</b>
<p>Using a backslash like this is called an <b>escape sequence</b>. It tells PHP to treat a character in
<p>a special way. Double quotes within a double-quoted string? You guessed it—escape them
<p>with a backslash.
<p>echo &#8220;Swift&#8217;s \&#8221;Gulliver&#8217;s Travels\&#8221;"; // displays the double quotes
<p>The next line of code achieves exactly the same thing, but by using a different combination
<p>of quotes:
<p>echo &#8216;Swift\&#8217;s &#8220;Gulliver\&#8217;s Travels&#8221;&#8216;;
<p>So what happens when you want to include a literal backslash? You escape it with a backslash
<p>(\\).
<p>The backslash (\\) and the single quote (\&#8217;) are the only escape sequences that work in a
<p>single-quoted string. Because double quotes are a signal to PHP to process any variables
<p>contained within a string, there are many more escape sequences for double-quoted
<p>strings. Most of them are to avoid conflicts with characters that are used with variables,
<p>but three of them have special meanings: \n inserts a new line character, \r inserts a carriage
<p>return (needed mainly for Windows), and \t inserts a tab. Table 10-1 lists the main
<p>escape sequences supported by PHP.
<p><b>Table 10-1. </b>The main PHP escape sequences
<p><b>Escape sequence Character represented in double-quoted string</b>
<p>\&#8221; Double quote
<p>\n New line
<p>\r Carriage return
<p>\t Tab
<p>\\ Backslash
<p>\$ Dollar sign
<p>\{ Opening curly brace
<p>\} Closing curly brace
<p>\[ Opening square bracket
<p>\] Closing square bracket
<p><i>When creating strings, the outside pair of quotes must match—any quotes of the</i>
<p><i>same style inside the string must be escaped with a backslash. However, putting a</i>
<p><i>backslash in front of the opposite style of quote will result in the backslash being displayed.</i>
<p><i>To see the effect, put a backslash in front of the apostrophe in the doubledquoted</i>
<p><i>string in the previous exercise.</i>
<p>INTRODUCING THE BASICS OF PHP
<p><b>303</b>
<p><b>10</b>
<p>Double quotes are obviously very useful, so why not use them all the time? Many people
<p>do, but the official recommendation is to use the quoting method that uses the least processing
<p>power—and that’s usually single quotes. When PHP sees an opening double quote,
<p>it tries to process any variables first. If it finds none, it goes back and treats the string as
<p>plain text. On short scripts, such as in this book, the difference in processing time is negligible,
<p>but it can make a difference on long, complex scripts.
<p><b>Joining strings together</b>
<p>PHP has a rather unusual way of joining strings. Although many other computer languages
<p>use the plus sign (+), PHP uses a period, dot, or full stop (.) like this:
<p>$firstName = &#8216;David&#8217;;
<p>$lastName = &#8216;Powers&#8217;;
<p>echo $firstName.$lastName; // displays DavidPowers
<p>As the comment in the final line of code indicates, when two strings are joined like this,
<p>PHP leaves no gap between them. Don’t be fooled into thinking that adding a space after
<p>the period will do the trick. It won’t. You can put as much space on either side of the
<p>period as you like; the result will always be the same, because PHP ignores whitespace in
<p>code. You must either include a space in one of the strings or insert the space as a string
<p>in its own right, like this:
<p>echo $firstName.&#8217; &#8216;.$lastName; // displays David Powers
<p><b>Adding to an existing string</b>
<p>Very often, you need to add more text at the end of an existing string. One way to do it is
<p>like this:
<p>$author = &#8216;David&#8217;;
<p>$author = $author.&#8217; Powers&#8217;; // $author is now &#8216;David Powers&#8217;
<p>Basically, this concatenates Powers (with a leading space) on the end of $author, and then
<p>assigns everything back to the original variable.
<p>Adding something to an existing variable is such a common operation, PHP offers a shorthand
<p>way of doing it—with the <b>combined concatenation operator</b>. Don’t worry about the
<p>highfalutin name, it’s just a period followed by an equal sign. It works like this:
<p><i>The period—or </i><i><b>concatenation operator</b></i><i>, to give it its correct name—can be difficult</i>
<p><i>to spot among a lot of other code. Make sure the font size in your script editor is large</i>
<p><i>enough to read without straining to see the difference between periods and commas.</i>
<p><i>The escape sequences listed in Table 10-1, with the exception of </i>\\<i>, work only in double-</i>
<p><i>quoted strings. If you use them in a single-quoted string, they are treated as a literal</i>
<p><i>backslash followed by the second character.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>304</b>
<p>$author = &#8216;David&#8217;;
<p>$author <b>.= </b>&#8216; Powers&#8217;; // $author is now &#8216;David Powers&#8217;
<p>There should be no space between the period and equal sign. You’ll find this shorthand
<p>very useful when building the string to form the body of an email message in the next
<p>chapter.
<p><b>Using quotes efficiently</b>
<p>Award yourself a bonus point if you spotted a better way of adding the space between
<p>$firstName and $lastName in the last example. Yes, that’s right . . . Use double quotes,
<p>like this:
<p>echo &#8220;$firstName $lastName&#8221;; // displays David Powers
<p>Choosing the most efficient combination of quotation marks isn’t easy when you first start
<p>working with PHP, but it can make your code a lot easier to use. Many beginners stick
<p>rigidly to double quotes for everything, and end up peppering their scripts with backslashes
<p>to escape double quotes in the middle of strings. It not only makes scripts difficult
<p>to read, but usually results in PHP errors or broken XHTML.
<p><b>Special cases: true, false and null</b>
<p>Although text should be enclosed in quotes, three special cases—true, false, and null—
<p>should never be enclosed in quotes unless you want to treat them as genuine text (or
<p>strings). The first two mean what you would expect; the last one, null, means “nothing” or
<p>“no value.”
<p>PHP makes decisions on the basis of whether something evaluates to true or false.
<p>Putting quotes around false has surprising consequences. The following code:
<p>$OK = &#8216;false&#8217;;
<p>does exactly the opposite of what you might expect: it makes $OK true! Why? Because the
<p>quotes around false turn it into a string, and PHP treats strings as true. The other thing
<p>to note about true, false, and null is that they are <i>case insensitive</i>. The following examples
<p>are all valid:
<p>$OK = TRUE;
<p>$OK = tRuE;
<p>$OK = true;
<p><i>How long can a string be? As far as PHP is concerned, there’s no limit. In practice, you</i>
<p><i>are likely to be constrained by other factors, such as server memory; but in theory,</i>
<p><i>you could store the whole of </i>War and Peace <i>in a string variable.</i>
<p>INTRODUCING THE BASICS OF PHP
<p><b>305</b>
<p><b>10</b>
<p><b>Working with numbers</b>
<p>PHP can do a lot with numbers—from simple addition to complex math. Numbers can
<p>contain a decimal point or use scientific notation, but they must contain no other punctuation.
<p>Never use a comma as a thousands separator. The following examples show the
<p>right and wrong ways to assign a large number to a variable:
<p>$million = 1000000; // this is correct
<p>$million = 1,000,000; // this generates an error
<p>$million = 1e6; // this is correct
<p>$million = 1e 6; // this generates an error
<p>When using scientific notation, the letter “e” can be uppercase or lowercase and optionally
<p>followed by a plus or minus sign. No spaces are permitted.
<p><b>Performing calculations</b>
<p>The standard arithmetic operators all work the way you would expect, although some of
<p>them look slightly different from those you learned at school. For instance, an asterisk (*)
<p>is used as the multiplication sign, and a forward slash (/) is used to indicate division.
<p>Table 10-2 shows examples of how the standard arithmetic operators work. To demonstrate
<p>their effect, the following variables have been set:
<p>$x = 20;
<p>$y = 10;
<p>$z = 3;
<p><b>Table 10-2. </b>Arithmetic operators in PHP
<p><b>Operation Operator Example Result</b>
<p>Addition + $x + $y 30
<p>Subtraction &#8211; $x &#8211; $y 10
<p>Multiplication * $x * $y 200
<p>Division / $x / $y 2
<p>Modulo division % $x % $z 2
<p>Increment (add 1) ++ $x++ 21
<p>Decrement (subtract 1) &#8212; $y&#8211; 9
<p>You may not be familiar with the modulo operator. This returns the remainder of a division,
<p>as follows:
<p>26 % 5 // result is 1
<p>26 % 27 // result is 26
<p>10 % 2 // result is 0
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>306</b>
<p>A quirk with the modulo operator in PHP is that it converts both numbers to integers
<p>before performing the calculation. Consequently, if $z is 4.5 in Table 10-2, it gets rounded
<p>up to 5, making the result 0, not 2, as you might expect. (Yes, it was a mistake in my previous
<p>books.)
<p>A practical use of the modulo operator is to work out whether a number is odd or even.
<p>$number % 2 will always produce 0 or 1.
<p>The increment (++) and decrement (&#8211;) operators can come either before or after the
<p>variable. When they come before the variable, 1 is added to or subtracted from the value
<p>before any further calculation is carried out. When they come after the variable, the main
<p>calculation is carried out first, and then 1 is either added or subtracted. Since the dollar
<p>sign is an integral part of the variable name, the increment and decrement operators go
<p>before the dollar sign when used in front:
<p>++$x
<p>&#8211;$y
<p>You can set your own values for $x, $y, and $z in calculation.php in examples/ch10 to
<p>test the arithmetic operators in action. The page also demonstrates the difference
<p>between putting the increment and decrement operators before and after the variable.
<p>As noted earlier, numbers should not normally be enclosed in quotes, although PHP will
<p>usually convert to its numeric equivalent a string that contains only a number or that
<p>begins with a number.
<p>Calculations in PHP follow exactly the same rules as standard arithmetic. Table 10-3 summarizes
<p>the precedence of arithmetic operators.
<p><b>Table 10-3. </b>Precedence of arithmetic operators
<p><b>Precedence Group Operators Rule</b>
<p>Highest Parentheses () Operations contained within
<p>parentheses are evaluated first. If
<p>these expressions are nested, the
<p>innermost is evaluated foremost.
<p>Next Multiplication * / % These operators are evaluated
<p>and division next. If an expression contains
<p>two or more operators, they are
<p>evaluated from left to right.
<p>Lowest Addition and + &#8211; These are the final operators to
<p>subtraction be evaluated in an expression.
<p>If an expression contains two
<p>or more operators, they are
<p>evaluated from left to right.
<p>If in doubt, use parentheses all the time to group the parts of a calculation that you want
<p>to make sure are performed as a single unit.
<p>INTRODUCING THE BASICS OF PHP
<p><b>307</b>
<p><b>10</b>
<p><b>Combining calculations and assignment</b>
<p>You will often want to perform a calculation on a variable and assign the result back to the
<p>same variable. PHP offers the same convenient shorthand for arithmetic calculations as for
<p>strings. Table 10-4 shows the main combined assignment operators and their use.
<p><b>Table 10-4. </b>Combined arithmetic assignment operators used in PHP
<p><b>Operator Example Equivalent to</b>
<p>+= $a += $b $a = $a + $b
<p>-= $a -= $b $a = $a &#8211; $b
<p>*= $a *= $b $a = $a * $b
<p>/= $a /= $b $a = $a / $b
<p>%= $a %= $b $a = $a % $b
<p>Don’t forget that <b>the plus sign is used in PHP only as an arithmetic operator</b>.
<p><b>Addition</b>: Use += as the combined assignment operator
<p><b>Strings</b>: Use .= as the combined assignment operator
<p><b>Using arrays to store multiple values</b>
<p>Arrays are an important—and useful—part of PHP. You met one of PHP’s built-in arrays,
<p>$_POST, in the last chapter, and you’ll work with it a lot more through the rest of this book.
<p>Arrays are also used extensively with a database, as you fetch the results of a search in a
<p>series of arrays.
<p>An array is a special type of variable that stores multiple values rather like a shopping list.
<p>Although each item might be different, you can refer to them collectively by a single
<p>name. Figure 10-1 demonstrates this concept: the variable $shoppingList refers collectively
<p>to all five items—wine, fish, bread, grapes, and cheese.
<p>Individual items—or <b>array elements</b>—are identified by means of a number in square
<p>brackets immediately following the variable name. PHP assigns the number automatically,
<p>but it’s important to note that the numbering always begins at 0. So the first item in the
<p>array, wine, is referred to as $shoppingList[0], not $shoppingList[1]. And although
<p>there are five items, the last one (cheese) is $shoppingList[4]. The number is referred to
<p>as the array <b>key </b>or <b>index</b>, and this type of array is called an <b>indexed array</b>.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>308</b>
<p><b>Figure 10-1. </b>Arrays are variables that store multiple items, just like a shopping list.
<p>Instead of declaring each array element individually, you can declare the variable name
<p>once, and assign all the elements by passing them as a comma-separated list to array(),
<p>like this:
<p>$shoppingList = array(&#8216;wine&#8217;, &#8216;fish&#8217;, &#8216;bread&#8217;, &#8216;grapes&#8217;, &#8216;cheese&#8217;);
<p>PHP numbers each array element automatically, so this creates the same array as in
<p>Figure 10-1. To add a new element to the end of the array, use a pair of empty square
<p>brackets like this:
<p>$shoppingList[] = &#8216;coffee&#8217;;
<p>PHP uses the next number available, so this becomes $shoppingList[5].
<p><b>Using names to identify array elements</b>
<p>Numbers are fine, but it’s often more convenient to give array elements meaningful
<p>names. For instance, an array containing details of this book might look like this:
<p>$book['title'] = &#8216;Essential Guide to Dreamweaver CS3&#8242;;
<p>$book['author'] = &#8216;David Powers&#8217;;
<p>$book['publisher'] = &#8216;friends of ED&#8217;;
<p>$book['ISBN13'] = &#8216;978-1-59059-859-7&#8242;;
<p><i>The comma must go outside the quotes, unlike American typographic practice.</i>
<p><i>For ease of reading, I have inserted a space following each comma, but it’s not</i>
<p><i>necessary to do so.</i>
<p>INTRODUCING THE BASICS OF PHP
<p><b>309</b>
<p><b>10</b>
<p>This type of array is called an <b>associative array</b>. Note that the array key is enclosed in
<p>quotes (single or double, it doesn’t matter). It mustn’t contain any spaces or punctuation,
<p>except for the underscore.
<p>The shorthand way of creating an associative array uses the =&gt; operator (an equal sign followed
<p>by a greater-than sign) to assign a value to each array key. The basic structure looks
<p>like this:
<p><i>$arrayName </i>= array(&#8216;<i>key1</i>&#8216; =&gt; &#8216;<i>element1</i>&#8216;, &#8216;<i>key2</i>&#8216; =&gt; &#8216;<i>element2</i>&#8216;);
<p>So, this is the shorthand way to build the $book array:
<p>$book = array(&#8216;title&#8217; =&gt; &#8216;Essential Guide to Dreamweaver CS3&#8242;,
<p>&#8216;author&#8217; =&gt; &#8216;David Powers&#8217;,
<p>&#8216;publisher&#8217; =&gt; &#8216;friends of ED&#8217;,
<p>&#8216;ISBN13&#8242; =&gt; &#8216;978-1-59059-859-7&#8242;);
<p>It’s not essential to align the =&gt; operators like this, but it makes code easier to read and
<p>maintain.
<p><b>Inspecting the contents of an array with print_r()</b>
<p>As you saw in the previous chapter, you can inspect the contents of an array using
<p>print_r(). This is the code that you inserted at the bottom of feedback.php:
<p>&lt;pre&gt;
<p>&lt;?php if ($_POST) {print_r($_POST);} ?&gt;
<p>&lt;/pre&gt;
<p>It displays the contents of the array like this:
<p>The &lt;pre&gt; tags are simply to make the output more readable. What really matters here is
<p>that print_r() displays the contents of an array. As explained earlier, echo and print
<p>work only with variables that contain a single value. However, the only real value of
<p>print_r() is to inspect the contents of an array for testing purposes. It’s no good in a live
<p>web page. To display the contents of an array in normal circumstances, you need to use a
<p><i>Technically speaking, all arrays in PHP are associative. This means that you can</i>
<p><i>use both numbers and strings as array keys in the same array. Don’t do it,</i>
<p><i>though, as it can produce unexpected results. It’s safer to treat indexed and</i>
<p><i>associative arrays as different types.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>310</b>
<p>loop. This gives you access to each array element one at a time. Once you get to an element
<p>that contains a single value, you can use echo or print to display its contents. Loops
<p>are covered a little later.
<p><b>Making decisions</b>
<p>Decisions, decisions, decisions . . . Life is full of decisions. So is PHP. They give it the ability
<p>to display different output according to circumstances. Decision making in PHP uses <b>conditional</b>
<p><b>statements</b>. The most common of these uses if and closely follows the structure
<p>of normal language. In real life, you may be faced with the following decision (admittedly
<p>not very often if you live in Britain):
<p>If the weather&#8217;s hot, I&#8217;ll go to the beach.
<p>In PHP pseudo-code, the same decision looks like this:
<p><i>if (the weather&#8217;s hot) {</i>
<p><i>I&#8217;ll go to the beach;</i>
<p><i>}</i>
<p>The condition being tested goes inside parentheses, and the resulting action goes between
<p>curly braces. This is the basic decision-making pattern:
<p>if (<i>condition is true</i>) {
<p>// code to be executed if condition is true
<p>}
<p>The code inside the curly braces is executed <i>only </i>if the condition is true. If it’s false, PHP
<p>ignores everything between the braces and moves on to the next section of code. How
<p>PHP determines whether a condition is true or false is described in the following section.
<p>Sometimes, the if statement is all you need, but you often want a default action to be
<p>invoked. To do this, use else, like this:
<p>if (<i>condition is true</i>) {
<p>// code to be executed if condition is true
<p>}
<p>else {
<p>// default code to run if condition is false
<p>}
<p><i>Confusion alert: I mentioned earlier that statements must always be followed by a</i>
<p><i>semicolon. This applies only to the statements (or commands) inside the curly braces.</i>
<p><i>Although called a conditional statement, this decision-making pattern is one of PHP’s</i>
<p><i>control structures, and it shouldn’t be followed by a semicolon. Think of the semicolon</i>
<p><i>as a command that means “do it.” The curly braces surround the command</i>
<p><i>statements and keep them together as a group.</i>
<p>INTRODUCING THE BASICS OF PHP
<p><b>311</b>
<p><b>10</b>
<p>What if you want more alternatives? One way is to add more if statements. PHP will test
<p>them, and as long as you finish with else, at least one block of code will run. However, it’s
<p>important to realize that <i>all </i>if statements will be tested, and the code will be run in every
<p>single one where the condition equates to true. If you want only one code block to be
<p>executed, use elseif like this:
<p>if (<i>condition is true</i>) {
<p>// code to be executed if first condition is true
<p>}
<p>elseif (<i>second condition is true</i>) {
<p>// code to be executed if first condition fails
<p>// but second condition is true
<p>else {
<p>// default code to run if both conditions are false
<p>}
<p>You can use as many elseif clauses in a conditional statement as you like. It’s important
<p>to note that only the first one that equates to true will be executed; all others will be
<p>ignored, even if they’re also true. This means you need to build conditional statements in
<p>the order of priority that you want them to be evaluated. It’s strictly a first-come, firstserved
<p>hierarchy.
<p><b>The truth according to PHP</b>
<p>Decision making in PHP conditional statements is based on the mutually exclusive <b>Boolean</b>
<p><b>values</b>, true and false (the name comes from a nineteenth century mathematician,
<p>George Boole, who devised a system of logical operations that subsequently became the
<p>basis of much modern-day computing). If the condition equates to true, the code within
<p>the conditional block is executed. If false, it’s ignored. Whether a condition is true or
<p>false is determined in one of the following ways:
<p>A variable set explicitly to true or false
<p>A value PHP interprets implicitly as true or false
<p>The comparison of two values
<p><b>Explicit true or false values </b>This is straightforward. If a variable is assigned the value true
<p>or false and then used in a conditional statement, the decision is based on that value. As
<p>explained earlier, true and false are case insensitive and must <i>not </i>be enclosed in quotes.
<p><b>Implicit true or false values </b>PHP regards the following as false:
<p>The case-insensitive keywords false and null
<p>Zero as an integer (0), a floating-point number (0.0), or a string (&#8216;0&#8242; or &#8220;0&#8243;)
<p>An empty string (single or double quotes with no space between them)
<p>An empty array
<p><i>Although </i>elseif <i>is normally written as one word, you can use </i>else if
<p><i>as separate words.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>312</b>
<p>An object with no values or functions (PHP 4 only)
<p>A SimpleXML object created from empty tags
<p>All other values equate to true.
<p>How comparisons equate to true or false is described in the next section.
<p><b>Using comparisons to make decisions</b>
<p>Conditional statements often depend on the comparison of two values. Is this bigger than
<p>that? Are they both the same? If the comparison is true, the conditional statement is executed.
<p>If not, it’s ignored.
<p>To test for equality, PHP uses two equal signs (==) like this:
<p>if ($status == &#8216;administrator&#8217;) {
<p>// send to admin page
<p>}
<p>else {
<p>// refuse entry to admin area
<p>}
<p>Size comparisons are performed using the mathematical symbols for less than (&lt;) and
<p>greater than (&gt;). Let’s say you’re checking the size of a file before allowing it to be
<p>uploaded to your server. You could set a maximum size of 50KB like this:
<p>if ($bytes &gt; 51200) {
<p>// display error message and abandon upload
<p>}
<p>else {
<p>// continue upload
<p>}
<p><b>Comparison operators </b>These compare two values (known as <b>operands </b>because they
<p>appear on either side of an operator). If both values pass the test, the result is true (or to
<p>use the technical expression, it <b>returns </b>true). Otherwise, it returns false. Table 10-5 lists
<p>the comparison operators used in PHP.
<p><i>Don’t use a single equal sign in the first line like this:</i>
<p>if ($status = &#8216;administrator&#8217;) {
<p><i>Doing so will open the admin area of your website to everyone. Why? Because</i>
<p><i>this automatically sets the value of </i>$status <i>to </i>administrator<i>; it doesn’t compare</i>
<p><i>the two values. To compare values, you must use two equal signs. It’s an</i>
<p><i>easy mistake to make, but one with potentially disastrous consequences.</i>
<p><i>This definition explains why </i>&#8220;false&#8221; <i>(in quotes) is interpreted by PHP as</i>
<p>true<i>. The value </i>–1 <i>is also treated as </i>true <i>in PHP.</i>
<p>INTRODUCING THE BASICS OF PHP
<p><b>313</b>
<p><b>10</b>
<p><b>Table 10-5. </b>PHP comparison operators used for decision making
<p><b>Symbol Name Use</b>
<p>== Equality Returns true if both operands have the
<p>same value; otherwise, returns false.
<p>!= Inequality Returns true if both operands have
<p>different values; otherwise, returns false.
<p>&lt;&gt; Inequality This has the same meaning as !=. It’s rarely
<p>used in PHP but has been included here for
<p>the sake of completeness.
<p>=== Identical Determines whether both operands are
<p>identical. To be considered identical, they
<p>must not only have the same value but also
<p>be of the same datatype (for example, both
<p>floating-point numbers).
<p>!== Not identical Determines whether both operands are not
<p>identical (according to the same criteria as
<p>the previous operator).
<p>&gt; Greater than Determines whether the operand on the left
<p>is greater in value than the one on the right.
<p>&gt;= Greater than or equal to Determines whether the operand on the left
<p>is greater in value than or equal to the one
<p>on the right.
<p>&lt; Less than Determines whether the operand on the left
<p>is less in value than the one on the right.
<p>&lt;= Less than or equal to Determines whether the operand on the left
<p>is less in value than or equal to the one on
<p>the right.
<p><b>Testing more than one condition</b>
<p>Frequently, comparing two values is not enough. PHP allows you to set a series of conditions
<p>using <b>logical operators </b>to specify whether all, or just some, need to be fulfilled.
<p>All the logical operators in PHP are listed in Table 10-6. <b>Negation</b>—testing that the opposite
<p>of something is true—is also considered a logical operator, although it applies to
<p>individual conditions rather than a series.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>314</b>
<p><b>Table 10-6. </b>Logical operators used for decision making in PHP
<p><b>Symbol Name Use</b>
<p>&amp;&amp; Logical AND Evaluates to true if both operands are true. If the lefthand
<p>operand evaluates to false, the right-hand
<p>operand is never tested.
<p>and Logical AND Exactly the same as &amp;&amp;, but it takes lower precedence.
<p>|| Logical OR Evaluates to true if either operand is true; otherwise,
<p>returns false. If the left-hand operand returns true,
<p>the right-hand operand is never tested.
<p>or Logical OR Exactly the same as ||, but it takes lower precedence.
<p>xor Exclusive OR Evaluates to true if only one of the two operands
<p>returns true. If both are true or both are false, it
<p>evaluates to false.
<p>! Negation Tests whether something is not true.
<p>Technically speaking, there is no limit to the number of conditions that can be tested. Each
<p>condition is considered in turn from left to right, and as soon as a defining point is
<p>reached, no further testing is carried out. When using &amp;&amp; or <i>and</i>, every condition must be
<p>fulfilled, so testing stops as soon as one turns out to be false. Similarly, when using || or
<p><i>or</i>, only one condition needs to be fulfilled, so testing stops as soon as one turns out to
<p>be true.
<p>$a = 10;
<p>$b = 25;
<p>if ($a &gt; 5 &amp;&amp; $b &gt; 20) // returns true
<p>if ($a &gt; 5 || $b &gt; 30) // returns true, $b never tested
<p>The implication of this is that when you need all conditions to be met, you should design
<p>your tests with the condition most likely to return false as the first to be evaluated. When
<p>you need just one condition to be fulfilled, place the one most likely to return true first.
<p>If you want a particular set of conditions considered as a group, enclose them in parentheses.
<p>if (($a &gt; 5 &amp;&amp; $a &lt; <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> || ($b &gt; 20 &amp;&amp; $b &lt; 40))
<p>Operator precedence is a tricky subject. Stick with &amp;&amp; and ||, rather than <i>and </i>and <i>or</i>, and
<p>use parentheses to group expressions to which you want to give priority. The xor operator
<p>is rarely used.
<p>INTRODUCING THE BASICS OF PHP
<p><b>315</b>
<p><b>10</b>
<p><b>Using the switch statement for decision chains</b>
<p>The switch statement offers an alternative to if . . . else for decision making. The
<p>basic structure looks like this:
<p>switch(<i>variable being tested</i>) {
<p>case <i>value1</i>:
<p><i>statements to be executed</i>
<p>break;
<p>case <i>value2</i>:
<p><i>statements to be executed</i>
<p>break;
<p>default:
<p><i>statements to be executed</i>
<p>}
<p>The case keyword indicates possible matching values for the variable passed to switch().
<p>When a match is made, every subsequent line of code is executed until the break keyword
<p>is encountered, at which point the switch statement comes to an end.
<p>Dreamweaver uses a switch statement in the GetSQLValueString() function, which it
<p>inserts into pages that insert or update records in a database.
<p>The main points to note about switch are as follows:
<p>The expression following the case keyword must be a number or a string.
<p>You can’t use comparison operators with case. So case &gt; 100: isn’t allowed.
<p>Each block of statements should normally end with break, unless you specifically
<p>want to continue executing code within the switch statement.
<p>You can group several instances of the case keyword together to apply the same
<p>block of code to them.
<p>If no match is made, any statements following the default keyword will be executed.
<p>If no default has been set, the switch statement will exit silently and continue
<p>with the next block of code.
<p><b>Using the conditional operator</b>
<p>The <b>conditional operator </b>(?:) is a shorthand method of representing a simple conditional
<p>statement. The basic syntax looks like this:
<p><i>condition ? value if true : value if false;</i>
<p>What this means is that, if the condition to the left of the question mark is true, the value
<p>immediately to the right of the question mark is used. However, if the condition evaluates
<p>to false, the value to the right of the colon is used instead. Here is an example of it in use:
<p>$age = 17;
<p>$fareType = $age &gt; 16 ? &#8216;adult&#8217; : &#8216;child&#8217;;
<p>The conditional operator can be quite confusing when you first encounter it, so let’s break
<p>down this example section by section.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>316</b>
<p>The first line sets the value of $age to 17.
<p>The second line sets the value of $fareType using the conditional operator. The condition
<p>is between the equal sign and the question mark—in other words, $age &gt; 16.
<p>If $age is greater than 16, the condition evaluates to true, so $fareType is set to the value
<p>between the question mark and the colon—in other words, &#8216;adult&#8217;. Otherwise $fareType
<p>is set to the value to the right of the colon—or &#8216;child&#8217;. You can rewrite the second line
<p>using if . . . else like this:
<p>if ($age &gt; 16) {
<p>$fareType = &#8216;adult&#8217;;
<p>}
<p>else {
<p>$fareType = &#8216;child&#8217;;
<p>}
<p>The if . . . else version is much easier to read, but the conditional operator is more
<p>compact, and it’s used frequently by Dreamweaver. Most beginners hate this shorthand,
<p>but you need to understand how it works if you want to customize Dreamweaver code.
<p>Because the conditional operator uses three operands, it’s sometimes called the ternary
<p>operator.
<p><b>Using loops for repetitive tasks</b>
<p>Loops are huge time-savers, because they perform the same task over and over again, yet
<p>involve very little code. They’re frequently used with arrays and database results. You can
<p>step through each item one at a time looking for matches or performing a specific task.
<p>Loops frequently contain conditional statements, so although they’re very simple in structure,
<p>they can be used to create code that processes data in often sophisticated ways.
<p><b>Loops using while and do . . . while</b>
<p>The simplest type of loop is called a while loop. Its basic structure looks like this:
<p>while (<i>condition is true</i>) {
<p><i>do something</i>
<p>}
<p>The following code displays every number from 1 through 100 in a browser (you can see it
<p>in action in while.php in examples/ch10). It begins by setting a variable ($i) to 1, and then
<p>using the variable as a counter to control the loop, as well as display the current number
<p>onscreen.
<p>$i = 1; // set counter
<p>while ($i &lt;= 100) {
<p>echo &#8220;$i&lt;br /&gt;&#8221;;
<p>$i++; // increase counter by 1
<p>}
<p>INTRODUCING THE BASICS OF PHP
<p><b>317</b>
<p><b>10</b>
<p>A variation of the while loop uses the keyword do and follows this basic pattern:
<p>do {
<p><i>code to be executed</i>
<p>} while (<i>condition to be tested</i>);
<p>The only difference between a do . . . while loop and a while loop is that the code
<p>within the do block is executed at least once, even if the condition is never true. The following
<p>code (in dowhile.php in examples/ch10) displays the value of $i once, even
<p>though it’s greater than the maximum expected.
<p>$i = 1000;
<p>do {
<p>echo &#8220;$i&lt;br /&gt;&#8221;;
<p>$i++; // increase counter by 1
<p>} while ($i &lt;= 100);
<p>Dreamweaver uses a do . . . while loop in its Repeat Region server behavior to loop
<p>through the results of a database query (what Dreamweaver calls a recordset) and display
<p>them on your page.
<p>The danger with creating while and do . . . while loops yourself is forgetting to set a
<p>condition that brings the loop to an end or setting an impossible condition. When this
<p>happens, you create an infinite loop that either freezes your computer or causes the
<p>browser to crash.
<p><b>The versatile for loop</b>
<p>The for loop is less prone to generating an infinite loop, because you specify in the first
<p>line how you want the loop to work. The for loop uses the following basic pattern:
<p>for (<i>initialize counter</i>; <i>test</i>; <i>increase or decrease the counter</i>) {
<p><i>code to be executed</i>
<p>}
<p>The three expressions inside the parentheses control the action of the loop (note that they
<p>are separated by semicolons, not commas):
<p>The first expression initializes the counter variable at the start of the loop. You can
<p>use any variable you like, but the convention is to use $i. When more than one
<p>counter is needed, $j and $k are frequently used.
<p>The second expression is a test that determines whether the loop should continue
<p>to run. This can be a fixed number, a variable, or an expression that calculates a
<p>value.
<p>The third expression shows the method of stepping through the loop. Most of the
<p>time, you will want to go through a loop one step at a time, so using the increment
<p>(++) or decrement (&#8211;) operator is convenient.
<p>The following code does exactly the same as the previous while loop, displaying every
<p>number from 1 to 100 (see forloop.php in examples/ch10):
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>318</b>
<p>for ($i = 1; $i &lt;= 100; $i++) {
<p>echo &#8220;$i&lt;br /&gt;&#8221;;
<p>}
<p>There is nothing stopping you from using bigger steps. For instance, replacing $i++ with
<p>$i+=10 in this example would display 1, 11, 21, 31, and so on.
<p><b>Looping through arrays with foreach</b>
<p>The final type of loop in PHP is used exclusively with arrays. It takes two forms, both of
<p>which use temporary variables to handle each array element. If you only need to do something
<p>with the value of each array element, the foreach loop takes the following form:
<p>foreach (<i>array_name </i>as <i>temporary_variable</i>) {
<p><i>do something with temporary_variable</i>
<p>}
<p>The following example loops through the $shoppingList array and displays the name of
<p>each item (see shopping_list.php in examples/ch10):
<p>$shoppingList = array(&#8216;wine&#8217;, &#8216;fish&#8217;, &#8216;bread&#8217;, &#8216;grapes&#8217;, &#8216;cheese&#8217;);
<p>foreach ($shoppingList as $item) {
<p>echo $item.&#8217;&lt;br /&gt;&#8217;;
<p>}
<p>The preceding example accesses only the value of each array element. An alternative form
<p>of the foreach loop gives access to both the key and value of each element. It takes this
<p>slightly different form:
<p>foreach (<i>array_name </i>as <i>key_variable </i>=&gt; <i>value_variable</i>) {
<p><i>do something with key_variable and value_variable</i>
<p>}
<p>This next example uses the $book array from “Using names to identify array elements” earlier
<p>in the chapter and incorporates the key and value of each element into a simple string,
<p>as shown in the screenshot (see book.php in examples/ch10):
<p>foreach ($book as $key =&gt; $value) {
<p>echo &#8220;The value of $key is $value&lt;br /&gt;&#8221;;
<p>}
<p>INTRODUCING THE BASICS OF PHP
<p><b>319</b>
<p><b>10</b>
<p><b>Breaking out of a loop</b>
<p>To bring a loop prematurely to an end when a certain condition is met, insert the break
<p>keyword inside a conditional statement. As soon as the script encounters break, it exits
<p>the loop.
<p>To skip an iteration of the loop when a certain condition is met, use the continue keyword.
<p>Instead of exiting, it returns to the top of the loop and executes the next iteration.
<p><b>Using functions for preset tasks</b>
<p><b>Functions </b>do things . . . lots of things, mind-bogglingly so in PHP. The last time I counted,
<p>PHP had nearly 3,000 built-in functions, and more have been added since. Don’t worry:
<p>you’ll only ever need to use a handful, but it’s reassuring to know that PHP is a fullfeatured
<p>language capable of industrial-strength applications.
<p>The functions you’ll be using in this book do really useful things, such as send email, query
<p>a database, format dates, and much, much more. You can identify functions in PHP code,
<p>because they’re always followed by a pair of parentheses. Sometimes the parentheses are
<p>empty, as in the case of phpinfo(), which you used in test.php when setting up your testing
<p>environment in Chapter 3. Often, though, the parentheses contain variables, numbers,
<p>or strings, like this:
<p>$thisYear = date(&#8216;Y&#8217;);
<p>This calculates the current year and stores it in the variable $thisYear. It works by feeding
<p>the string &#8216;Y&#8217; to the built-in PHP function date(). Placing a value between the parentheses
<p>like this is known as <b>passing an argument </b>to a function. The function takes the value in
<p>the argument and processes it to produce (or <b>return</b>) the result. For instance, if you pass
<p>the string &#8216;M&#8217; as an argument to date() instead of &#8216;Y&#8217;, it will return the current month as
<p>a three-letter abbreviation (e.g., Mar, Apr, May). The date() function is covered in detail in
<p>Chapter 17.
<p>Some functions take more than one argument. When this happens, separate the arguments
<p>with commas inside the parentheses, like this:
<p>$mailSent = mail($to, $subject, $message);
<p>It doesn’t take a genius to work out that this sends an email to the address stored in the
<p>first argument, with the subject line stored in the second argument, and the message
<p>stored in the third one. You’ll see how this function works in the next chapter.
<p><i>You’ll often come across the term “parameter” in place of “argument.” There is</i>
<p><i>a technical difference between the two words, but for all practical purposes,</i>
<p><i>they are interchangeable.</i>
<p><i>The </i>foreach <i>keyword is one word. Inserting a space between </i>for <i>and</i>
<p>each <i>doesn’t work.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>320</b>
<p>As if the 3,000-odd built-in functions weren’t enough, PHP lets you build your own custom
<p>functions. Even if you don’t relish the idea of creating your own, throughout this book
<p>you’ll use some that I have made. You use them in exactly the same way.
<p><b>Understanding PHP error messages</b>
<p>There’s one final thing you need to know about before savoring the delights of PHP: error
<p>messages. They’re an unfortunate fact of life, but it helps a great deal if you understand
<p>what they’re trying to tell you. The following illustration shows the structure of a typical
<p>error message.
<p>The first thing to realize about PHP error messages is that they report the line where PHP
<p>discovered a problem. Most newcomers—quite naturally—assume that’s where they’ve
<p>got to look for their mistake. Wrong . . .
<p>What PHP is telling you most of the time is that something unexpected has happened. In
<p>other words, the mistake frequently lies <i>before </i>that point. The preceding error message
<p>means that PHP discovered a foreach command where there shouldn’t have been one.
<p>(Error messages always prefix PHP elements with T_, which stands for token. Just ignore it.)
<p>Instead of worrying what might be wrong with the foreach command (probably nothing),
<p>start working backward, looking for anything that might be missing. Usually, it’s a semicolon
<p>or closing quote. In this example, the error was caused by omitting the semicolon at
<p>the end of line 28 in book.php.
<p>There are four main categories of error, presented here in descending order of importance:
<p><b>Fatal error</b>: Any XHTML output preceding the error will be displayed, but once the
<p>error is encountered—as the name suggests—everything else is killed stone dead.
<p>A fatal error is normally caused by referring to a nonexistent file or function.
<p><b>Parse error</b>: This means there’s a mistake in your code, such as mismatched quotes,
<p>or a missing semicolon or closing brace. Like a fatal error, it stops the script in its
<p>tracks and doesn’t even allow any XHTML output to be displayed.
<p><b>Warning</b>: This alerts you to a serious problem, such as a missing include file.
<p>(Include files are covered in Chapter 12.) However, the error is not serious enough
<p>to prevent the rest of the script from being executed.
<p><b>Notice</b>: This advises you about relatively minor issues, such as the use of a nondeclared
<p>variable. Although you can turn off the display of notices, you should always
<p>try to eliminate the cause, rather than sweep the issue under the carpet. Any error
<p>is a threat to your output.
<p>INTRODUCING THE BASICS OF PHP
<p><b>321</b>
<p><b>10</b>
<p>Hosting companies have different policies about the level of error checking. If error checking
<p>is set to a high level and the display of errors is turned off, any mistakes in your code
<p>will result in a blank screen. Even if your hosting company has a more relaxed policy, you
<p>still don’t want mistakes to be displayed for all to see. Test your code thoroughly, and eliminate
<p>all errors before deploying it on a live website.
<p>Another type of error, strict, was introduced in PHP 5.0.0, mainly for the benefit of
<p>advanced developers. As of this writing, strict error messages are not displayed by default,
<p>but there are plans to change this and introduce a new deprecated category as a prelude
<p>to removing outdated parts of the language. If you see a strict or deprecated error message,
<p>ignore it at your peril.
<p><b>Now put it to work . . .</b>
<p>After that crash course, I hope you’re feeling not like a crash victim but invigorated and
<p>raring to go. Although you have been bombarded with a mass of information, you’ll discover
<p>that it’s easy to make rapid progress with PHP. In the next chapter, you’ll use most of
<p>the techniques from this chapter to send user input from an online form to your email
<p>inbox. To begin with, you’ll probably feel that you’re copying code without much comprehension,
<p>but I’ll explain all the important things along the way, and you should soon find
<p>things falling into place.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>322</b>
<p>11 <b>USING PHP TO PROCESS A FORM</b>
<p>In Chapter 9, I showed you how to build a feedback form and validate the input on the
<p>client side with Spry validation widgets. In this chapter, we’ll take the process to its next
<p>stage by validating the data on the server side with PHP. If the data is OK, we’ll send the
<p>contents by email and display an acknowledgement message. If there’s a problem with any
<p>of the data, we’ll redisplay it in the form with messages prompting the user to correct any
<p>errors or omissions. Figure 11-1 shows the flow of events.
<p><b>Figure 11-1. </b>The flow of events in processing the feedback form
<p>Sending an email from an online form is just the sort of task that Dreamweaver should
<p>automate, but unfortunately it doesn’t. Commercial extensions are available to automate
<p>the process for you, but not everyone will have—or want to buy—a commercial extension
<p>in addition to Dreamweaver CS3, so I think it’s important to show you how to hand-code
<p>this vital feature. At the same time, it gives you practical experience working with PHP
<p>code, which is essential unless you are willing to be limited to very basic tasks. The
<p>Dreamweaver server behaviors and data objects that you will use in later chapters take a
<p>lot of the hard work out of creating dynamic applications, but like the CSS layout that you
<p>used in Chapter 6, they lay a solid foundation for you to build on, rather than do
<p>absolutely everything for you.
<p>This chapter shows you how to
<p>Gather user input and send it by email
<p>Use PHP conditional logic to check required fields
<p>Display errors without losing user input
<p>Filter out suspect material
<p>Avoid email header injection attacks
<p>Process multiple-choice form elements
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>326</b>
<p>The flow of events shown in Figure 11-1 is controlled by a series of conditional statements
<p>(see “Making decisions” in the previous chapter). The PHP script will be in the same page
<p>as the form, so the first thing that it needs to know is <i>if </i>the form has been submitted. <i>If </i>it
<p>has, the contents of the $_POST array will be checked. <i>If </i>it’s OK, the email will be sent and
<p>an acknowledgement displayed, <i>else </i>a series of error messages will be displayed. In other
<p>words, everything is controlled by if . . . else statements.
<p><b>Activating the form</b>
<p>As you saw in Chapter 9, data entered into the form can be retrieved by using
<p>print_r($_POST); to inspect the contents of the $_POST array. This is one of PHP’s socalled
<p><b>superglobal arrays</b>. They’re such an important part of PHP, it’s worth pausing for a
<p>moment to take a look at what they do.
<p><b>Getting information from the server with PHP superglobals</b>
<p>Superglobal arrays are built-in associative arrays that are automatically populated with
<p>really useful information. They all begin with a dollar sign followed by an underscore. The
<p>most important superglobal arrays are as follows:
<p><b>$_POST</b>: This contains values sent through the post method.
<p><b>$_GET</b>: This contains values sent through the get method or a URL query string.
<p><b>$_SERVER</b>: This contains information stored by the web server, such as file name,
<p>pathname, hostname, etc.
<p><b>$_SESSION</b>: This stores information that you want to preserve so that it’s available
<p>to other pages. Sessions are covered in Chapter 15.
<p><b>$_FILES</b>: This contains details of file uploads. File uploads are not covered in this
<p>book. See www.php.net/manual/en/features.file-upload.php or my book <i>PHP</i>
<p><i>Solutions: Dynamic Web Design Made Easy </i>(friends of ED, ISBN-13: 978-1-59059-
<p>731-6) for details.
<p>The keys of $_POST and $_GET are automatically derived from the names of form elements.
<p>Let’s say you have a text input field called address in a form; PHP automatically creates
<p>an array element called $_POST['address'] when the form is submitted by the post
<p>method or $_GET['address'] if you use the get method. As Figure 11-2 shows,
<p>$_POST['address'] contains whatever value a visitor enters in the text field, enabling you
<p>to display it onscreen, insert it in a database, send it to your email inbox, or do whatever
<p>you want with it.
<p><b>Figure 11-2. </b>The $_POST array automatically creates variables with the same name
<p>and value as each form field.
<p>USING PHP TO PROCESS A FORM
<p><b>327</b>
<p><b>11</b>
<p>It’s important to realize that variables like $_POST['address'] or $_GET['address'] don’t
<p>exist until the form has been submitted. So, before using $_POST or $_GET variables in a
<p>script, you should always test for their existence with isset() or wrap the entire section
<p>of script in a conditional statement that checks whether the form has been submitted.
<p>You’ll see both of these techniques in action in this chapter and the rest of this book.
<p>You may come across old scripts or tutorials that tell you PHP automatically creates variables
<p>with the same name as form fields. In this example, it would be $address. This relies
<p>on a setting called register_globals being on. The default for register_globals has
<p>been off since 2002, but some hosting companies still switch it back on. You should never
<p>rely on register_globals, as it leaves your site wide open to malicious attacks. Moreover,
<p>register_globals has been removed from PHP 6, so scripts that rely on this setting will
<p>break in the future.
<p>Some scripts also recommend the use of $_REQUEST, which is another PHP superglobal. It’s
<p>much less secure. Always use $_POST for data submitted using the post method and $_GET
<p>for the get method or when values are passed through a query string at the end of a URL.
<p>Dreamweaver code hints make it easy to type the names of superglobals. As soon as you
<p>type the underscore after the dollar sign, it displays a list of the array names; and for arrays
<p>such as $_SERVER with predefined elements, a second menu with the predefined elements
<p>is also displayed, as you’ll see when you start scripting the form.
<p><b>Sending email</b>
<p>To send an email with PHP, you use the mail() function, which takes up to five arguments,
<p>all of them strings, as follows:
<p>The address(es) of the recipient(s)
<p>The subject line
<p>The message body
<p>A list of other email headers
<p>Additional parameters
<p>The first three arguments are required. Email addresses in the first argument can be in
<p>either of the following formats:
<p>&#8216;user@example.com&#8217;
<p>&#8216;Some Guy &lt;user2@example.com&gt;&#8217;
<p>To send to more than one address, use a comma-separated string like this:
<p>&#8216;user@example.com, another@example.com, Some Guy &lt;user2@example.com&gt;&#8217;
<p><i>Don’t forget that PHP is case sensitive. All superglobal array names are written in</i>
<p><i>uppercase. </i>$_Post <i>or </i>$_Get<i>, for example, won’t work.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>328</b>
<p>The second argument is a string containing the subject line. The third argument is the message
<p>body, which must be a single string, regardless of how long it is. I’ll come back to the
<p>final two arguments later.
<p>It’s important to understand that mail() isn’t an email program. It passes data to the web
<p>server’s mail transport agent (MTA). PHP’s responsibility ends there. It has no way of knowing
<p>if the email is delivered to its destination. It doesn’t handle attachments or HTML
<p>email. Still, it’s efficient and easy to use.
<p>These days, most Internet service providers (ISPs) enforce simple mail transfer protocol
<p>(SMTP) authentication before accepting email for relay from another machine. However,
<p>since mail() communicates directly with the MTA on the same machine, no authentication
<p>is required. More important, since mail() doesn’t normally need to authenticate
<p>itself, it’s not capable of doing so when you attempt to use it in your local test environment.
<p>What happens is that mail() tries to hand the message to your local MTA. If it finds
<p>one, and your ISP accepts the message, you’re in luck. More often than not, it can’t find
<p>one or the ISP rejects the mail without authentication. On Windows, you can edit php.ini
<p>(see Chapter 3) and change the SMTP command from localhost to the address of your
<p>ISP’s outgoing mail server (it’s usually something like smtp.example.com). On a Mac, PHP
<p>uses the MTA built into OS X, so there is no need to edit php.ini.
<p><b>Scripting the feedback form</b>
<p>To make things simple, I’m going to break up the PHP script into several sections. To start
<p>off, I’ll concentrate on the text input fields and sending their content by email. Then I’ll
<p>move onto validation and the display of error messages before showing you how to handle
<p>checkboxes, radio buttons, menus, and multiple-choice lists.
<p>Most readers should be able to send a simple email after the following exercise, but even
<p>if you are successful, you should implement the server-side validation described later in
<p>the chapter. This is because, without some simple security precautions, you risk turning
<p>your online forms into a spam relay. Your hosting company might suspend your site or
<p>close down your account altogether. In fact, many hosting companies implement security
<p>measures that prevent the first version of the mail script from working. However, you
<p>should have a fully working form by the end of this chapter.
<p>This involves a lot of hand-coding—much more than you’ll encounter in later chapters.
<p>Even if you don’t want to do a lot of PHP programming, it’s important to get a feel for the
<p>flow of a script, as this will help you customize the Dreamweaver code once you start
<p>working with a database. The script uses a lot of PHP’s built-in functions. I explain the
<p>important ones but don’t always go into the finer points of how they work. The idea is to
<p>give you a working solution, rather than overwhelm you with detail. The finished code for
<p>each section is in examples/ch11; and in the next chapter, I’ll show you how to put the
<p>main part of the script in an external file so that you can reuse it with other forms without
<p>the need to hand-code everything from scratch every time.
<p><i>Local testing with </i>mail() <i>is very much hit and miss. The most reliable approach is to</i>
<p><i>test mail-processing scripts on your remote server. The instructions in this chapter</i>
<p><i>explain which parts of the script can be tested locally.</i>
<p>USING PHP TO PROCESS A FORM
<p><b>329</b>
<p><b>11</b>
<p>The starting point is in feedback_01.php in examples/ch11. It’s the same as feedback_
<p>fieldsets.php from Chapter 9 but with the small block of PHP code removed from the
<p>bottom of the page. If you want to use your own form, I suggest that you remove any
<p>client-side validation from it, as the client-side validation makes it difficult to check
<p>whether the more important server-side validation with PHP is working correctly. You can
<p>add the client-side validation back at the final stage.
<p><b>1. </b>Copy feedback_01.php from examples/ch11 to workfiles/ch11, and save it as
<p>feedback.php. Also make sure you have a copy of contact.css in your styles
<p>folder.
<p><b>2. </b>Open contact.css, and add the following style rule (it already exists in the version
<p>in the examples/styles folder):
<p>.warning {
<p>font-weight:bold;
<p>color:#FF0000;
<p>}
<p>This adds a class called warning, which displays text in bold red. Close
<p>contact.css.
<p><b>3. </b>Open feedback.php in Split view, click anywhere inside the form, and use the Tag
<p>selector to select the entire form. This should bring the opening tag of the form
<p>into view in the Code view section of the Document window. Click inside Code view
<p>so that your cursor is between the quotes of the action attribute. Although you
<p>can set the action for the form through the Property inspector, doing so in Code
<p>view greatly reduces the possibility of making a mistake.
<p><b>4. </b>Select the PHP tab on the Insert bar, and click the Echo button (the menu option is
<p>Insert <b>ä </b>PHP Objects <b>ä </b>Echo). This will insert a pair of PHP tags followed by echo
<p>between the quotes of the action attribute, and Dreamweaver positions your cursor
<p>in the correct place to start typing, as shown in the following screenshot:
<p><b>Processing and acknowledging the message</b>
<p><i>This is a long script. Give yourself plenty of time to absorb the details. You can</i>
<p><i>check your progress at each stage with the files in </i>examples/ch11<i>. The final</i>
<p><i>code is in </i>feedback_12.php<i>.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>330</b>
<p><b>5. </b>To set the action attribute of the form to process itself, you need to use a variable
<p>from the $_SERVER superglobal array. As noted before, superglobals always begin
<p>with $_, so type just that at the current position. Dreamweaver automatically presents
<p>you with a pop-up menu containing all the superglobals, as shown here:
<p>You can navigate this pop-up menu in several ways: continue typing “server” in
<p>either uppercase or lowercase until SERVER is highlighted or use your mouse or
<p>the arrow keys to highlight it. Then double-click or press Enter/Return.
<p>Dreamweaver will present you with another pop-up menu. Locate PHP_SELF as
<p>shown, and either double-click or press Enter/Return:
<p><b>6. </b>Although it’s not strictly necessary for a single command, get into the habit of ending
<p>all statements with a semicolon, and type one after the closing square bracket
<p>(]) of the superglobal variable that’s just been entered. The code in the opening
<p>&lt;form&gt; tag should look like this (new code is highlighted in bold type):
<p>&lt;form action=&#8221;<b>&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;</b>&#8221; method=&#8221;post&#8221; <b>å</b>
<p>name=&#8221;form1&#8243; id=&#8221;form1&#8243;&gt;
<p>The predefined variable $_SERVER['PHP_SELF'] always contains the name of the
<p>current page, so using echo between the quotes of the action attribute automatically
<p>sets it to the current page, making this a self-processing form. As you saw
<p>in Chapter 9, leaving out the value of action also results in the form attempting
<p>to process itself. So, technically speaking, this isn’t 100 percent necessary, but
<p>it’s common practice in PHP scripts, and it’s useful to know what
<p>$_SERVER['PHP_SELF'] does.
<p><b>7. </b>You now need to add the mail-processing script at the top of the page. As you saw
<p>in Chapter 9, the $_POST array contains not only the data entered into the form but
<p>also the name and value of the submit button. You can use this information to
<p>determine whether the submit button has been clicked. From this point onward, it
<p>will be easier to work in Code view. Switch to Code view, and insert the following
<p>block of PHP code immediately above the DOCTYPE declaration:
<p>USING PHP TO PROCESS A FORM
<p><b>331</b>
<p><b>11</b>
<p><b>&lt;?php</b>
<p><b>if (array_key_exists(&#8217;send&#8217;, $_POST)) {</b>
<p><b>// mail processing script</b>
<p><b>echo &#8216;You clicked the submit button&#8217;;</b>
<p><b>}</b>
<p><b>?&gt;</b>
<p>&lt;!DOCTYPE html PUBLIC &#8220;-//W3C//DTD XHTML 1.0 Transitional//EN&#8221; <b>å</b>
<p>&#8220;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&#8221;&gt;
<p>This uses the PHP function array_key_exists() to check whether the $_POST array
<p>contains a key called send, the name attribute of the form submit button. If you
<p>don’t want to type out the function name yourself, you can press Ctrl+Space to
<p>bring up an alphabetical list of all PHP functions. Type just the first few letters, and
<p>then use your arrow keys to select the right one. When you press Tab or
<p>Enter/Return, Dreamweaver finishes the rest of the typing and pops up a code hint.
<p>Alternatively, just type the function name directly, and the code hint appears as
<p>soon as you enter the opening parenthesis after array_key_exists, as shown here:
<p>The mixed datatype refers to the fact that array keys can be either numbers or
<p>strings. In this case, you are using a string, so enclose send in quotes, and then after
<p>a comma, type $_POST. Because it’s a superglobal, you are presented with the
<p>same pop-up menu as in step 5. If you select POST, Dreamweaver assumes that you
<p>want to add the name of an array key and will automatically add an opening square
<p>bracket after the T. On this occasion, you want to check the whole $_POST array,
<p>not just a single element, so remove the bracket by pressing Backspace. Make sure
<p>that you use two closing parentheses—the first belongs to the function
<p>array_key_exists(), and the second encloses the condition being tested for by
<p>the if statement.
<p>If the send array key exists, the submit button must have been clicked, so any script
<p>between the curly braces is executed. Otherwise, it’s ignored. Don’t worry that echo
<p>will display text above the DOCTYPE declaration. It’s being used for test purposes
<p>only and will be removed eventually.
<p><b>8. </b>Save feedback.php, and test it in a browser. It should look no different from
<p>before.
<p><i>Remember, an </i>if <i>statement doesn’t always need to be followed by </i>else <i>or</i>
<p>elseif<i>. When the condition of a solitary </i>if <i>statement isn’t met, PHP simply</i>
<p><i>skips to the next block of code.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>332</b>
<p><b>9. </b>Click the Send comments button. A message should appear at the top of the page
<p>saying “You clicked the submit button.”
<p><b>10. </b>Reload the page without using the browser’s Reload button. Click inside the
<p>address bar, and press Enter/Return. The message should disappear. This confirms
<p>that any code inside the curly braces runs only if the submit button has been
<p>clicked.
<p><b>11. </b>Change the block of code that you entered in step 7 so that it looks like this:
<p>&lt;?php
<p>if (array_key_exists(&#8217;send&#8217;, $_POST)) {
<p>//mail processing script
<p><b>$to = &#8216;me@example.com&#8217;; // use your own email address</b>
<p><b>$subject = &#8216;Feedback from Essential Guide&#8217;;</b>
<p>// process the $_POST variables
<p><b>$name = $_POST['name'];</b>
<p><b>$email = $_POST['email'];</b>
<p><b>$comments = $_POST['comments'];</b>
<p>// build the message
<p><b>$message = &#8220;Name: $name\n\n&#8221;;</b>
<p><b>$message .= &#8220;Email: $email\n\n&#8221;;</b>
<p><b>$message .= &#8220;Comments: $comments&#8221;;</b>
<p>// limit line length to 70 characters
<p><b>$message = wordwrap($message, 70);</b>
<p>// send it
<p><b>$mailSent = mail($to, $subject, $message);</b>
<p>}
<p>?&gt;
<p>The code that does the processing consists of five stages. The first two lines assign
<p>your email address to $to and the subject line of the email to $subject.
<p>Next, $_POST['name'], $_POST['email'], and $_POST['comments'] are reassigned
<p>to ordinary variables to make them easier to handle.
<p>The shorter variables are then used to build the body of the email message, which
<p>must consist of a single string. As you can see, I have used the combined concatenation
<p>operator (.=) to build the message and escape sequences to add new line
<p>characters between each section (see “Adding to an existing string” and “Using
<p>escape sequences in strings” in Chapter 10).
<p>Once the message body is complete, it’s passed to the wordwrap() function, which
<p>takes two arguments: a string and an integer that sets the maximum length of each
<p>line. Although most mail systems will accept longer lines, it’s recommended to limit
<p>each line to 70 characters.
<p>USING PHP TO PROCESS A FORM
<p><b>333</b>
<p><b>11</b>
<p>After the message has been built and formatted, the recipient’s address, subject
<p>line, and body of the message are passed to the mail() function. There is nothing
<p>magical about the variable names $to, $subject, and $message. I chose them to
<p>describe what each one contains, making much of the script self-commenting.
<p>The mail() function returns a Boolean value (true or false) indicating whether it
<p>succeeded. By capturing this value as $mailSent, you can use it to redirect the user
<p>to another page or change the contents of the current one.
<p><b>12. </b>For the time being, let’s keep everything in the same page, because the rest of the
<p>chapter will add further refinements to the basic script. Scroll down, and insert the
<p>following code just after the page’s main heading (new code is highlighted in bold):
<p>&lt;h1&gt;Contact us&lt;/h1&gt;
<p><b>&lt;?php</b>
<p><b>if ($_POST &amp;&amp; !$mailSent) {</b>
<p><b>?&gt;</b>
<p><b>&lt;p class=&#8221;warning&#8221;&gt;Sorry, there was a problem sending your message.</b>
<p><b>Please try later.&lt;/p&gt;</b>
<p><b>&lt;?php</b>
<p><b>}</b>
<p><b>elseif ($_POST &amp;&amp; $mailSent) {</b>
<p><b>?&gt;</b>
<p><b>&lt;p&gt;&lt;strong&gt;Your message has been sent. Thank you for your feedback.</b>
<p><b>&lt;/strong&gt;&lt;/p&gt;</b>
<p><b>&lt;?php } ?&gt;</b>
<p>&lt;p&gt;We welcome feedback from visitors . . .&lt;/p&gt;
<p>Many beginners mistakenly think that you need to use echo or print to display
<p>XHTML inside a PHP block. However, except for very short pieces of code, it’s more
<p>efficient to switch back to XHTML, as I’ve done here. Doing so avoids the need to
<p>worry about escaping quotes. Also, Dreamweaver code hints and automatic tag
<p>completion speed things up for you. As soon as you type a space after &lt;p in the
<p>first paragraph, Dreamweaver pops up a code hint menu like this:
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>334</b>
<p>Select class. As soon as you do so, Dreamweaver checks the available classes in the
<p>attached style sheet and pops up another code hint menu, as shown in the next
<p>screenshot, so you can choose warning.
<p>This makes coding much quicker and more accurate. Dreamweaver’s context sensitivity
<p>means you get the full range of XHTML code hints only when you’re in a section
<p>of XHTML code. When you’re inside a block of PHP code, you get a list of
<p>XHTML tags when you type an opening angle bracket, but there are no attribute
<p>hints or auto-completion. So it makes more sense to use PHP for the conditional
<p>logic but keep the XHTML separate. The only thing you need to watch carefully is
<p>that you balance the opening and closing curly braces correctly. I’ll show you how
<p>to do that in “Using balance braces” a little later in the chapter.
<p>So what does this code do? It may look odd if you’re not used to seeing scripts that
<p>mix XHTML with PHP logic, but it can be summarized like this:
<p>&lt;h1&gt;Contact us&lt;/h1&gt;
<p>&lt;?php
<p>if ($_POST &amp;&amp; !$mailSent) {
<p>// display a failure message
<p>}
<p>elseif ($_POST &amp;&amp; $mailSent) {
<p>// display an acknowledgment
<p>}
<p>?&gt;
<p>&lt;p&gt;We welcome feedback from visitors . . .&lt;/p&gt;
<p>Both parts of the conditional statement check the Boolean values of $_POST and
<p>$mailSent. Although the $_POST array is always set, it doesn’t contain any values
<p>unless the form has been submitted. Since PHP treats an empty array as false (see
<p>“The truth according to PHP” in Chapter 10), you can use $_POST on its own to test
<p>whether a form has been submitted. So the code in both parts of this conditional
<p>statement is ignored when the page first loads.
<p>However, if the form has been submitted, $_POST equates to true, so the next
<p>condition is tested. The exclamation mark in front of $mailSent is the negative
<p>operator, making it the equivalent of <i>not </i>$mailSent. So, if the email hasn’t been
<p>sent, both parts of the test are true, and the XHTML containing the error message
<p>is displayed. However, if $mailSent is true, the XHTML containing the acknowledgment
<p>is displayed instead.
<p>USING PHP TO PROCESS A FORM
<p><b>335</b>
<p><b>11</b>
<p><b>13. </b>Save feedback.php, and switch to Design view. The top of the page should now
<p>look like this:
<p>There are three gold shields indicating the presence of PHP code, and both the
<p>error and acknowledgement messages are displayed. You need to get used to this
<p>sort of thing when designing dynamic pages.
<p>If you don’t see the gold shields, refer to “Passing information through a hidden
<p>field” in Chapter 9 for details of how to control invisible elements in Design view.
<p><b>14. </b>To see what the page looks like when the PHP is processed, click the Live Data view
<p>button (see alongside) to the right of the Design view button on the Document
<p>toolbar.
<p>If you have coded everything correctly, the error message and acknowledgement
<p>should disappear. Click the Live Data view button to toggle it off again.
<p>If you got a PHP error message, read “Using balance braces,” and then check your
<p>code against feedback_02.php.
<p><b>Using Balance Braces</b>
<p>Even if you didn’t encounter a problem in the preceding exercise, Balance Braces is a tool
<p>that you definitely need to know about. Like quotes, curly braces must always be in matching
<p>pairs, but sometimes the opening and closing braces can be dozens, even hundreds, of
<p>lines apart. If one of a pair is missing, your script will collapse like a house of cards. Balance
<p>Braces matches pairs in a highly visual way, making troubleshooting a breeze.
<p>Let’s take a look at the code in step 12 that I suspect will trip many people up. I deliberately
<p>removed an opening curly brace at the end of line 41 in the following screenshot.
<p>That triggered a parse error, which reported an unexpected closing curly brace on line 45.
<p>Now, that could mean either of the following:
<p><i>The script in step 11 is theoretically all you need to send email from an online form.</i>
<p><i>Don’t be tempted to leave it at that. Without the security checks described in the rest</i>
<p><i>of the chapter, you run the risk of turning your website into a spam relay.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>336</b>
<p>There’s a missing opening brace to match the closing one.
<p>There’s an extra closing brace that shouldn’t be there.
<p>The way to resolve the problem is to place your cursor anywhere between a pair of curly
<p>braces, and click the Balance Braces button in the Coding toolbar. This highlights the code
<p>between the matching braces. I started by placing my cursor on line 37. As you can see, it
<p>highlighted all the code between the braces on lines 35 and 40.
<p>Next, I positioned my cursor on line 43. When I clicked the Balance Braces button again,
<p>nothing was highlighted, and my computer just beeped. So there was the culprit. All I
<p>needed to work out was where the opening brace should go. My first test showed that I
<p>had a logical block on lines 35–40, so it was just a process of elimination tracking down the
<p>missing brace. If the problem had been an extra curly brace that shouldn’t have been
<p>there, the code would have been highlighted, giving me a clear indication of where the
<p>block ended.
<p>Although it can’t tell you whether your code logic is right or where a missing brace should
<p>go, you’ll find this tool a great timesaver. It works not only with braces, but also with
<p>square brackets and parentheses. Just position your cursor inside any curly brace, square
<p>bracket, or parenthesis, and click the Balance Braces button to find the other one of the
<p>pair. You may need to test several blocks to find the cause of a problem, but it’s an excellent
<p>way of visualizing code blocks and the branching logic of your scripts.
<p>You can also access Balance Braces through the Edit menu, and if you’re a keyboard shortcut
<p>fan, the combination is Ctrl+’/Cmd+’ (single quote).
<p><b>Testing the feedback form</b>
<p>Assuming that you now have a page that displays correctly in Live Data view, it’s time to
<p>test it. As mentioned earlier, testing mail() in a local PHP testing environment is unreliable,
<p>so I suggest that you upload feedback.php to a remote server for the next stage of
<p>testing. Once you have established that the mail() function is working, you can continue
<p>testing locally.
<p>Upload feedback.php and contact.css to your remote server. Enter some text in the
<p>Name, Email, and Comments fields. Make sure that your input includes at least an apostrophe
<p>or quotation mark, and click Send comments. The form should clear, and you should
<p>see a confirmation message, as in Figure 11-3.
<p>USING PHP TO PROCESS A FORM
<p><b>337</b>
<p><b>11</b>
<p><b>Figure 11-3. </b>Confirmation that the mail() function has passed the message to the server’s mail
<p>transport agent
<p>Shortly afterward, you should receive the message in your inbox. Most of the time, it
<p>should work, but there are several things that might go wrong. The next section should
<p>help you resolve the problem.
<p><b>Troubleshooting mail()</b>
<p>If you don’t receive anything, the first thing to check is your spam trap, because the email
<p>may appear to come from an unknown or a suspicious source. For example, it may appear
<p>to come from Apache or a mysterious nobody (the name often used for web servers).
<p>Don’t worry about the odd name; that will be fixed soon. The main thing is to check that
<p>the mail is being sent correctly.
<p>If you see an error message saying that the From header wasn’t set or that sendmail_from
<p>isn’t defined in php.ini, again that’s nothing to worry about and will be fixed shortly. Keep
<p>building the script as described in each section, and I’ll tell you when you can test your
<p>page on the remote server again.
<p>Some hosting companies now make it a requirement to use the fifth argument to mail()
<p>to ensure that it comes from an entrusted user. If you don’t receive mail or see a PHP error
<p>message, check your hosting company’s instructions and find out the exact format
<p>required for the fifth parameter. It normally consists of -f followed (without a space) by
<p>your own email address, all enclosed in quotes. You’ll see later how to add it to your code.
<p>Again, keep building the script as described in each section.
<p>Some mail servers object to new line characters that are not accompanied by carriage
<p>returns. If you receive a warning that includes SMTP server response: 451, change the
<p>escape sequences in the section that builds the message like this:
<p>$message = &#8220;Name: $name<b>\r</b>\n<b>\r</b>\n&#8221;;
<p>$message .= &#8220;Email: $email<b>\r</b>\n<b>\r</b>\n&#8221;;
<p>$message .= &#8220;Comments: $comments&#8221;;
<p><b>Getting rid of unwanted backslashes</b>
<p>Some day back in the mists of time, the PHP development team had the “brilliant” idea of
<p>creating a feature known as magic quotes . . . only it wasn’t so brilliant after all. When
<p>inserting data into a database, it’s essential to escape single and double quotes. So the idea
<p>of magic quotes was to make life simpler for beginners by doing this automatically for all
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>338</b>
<p>data passed through the $_POST and $_GET arrays, and cookies. While this seemed like a
<p>good idea at the time, it has caused endless problems. To cut a long story short, magic
<p>quotes are being officially phased out of PHP (they’ll be gone in PHP 6), but they’re still
<p>enabled on a lot of shared servers. You will know if your server uses them if your test email
<p>has backslashes in front of any apostrophes or quotes, as shown in Figure 11-4.
<p><b>Figure 11-4. </b>PHP magic quotes insert unwanted
<p>backslashes in the email.
<p>Dreamweaver’s server behaviors automatically handle magic quotes by stripping the backslashes,
<p>if necessary, and preparing data for database input. However, when you’re handcoding
<p>like this, you need to deal with the backslashes yourself.
<p>I have created a Dreamweaver snippet, so that you can drop a ready-made script into any
<p>page that needs to get rid of unwanted backslashes. It automatically detects whether
<p>magic quotes are enabled, so you can use it safely on any server. If magic quotes are on, it
<p>removes the backslashes. If magic quotes are off, it leaves your data untouched. It’s part of
<p>a collection of snippets that I’ve created for this book and packaged as a Dreamweaver
<p>extension so they can be installed in a single operation.
<p><b>1. </b>If Dreamweaver is open, you will need to close and restart the program after
<p>installing the snippets, so save any files that are open. Access the Extension
<p>Manager by choosing Manage Extensions from either the Commands or Help menu.
<p>If Dreamweaver is closed, launch Adobe Extension Manager CS3 from Start <b>ä </b>All
<p>Programs (Windows) or Finder <b>ä </b>Applications (Mac).
<p><b>2. </b>Select Dreamweaver CS3 in the drop-down menu on the Extension Manager toolbar,
<p>and choose File <b>ä </b>Install Extension, or click the Install button. Alternatively,
<p>press Ctrl+O/Cmd+O (capital “o,” not zero).
<p><b>3. </b>In the dialog box that opens, navigate to egdwcs3_snippets.mxp in the tools
<p>folder of the download files, and click Install.
<p><b>4. </b>After the extension has been installed, close Dreamweaver if it’s open. The snippets
<p>will be in the PHP-DWCS3 folder of the Snippets panel when you next open the
<p>program.
<p><b>Installing the PHP snippets collection</b>
<p>USING PHP TO PROCESS A FORM
<p><b>339</b>
<p><b>11</b>
<p><b>1. </b>Open feedback.php in Code view. Position your
<p>cursor on line 4, just under the mail processing
<p>script comment, and insert a couple of blank
<p>lines.
<p>Move your cursor onto one of the blank lines,
<p>and open the Snippets panel by clicking the
<p>Snippets tab in the Files panel group or selecting
<p>Window <b>ä </b>Snippets. On Windows, you can also
<p>use the keyboard shortcut Shift+F9, but this
<p>doesn’t work on the Mac version.
<p>Highlight the new POST stripslashes snippet in
<p>the PHP-DWCS3 folder, as shown alongside, and
<p>double-click it, or click the Insert button at the
<p>bottom of the panel.
<p><b>2. </b>This inserts the following block of code into your page:
<p>// remove escape characters from $_POST array
<p>if (get_magic_quotes_gpc()) {
<p>function stripslashes_deep($value) {
<p>$value = is_array($value) ? array_map(&#8217;stripslashes_deep&#8217;, <b>å</b>
<p>$value) : stripslashes($value);
<p>return $value;
<p>}
<p>$_POST = array_map(&#8217;stripslashes_deep&#8217;, $_POST);
<p>}
<p>Lying at the heart of this code is the PHP function stripslashes(), which removes
<p>the escape backslashes from quotes and apostrophes. Normally, you just pass the
<p>string that you want to clean up as the argument to stripslashes().
<p>Unfortunately, that won’t work with an array. This block of code checks whether
<p>magic quotes have been turned on; and if they have, it goes through the $_POST
<p>array and any nested arrays, cleaning up your text for display either in an email or
<p>in a web page.
<p><b>3. </b>Save feedback.php, and send another test email that includes apostrophes and
<p>quotes in the message. The email that you receive should be nicely cleaned up. This
<p>won’t work yet if you weren’t able to send the first test email.
<p>If you have any problems, check your page against feedback_03.php.
<p><b>Using the POST stripslashes snippet</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>340</b>
<p><b>Making sure required fields aren’t blank</b>
<p>When required fields are left blank, you don’t get the information you need, and the user
<p>may never get a reply, particularly if contact details have been omitted. The following
<p>instructions make use of arrays and the foreach loop, both of which are described in
<p>Chapter 10. So, if you’re new to PHP, you might find it useful to refer to the relevant sections
<p>in the previous chapter before continuing.
<p>In this part of the script, you create three arrays to hold details of variables you expect to
<p>receive from the form, those that are required, and those that are missing. This not only
<p>helps identify any required items that haven’t been filled in; it also adds an important
<p>security check before passing the user input to a loop that converts the names of $_POST
<p>variables to shorter ones that are easier to handle.
<p><b>1. </b>Start by creating two arrays: one listing the name attribute of each field in the form
<p>and the other listing all <i>required </i>fields. Also, initialize an empty array to store the
<p>names of required fields that have not been completed. For the sake of this
<p>demonstration, make the email field optional, so that only the name and comments
<p>fields are required. Add the following code just before the section that processes
<p>the $_POST variables:
<p>$subject = &#8216;Feedback from Essential Guide&#8217;;
<p><b>// list expected fields</b>
<p><b>$expected = array(&#8216;name&#8217;, &#8216;email&#8217;, &#8216;comments&#8217;);</b>
<p><b>// set required fields</b>
<p><b>$required = array(&#8216;name&#8217;, &#8216;comments&#8217;);</b>
<p><b>// create empty array for any missing fields</b>
<p><b>$missing = array();</b>
<p>// process the $_POST variables
<p><b>2. </b>At the moment, the $_POST variables are assigned manually to variables that use
<p>the same name as the $_POST array key. With three fields, manual assignment is
<p>fine, but it becomes a major chore with more fields. Let’s kill two birds with one
<p>stone by checking required fields and automating the naming of the variables at
<p>the same time. Replace the three lines of code beneath the $_POST variables comment
<p>as follows:
<p>// process the $_POST variables
<p><b>foreach ($_POST as $key =&gt; $value) {</b>
<p>// assign to temporary variable and strip whitespace if not an array
<p><b>$temp = is_array($value) ? $value : trim($value);</b>
<p>// if empty and required, add to $missing array
<p><b>if (empty($temp) &amp;&amp; in_array($key, $required)) {</b>
<p><b>array_push($missing, $key);</b>
<p><b>}</b>
<p>// otherwise, assign to a variable of the same name as $key
<p><b>elseif (in_array($key, $expected)) {</b>
<p><b>Checking required fields</b>
<p>USING PHP TO PROCESS A FORM
<p><b>341</b>
<p><b>11</b>
<p><b>${$key} = $temp;</b>
<p><b>}</b>
<p><b>}</b>
<p>// build the message
<p>If studying PHP code makes your brain hurt, you don’t need to worry about how
<p>this works. As long as you create the $expected, $required, and $missing arrays in
<p>the previous step, you can just copy and paste the code for use in any form.
<p>So what does it do? In simple terms, this foreach loop goes through the $_POST
<p>array, strips out any whitespace from user input, and assigns its contents to a variable
<p>with the same name (so $_POST['email'] becomes $email, and so on). If a
<p>required field is left blank, its name attribute is added to the $missing array.
<p>The code uses several built-in PHP functions, all of which have intuitive names:
<p>is_array() tests whether a variable is an array.
<p>trim() trims whitespace from both ends of a string.
<p>empty() tests whether a variable contains nothing or equates to false.
<p>in_array() checks whether the first argument is part of the array specified in
<p>the second argument.
<p>array_push() adds a new element to the end of an array.
<p>At this stage, you don’t need to understand how each function works, but you
<p>can find details in the PHP online documentation at www.php.net/manual/en/
<p>index.php. Type the name of the function in the search for field at the top right of
<p>the page (see Figure 11-5), and click the right-facing arrow alongside function list.
<p>The PHP documentation has many practical examples showing how functions and
<p>other features are used.
<p><b>Figure 11-5. </b>Refer often to the excellent PHP online documentation, and your skills will increase
<p>rapidly.
<p><i>Why is the </i>$expected <i>array necessary? It’s to prevent an attacker from injecting</i>
<p><i>other variables in the </i>$_POST <i>array in an attempt to overwrite your default</i>
<p><i>values. By processing only those variables that you expect, your form is much</i>
<p><i>more secure. Any spurious values are ignored.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>342</b>
<p><b>3. </b>You want to build the body of the email message and send it only if all required
<p>fields have been filled in. Since $missing starts off as an empty array, nothing is
<p>added to it if all required fields are completed, so empty($missing) is true. Wrap
<p>the rest of the script in the opening PHP code block like this:
<p><b>// go ahead only if all required fields OK</b>
<p><b>if (empty($missing)) {</b>
<p>// build the message
<p>$message = &#8220;Name: $name\n\n&#8221;;
<p>$message .= &#8220;Email: $email\n\n&#8221;;
<p>$message .= &#8220;Comments: $comments&#8221;;
<p>// limit line length to 70 characters
<p>$message = wordwrap($message, 70);
<p>// send it
<p>$mailSent = mail($to, $subject, $message);
<p><b>if ($mailSent) {</b>
<p><b>// $missing is no longer needed if the email is sent, so unset it</b>
<p><b>unset($missing);</b>
<p><b>}</b>
<p>}
<p><b>}</b>
<p>This ensures that the mail is sent only if nothing has been added to $missing.
<p>However, $missing will be used to control the display of error messages in the
<p>main body of the page, so you need to get rid of it if the mail is successfully sent.
<p>This is done by using unset(), which destroys a variable and any value it contains.
<p><b>4. </b>Let’s turn now to the main body of the page. You need to display a warning if anything
<p>is missing. Amend the conditional statement at the top of the page content
<p>like this:
<p>&lt;h1&gt;Contact us&lt;/h1&gt;
<p>&lt;?php
<p><b>if ($_POST &amp;&amp; isset($missing) &amp;&amp; !empty($missing)) {</b>
<p><b>?&gt;</b>
<p><b>&lt;p class=&#8221;warning&#8221;&gt;Please complete the missing item(s) indicated.&lt;/p&gt;</b>
<p><b>&lt;?php</b>
<p><b>}</b>
<p><b>elseif </b>($_POST &amp;&amp; !$mailSent) {
<p>?&gt;
<p>&lt;p class=&#8221;warning&#8221;&gt;Sorry, there was a problem sending your message.
<p>Please try later.&lt;/p&gt;
<p>This adds a new condition. The isset() function checks whether a variable exists. If
<p>$missing doesn’t exist, that means that all required fields were filled in and the
<p>email was sent successfully, so the condition fails, and the script moves on to consider
<p>the elseif condition. However, if all required fields were filled in, but there
<p>was a problem sending the email, $missing still exists, so you need to make sure it’s
<p>empty. An exclamation mark is the negative operator, so !empty means “not empty.”
<p>USING PHP TO PROCESS A FORM
<p><b>343</b>
<p><b>11</b>
<p>On the other hand, if $missing exists and <i>isn’t </i>empty, you know that at least one
<p>required field was omitted, so the warning message is displayed.
<p>I’ve placed this new condition first. The $mailSent variable won’t even be set if any
<p>required fields have been omitted, so you must test for $missing first.
<p><b>5. </b>To make sure it works so far, save feedback.php, and load it in a browser. You don’t
<p>need to upload it to your remote server, because you want to test the message
<p>about missing items. Don’t fill in any fields. Just click Send comments. The top of
<p>the page should look like this (check your code against feedback_04.php if
<p>necessary):
<p><b>6. </b>To display a suitable message alongside each missing required field, add a PHP code
<p>block to display a warning as a &lt;span&gt; inside the &lt;label&gt; tag like this:
<p>&lt;label for=&#8221;name&#8221;&gt;Name: <b>&lt;?php</b>
<p><b>if (isset($missing) &amp;&amp; in_array(&#8216;name&#8217;, $missing)) { ?&gt;</b>
<p><b>&lt;span class=&#8221;warning&#8221;&gt;Please enter your name&lt;/span&gt;&lt;?php } ?&gt;</b>
<p>&lt;/label&gt;
<p>Since the $missing array is created only after the form has been submitted, you
<p>need to check first with isset() that it exists. If it doesn’t exist—such as when the
<p>page first loads or if the email has been sent successfully—the &lt;span&gt; is never displayed.
<p>If $missing does exist, the second condition checks if the $missing array
<p>contains the value name. If it does, the &lt;span&gt; is displayed as shown in Figure 11-6.
<p><b>7. </b>Insert a similar warning for the comments field like this:
<p>&lt;label for=&#8221;comments&#8221;&gt;Comments: <b>&lt;?php</b>
<p><b>if (isset($missing) &amp;&amp; in_array(&#8216;comments&#8217;, $missing)) { ?&gt;</b>
<p><b>&lt;span class=&#8221;warning&#8221;&gt;Please enter your comments&lt;/span&gt;&lt;?php } ?&gt;</b>
<p>&lt;/label&gt;
<p>The PHP code is the same except for the value you are looking for in the $missing
<p>array. It’s the same as the name attribute for the form element.
<p><b>8. </b>Save feedback.php, and test the page again locally by entering nothing into any
<p>of the fields. The page should look like Figure 11-6. Check your code against
<p>feedback_05.php if you encounter any problems.
<p><b>9. </b>Try one more test. Open Code view, and amend the line that sends the email like
<p>this:
<p>$mailSent = <b>false; // </b>mail($to, $subject, $message);
<p>This temporarily sets the value of $mailSent to false and comments out the code
<p>that actually sends the email.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>344</b>
<p><b>Figure 11-6. </b>The PHP script displays alerts if required information is missing, even when
<p>JavaScript is disabled.
<p><b>10. </b>Reload feedback.php into your browser, and type something in the Name and
<p>Comments fields before clicking Send comments. This time you should see the message
<p>telling you there was a problem and asking you to try later.
<p><b>11. </b>Reverse the change you made in step 9 so that the code is ready to send the email.
<p><b>Preserving user input when a form is incomplete</b>
<p>Imagine you have just spent ten minutes filling in a form. You click the submit button, and
<p>back comes the response that a required field is missing. It’s infuriating if you have to fill
<p>in every field all over again. Since the content of each field is in the $_POST array, it’s easy
<p>to redisplay it when an error occurs.
<p>When the page first loads or the email is successfully sent, you don’t want anything to
<p>appear in the input fields. But you do want to redisplay the content if a required field is
<p>missing. So that’s the key: if the $missing variable exists, you want the content of each
<p>field to be redisplayed. You can set default text for a text input field by setting the value
<p>attribute of the &lt;input&gt; tag.
<p>At the moment, the &lt;input&gt; tag for name looks like this:
<p>&lt;input name=&#8221;name&#8221; type=&#8221;text&#8221; class=&#8221;textInput&#8221; id=&#8221;name&#8221; /&gt;
<p>To add the value attribute, all you need is a conditional statement that checks whether
<p>$missing exists. If it does, you can use echo to display value=&#8221;" and put the value held in
<p>$_POST['name'] between the quotes. It sounds simple enough, but this is one of those situations
<p>where getting the right combination of quotes can drive you mad. It’s made even
<p>worse by the fact that the user input in the text field might also contain quotes. Figure 11-7
<p>shows what happens if you don’t give quotes in user input special treatment. The browser
<p>finds the first matching quote and throws the rest of the input away.
<p>USING PHP TO PROCESS A FORM
<p><b>345</b>
<p><b>11</b>
<p><b>Figure 11-7. </b>Quotes within user input need special treatment before form fields can be
<p>redisplayed.
<p>You might be thinking that this is a case where magic quotes would be useful.
<p>Unfortunately, they won’t work either. If you don’t use the POST stripslashes snippet, this
<p>is what you get instead:
<p>Magic quotes work only with input into a database (and not very well, either, which is why
<p>they are being phased out). The browser still sees the first matching quote as the end of
<p>the value attribute. The solution is simple: convert the quotes to the HTML entity equivalent
<p>(&amp;quot;), and PHP has a function called—appropriately—htmlentities(). Passing the
<p>$_POST array element to this function converts all characters (except space and single
<p>quote) that have an HTML entity equivalent to that entity. As a result, the content is no
<p>longer truncated. What’s cool is that the HTML entity &amp;quot; is converted back to double
<p>quotes when the form is resubmitted, so there’s no need for any further conversion.
<p>That’s the theory—now let’s put it into practice.
<p><b>1. </b>Amend the &lt;input&gt; tag for the Name text field like this:
<p>&lt;input name=&#8221;name&#8221; type=&#8221;text&#8221; class=&#8221;textInput&#8221; id=&#8221;name&#8221;
<p><b>&lt;?php if (isset($missing)) {</b>
<p><b>echo &#8216;value=&#8221;&#8216;.htmlentities($_POST['name']).&#8217;&#8221;&#8216;;</b>
<p><b>} ?&gt;</b>
<p>/&gt;
<p><b>Creating sticky form fields</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>346</b>
<p>This code is quite short, but the line inside the curly braces contains a tricky combination
<p>of quotes and periods. The first thing to realize is that there’s only one
<p>semicolon—right at the end—so the echo command applies to the whole line. You
<p>can break down the rest of the line into three sections, as follows:
<p>&#8216;value=&#8221;&#8216;.
<p>htmlentities($_POST['name'])
<p>.&#8217;&#8221;&#8216;
<p>The first section outputs value=&#8221; as text and uses the concatenation operator (a
<p>period—see “Joining strings together” in Chapter 10) to join it to the next section,
<p>which passes $_POST['name'] to the htmlentities() function. The final section
<p>uses the concatenation operator again to join the next string, which consists solely
<p>of a double quote. So, if $missing has been set, and $_POST['name'] contains Joe,
<p>you’ll end up with this inside the &lt;input&gt; tag:
<p>&lt;input name=&#8221;name&#8221; type=&#8221;text&#8221; class=&#8221;textInput&#8221; id=&#8221;name&#8221; <b>å</b>
<p><b>value=&#8221;Joe&#8221; </b>/&gt;
<p><b>2. </b>Amend the email input field in the same way, using $_POST['email'].
<p><b>3. </b>The comments text area needs to be handled slightly differently, because
<p>&lt;textarea&gt; tags don’t have a value attribute. You place the PHP block between
<p>the opening and closing tags of the text area like this (new code is shown in bold):
<p>&lt;textarea name=&#8221;comments&#8221; id=&#8221;comments&#8221; cols=&#8221;45&#8243; rows=&#8221;5&#8243;&gt;<b>&lt;?php</b>
<p><b>if (isset($missing)) {</b>
<p><b>echo htmlentities($_POST['comments']);</b>
<p><b>} ?&gt;</b>&lt;/textarea&gt;
<p>It’s important to position the opening and closing PHP tags right up against the
<p>&lt;textarea&gt; tags. If you don’t, you’ll get unwanted whitespace inside the text area.
<p><b>4. </b>Save feedback.php, and test the page. If the first test message earlier in the chapter
<p>was successful, you can upload it to your remote server. If any required fields
<p>are omitted, the form displays the original content along with any error messages.
<p>However, if the form is correctly filled in, the email is sent, an acknowledgment is
<p>displayed, and the input fields are cleared.
<p>If your remote server test didn’t succeed earlier in the chapter, just test locally.
<p>You’ll probably get a PHP error message if all required fields are filled in, but that’s
<p>nothing to worry about. We’re almost at the stage to get your remote server
<p>working.
<p>You can check your code with feedback_06.php.
<p><i>By default, </i>htmlentities() <i>leaves single quotes untouched. Since I chose to wrap the</i>
<p>value <i>attribute in double quotes, this doesn’t matter. To convert a single quote to an</i>
<p><i>HTML entity as well, pass </i>ENT_QUOTES <i>(all uppercase) as a second argument to</i>
<p>htmlentities() <i>like this: </i>htmlentities($_POST['name'], ENT_QUOTES)<i>.</i>
<p>USING PHP TO PROCESS A FORM
<p><b>347</b>
<p><b>11</b>
<p><b>Filtering out potential attacks</b>
<p>A particularly nasty exploit known as email header injection emerged in mid-2005. It seeks
<p>to turn online forms into spam relays. A simple way of preventing this is to look for the
<p>strings “Content-Type:”, “Cc:”, and “Bcc:”, as these are email headers that the attacker
<p>injects into your script in an attempt to trick it into sending HTML email with copies to
<p>many people. If you detect any of these strings in user input, it’s a pretty safe bet that
<p>you’re the target of an attack, so you should block the message. An innocent message may
<p>also be blocked, but the advantages of stopping an attack outweigh that small risk.
<p>In this section, we’ll create a pattern to check for suspect phrases, and pass the form input
<p>to a custom-built function that checks for any matches. The function is one of the snippets
<p>that you installed earlier in the chapter, so the most complex part of the coding is already
<p>done for you. If a match is found, a conditional statement prevents the email from being
<p>sent.
<p><b>1. </b>PHP conditional statements rely on a true/false test to determine whether to execute
<p>a section of code. So the way to filter out suspect phrases is to create a
<p>Boolean variable that is switched to true as soon as one of those phrases is
<p>detected. The detection is done using a search pattern or <b>regular expression</b>. Insert
<p>the code for both of these just above the section that processes the $_POST
<p>variables:
<p>// create empty array for any missing fields
<p>$missing = array();
<p><b>// assume that there is nothing suspect</b>
<p><b>$suspect = false;</b>
<p><b>// create a pattern to locate suspect phrases</b>
<p><b>$pattern = &#8216;/Content-Type:|Bcc:|Cc:/i&#8217;;</b>
<p>// process the $_POST variables
<p>The string assigned to $pattern will be used to perform a case-insensitive search
<p>for any of the following: “Content-Type:”, “Bcc:”, or “Cc:”. It’s written in a format
<p>called Perl-compatible regular expression (PCRE). The search pattern is enclosed in
<p>a pair of forward slashes, and the i after the final slash makes the pattern case
<p>insensitive.
<p><b>2. </b>You can now use $pattern to filter out any suspect user input from the $_POST
<p>array. At the moment, each element of the $_POST array contains only a string.
<p>However, multiple-choice form elements, such as checkboxes, return an array of
<p>results. So you need to tunnel down any subarrays and check the content of each
<p>element separately. In the snippets collection that you installed earlier in the chapter,
<p>you’ll find a custom-built function to do precisely that.
<p>Insert two blank lines immediately after the $pattern variable from step 1. Then
<p>open the Snippets panel, and double-click Suspect pattern filter in the PHP-DWCS3
<p>folder to insert the code shown here in bold:
<p><b>Blocking emails that contain specific phrases</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>348</b>
<p>// create a pattern to locate suspect phrases
<p>$pattern = &#8216;/Content-Type:|Bcc:|Cc:/i&#8217;;
<p><b>// function to check for suspect phrases</b>
<p><b>function isSuspect($val, $pattern, &amp;$suspect) {</b>
<p><b>// if the variable is an array, loop through each element</b>
<p><b>// and pass it recursively back to the same function</b>
<p><b>if (is_array($val)) {</b>
<p><b>foreach ($val as $item) {</b>
<p><b>isSuspect($item, $pattern, $suspect);</b>
<p><b>}</b>
<p><b>}</b>
<p><b>else {</b>
<p><b>// if one of the suspect phrases is found, set Boolean to true</b>
<p><b>if (preg_match($pattern, $val)) {</b>
<p><b>$suspect = true;</b>
<p><b>}</b>
<p><b>}</b>
<p><b>}</b>
<p><b>3. </b>I won’t go into detail about how this code works. All you need to know is that calling
<p>the isSuspect() function is very easy. You just pass it three values: the $_POST
<p>array, the pattern, and the $suspect Boolean variable. Insert the following code
<p>immediately after the code in the previous step:
<p>// check the $_POST array and any subarrays for suspect content
<p>isSuspect($_POST, $pattern, $suspect);
<p><b>4. </b>If any suspect phrases are detected, the value of $suspect changes to true, so you
<p>need to set $mailSent to false and delete the $missing array to prevent the email
<p>from being sent and to display an appropriate message in the form. There’s also no
<p>point in processing the $_POST array any further. Wrap the code that processes the
<p>$_POST variables in the second half of an if . . . else statement like this:
<p><b>if ($suspect) {</b>
<p><b>$mailSent = false;</b>
<p><b>unset($missing);</b>
<p><b>}</b>
<p><b>else {</b>
<p>// process the $_POST variables
<p>foreach ($_POST as $key =&gt; $value) {
<p>// assign to temporary variable and strip whitespace if not an array
<p>$temp = is_array($value) ? $value : trim($value);
<p>// if empty and required, add to $missing array
<p>if (empty($temp) &amp;&amp; in_array($key, $required)) {
<p>array_push($missing, $key);
<p>}
<p>// otherwise, assign to a variable of the same name as $key
<p>elseif (in_array($key, $expected)) {
<p>${$key} = $temp;
<p>USING PHP TO PROCESS A FORM
<p><b>349</b>
<p><b>11</b>
<p>}
<p>}
<p><b>}</b>
<p>Don’t forget the extra curly brace to close the else statement.
<p><b>5. </b>If suspect content is detected, you don’t want the code that builds and sends the
<p>email to run, so amend the condition in the opening if statement like this:
<p>// go ahead only if <b>not suspect and </b>all required fields OK
<p>if (<b>!$suspect &amp;&amp; </b>empty($missing)) {
<p>// build the message
<p><b>6. </b>Save feedback.php, and check your code against feedback_07.php.
<p>Because the if statement in step 4 sets $mailSent to false and unsets $missing if it
<p>detects any suspect pattern, the code in the main body of the page displays the same message
<p>that’s displayed if there’s a genuine problem with the server. A neutral message
<p>reveals nothing that might assist an attacker. It also avoids offending anyone who may
<p>have innocently used a suspect phrase.
<p>You can use isSuspect() with any array or pattern, but it always requires the following
<p>three arguments:
<p>An array that you want to filter. If the array contains other arrays, the function burrows
<p>down until it finds a simple value against which it can match the pattern.
<p>A regular expression containing the pattern(s) you want to search for. There are
<p>two types of regular expression, Perl-compatible (PCRE), and Portable Operating
<p>System Interface (POSIX). You must use a PCRE. This function won’t work with a
<p>POSIX regular expression. A good online source is http://regexlib.com.
<p>A Boolean variable set to false. If the pattern is found, the value is switched to
<p>true.
<p><b>Safely including the user’s address in email headers</b>
<p>Up to now, I’ve avoided using one of the most useful features of the PHP mail() function:
<p>the ability to add extra email headers with the optional fourth argument. A popular use of
<p>extra headers is to incorporate the user’s email address into a Reply-To header, which
<p>enables you to reply directly to incoming messages by clicking the Reply button in your
<p>email program. It’s convenient, but it provides a wide open door for an attacker to supply
<p>a spurious set of headers. With the isSuspect() function in place, you can block attacks
<p>and safely use the fourth argument with the mail() function.
<p>The most important header that you should add is From. Email sent by mail() is often
<p>identified as coming from nobody@servername. Adding the From header not only identifies
<p>your mail in a more user-friendly way, but it also solves the problem you might have
<p>encountered on the first test of there being no setting for sendmail_from in php.ini.
<p>You can find a full list of email headers at www.faqs.org/rfcs/rfc2076, but some of the
<p>most well-known and useful ones enable you to send copies of an email to other
<p>addresses (Cc and Bcc) or to change the encoding (often essential for languages other
<p>than Western European ones).
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>350</b>
<p>Like the body of the email message, headers must be passed to the mail() function as a
<p>single string. Each new header, except the final one, must be on a separate line terminated
<p>by a carriage return and new line character. This means using the \r and \n escape
<p>sequences in double-quoted strings.
<p>Let’s say you want to send copies of messages to other departments, plus a copy to
<p>another address that you don’t want the others to see. This is how you pass those additional
<p>email headers to mail():
<p>$headers = &#8220;From: Essential Guide&lt;feedback@example.com&gt;\r\n&#8221;;
<p>$headers .= &#8220;Cc: sales@example.com, finance@example.com\r\n&#8221;;
<p>$headers .= &#8216;Bcc: secretplanning@example.com&#8217;;
<p>$mailSent = mail($to, $subject, $message, $headers);
<p>The default encoding for email is iso-8859-1 (English and Western European). If you want
<p>to use a different encoding, set the Content-Type header. For Unicode (UTF-8), set it
<p>like this:
<p>$headers = &#8220;Content-Type: text/plain; charset=utf-8\r\n&#8221;;
<p>The web page that the form is embedded in must use the same encoding (usually set in a
<p>&lt;meta&gt; tag).
<p>Hard-coded additional headers present no security risk, but anything that comes from user
<p>input must be filtered before it’s used.
<p>This section incorporates the user’s email address into a Reply-To header. Although
<p>isSuspect() should sanitize user input, it’s worth subjecting the email field to a more rigorous
<p>check to make sure that it doesn’t contain illegal characters or more than one
<p>address.
<p><b>1. </b>At the moment, the $required array doesn’t include email, and you may be happy
<p>to leave it that way. So, to keep the validation routine flexible, it makes more sense
<p>to handle the email address outside the main loop that processes the $_POST array.
<p>If email is required but has been left blank, the loop will have already added
<p>email to the $missing array, so the message won’t get sent anyway.
<p>If it’s not a required field, you need to check $email only if it contains something.
<p>So you need to wrap the validation code in an if statement that uses
<p>!empty().
<p>Insert the code shown in bold after the loop that processes the $_POST array.
<p>// otherwise, assign to a variable of the same name as $key
<p>elseif (in_array($key, $expected)) {
<p>${$key} = $temp;
<p>}
<p>}
<p>}
<p><b>Adding email headers and automating the reply address</b>
<p>USING PHP TO PROCESS A FORM
<p><b>351</b>
<p><b>11</b>
<p><b>// validate the email address</b>
<p><b>if (!empty($email)) {</b>
<p><b>}</b>
<p>// go ahead only if not suspect and all required fields OK
<p>if (!$suspect &amp;&amp; empty($missing)) {
<p><b>2. </b>Position your cursor on the blank line between the curly braces of the conditional
<p>statement you have just inserted. Open the Snippets panel, and double-click Check
<p>email PCRE in the PHP-DWCS3 folder. This inserts the following regular expression:
<p>$checkEmail = &#8216;/^[^@]+@[^\s\r\n\'";,@%]+$/&#8217;;
<p>Designing a regular expression to recognize a valid-looking email address is notoriously
<p>difficult. So, instead of striving for perfection, $checkEmail, takes a negative
<p>approach by rejecting characters that are illegal in an email address. However, to
<p>make sure that the input resembles an email address in some way, it checks for an
<p>@ mark surrounded by at least one character on either side.
<p><b>3. </b>Now add the code shown in bold to check $email against the regular expression:
<p>// validate the email address
<p>if (!empty($email)) {
<p>// regex to ensure no illegal characters in email address
<p>$checkEmail = &#8216;/^[^@]+@[^\s\r\n\'";,@%]+$/&#8217;;
<p><b>// reject the email address if it doesn&#8217;t match</b>
<p><b>if (!preg_match($checkEmail, $email)) {</b>
<p><b>$suspect = true;</b>
<p><b>$mailSent = false;</b>
<p><b>unset($missing);</b>
<p><b>}</b>
<p>}
<p>The conditional statement uses the preg_match(), which takes two arguments: a
<p>PCRE and the string that you want to check. If a match is found, the function
<p>returns true. Since it’s preceded by the negative operator, the condition is true if
<p>the contents of $email <i>don’t </i>match the PCRE.
<p>If there’s no match, $suspect is set to true, $mailSent is set to false, and
<p>$missing is unset. This results in the neutral alert saying that the message can’t be
<p>sent and clears the form. This runs the risk that someone who has accidentally
<p>mistyped the email address will be forced to enter everything again. If you don’t
<p>want that to happen, you can omit unset($missing);. However, the PCRE detects
<p>illegal characters that are unlikely to be used by accident, so I have left it in.
<p><i>Many popular PHP scripts use pattern-matching functions that begin with </i>ereg<i>.</i>
<p><i>These work only with POSIX regular expressions. I recommend that you always</i>
<p><i>use the PCRE functions that begin with </i>preg_<i>. Not only is PCRE more efficient,</i>
<p><i>there’s a strong likelihood that support for the </i>ereg <i>family of functions will be</i>
<p><i>removed from a future version of PHP.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>352</b>
<p><b>4. </b>Now add the additional headers to the email. Place them immediately above the
<p>call to the mail() function, and add $headers as the fourth argument like this:
<p>// limit line length to 70 characters
<p>$message = wordwrap($message, 70);
<p><b>// create additional headers</b>
<p><b>$headers = &#8216;From: Essential Guide&lt;feedback@example.com&gt;&#8217;;</b>
<p><b>if (!empty($email)) {</b>
<p><b>$headers .= &#8220;\r\nReply-To: $email&#8221;;</b>
<p><b>}</b>
<p>// send it
<p>$mailSent = mail($to, $subject, $message<b>, $headers</b>);
<p>If you don’t want email to be a required field, there’s no point in using a nonexistent
<p>value in the Reply-To header, so I have wrapped it in a conditional statement.
<p>Since you have no way of telling whether the Reply-To header will be created, it
<p>makes sense to put the carriage return and new line characters at the beginning of
<p>the second header. It doesn’t matter whether you put them at the end of one
<p>header or the start of the next one, as long as a carriage return and new line separates
<p>each header. For instance, if you wanted to add a Cc header, you could do it
<p>like this:
<p>$headers = <b>&#8220;</b>From: Essential Guide&lt;feedback@example.com&gt;<b>\r\n&#8221;</b>;
<p><b>$headers .= &#8216;Cc: admin@example.com&#8217;;</b>
<p>if (!empty($email)) {
<p>$headers .= &#8220;\r\nReply-To: $email&#8221;;
<p>}
<p>Or like this:
<p>$headers = &#8216;From: Essential Guide&lt;feedback@example.com&gt;&#8217;;
<p>$headers .= <b>&#8220;\r\n</b>Cc: admin@example.com<b>&#8220;</b>;
<p>if (!empty($email)) {
<p>$headers .= &#8220;\r\nReply-To: $email&#8221;;
<p>}
<p>If your hosting company requires you to supply the fifth argument to mail() for
<p>security reasons, you should add it after the headers. Normally, it takes the form of
<p>-f followed by your email address like this:
<p>$mailSent = mail($to,$subject,$message,$headers<b>,&#8217;-fdavid@example.com&#8217;</b>);
<p>Use this fifth argument <i>only </i>if instructed to do so by your hosting company.
<p><b>5. </b>Save feedback.php, upload it to your remote server, and test the form. When you
<p>receive the email, click the Reply button in your email program, and you should see
<p>the address that you entered in the form automatically entered in the recipient’s
<p>address field. You can check your code against feedback_08.php.
<p>USING PHP TO PROCESS A FORM
<p><b>353</b>
<p><b>11</b>
<p><b>Handling multiple-choice form elements</b>
<p>You now have the basic knowledge to process text input from an online form and email it
<p>to your inbox. The principle behind handling multiple-choice elements is exactly the same:
<p>the name attribute is used as the key in the $_POST array. However, as you saw in Chapter
<p>9, checkboxes and multiple-choice lists don’t appear in the $_POST array if nothing has
<p>been selected, so they require different treatment.
<p>The following exercises show you how to handle each type of multiple-choice element. If
<p>you’re feeling punch drunk at this stage, come back later to study how to handle multiplechoice
<p>elements when you need to incorporate them into a script of your own.
<p>In Chapter 9, I showed you how to create a checkbox group, which stores all checked
<p>values in a subarray of the $_POST array. However, the subarray isn’t even created if all
<p>boxes are left unchecked. So you need to use isset() to check the existence of the subarray
<p>before attempting to process it.
<p><b>1. </b>Add the name of the checkbox group to the $expected array like this:
<p>$expected = array(&#8216;name&#8217;, &#8216;email&#8217;, &#8216;comments&#8217;<b>, &#8216;interests&#8217;</b>);
<p>In the form, interests is followed by square brackets like this:
<p>&lt;input type=&#8221;checkbox&#8221; name=&#8221;interests[]&#8221; . . .
<p>The square brackets in the form tell the $_POST array to store all checked values in
<p>a subarray called $_POST['interests']. However, <i>don’t </i>add square brackets to
<p>interests in the $expected array. Doing so would bury the checked values in a
<p>subarray one level deeper than you want. See “Using arrays to store multiple
<p>values” in Chapter 10 for a reminder of how arrays are created.
<p><b>2. </b>If you want the checkboxes to be required, add the name of the checkbox group to
<p>the $required array in the same way.
<p><b>3. </b>Because the checkbox array might never be created, you need to set a default
<p>value before attempting to build the body of the email. The following code in bold
<p>goes in the section that prepares the message prior to sending it:
<p>// go ahead only if not suspect and all required fields OK
<p>if (!$suspect &amp;&amp; empty($missing)) {
<p><b>// set default values for variables that might not exist</b>
<p><b>$interests = isset($interests) ? $interests : array(&#8216;None selected&#8217;);</b>
<p><b>Getting data from checkboxes</b>
<p><i>When building your own forms, don’t forget to add the </i>name <i>of each text field to the</i>
<p>$expected <i>array. Also add the </i>name <i>of required fields to the </i>$required <i>array, and add</i>
<p><i>a suitable alert as described in “Checking required fields.”</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>354</b>
<p>This uses the conditional operator (see “Using the conditional operator” in
<p>Chapter 10) to check whether $interests has been set. If it has, the existing array
<p>of checked values is reassigned to $interests. Otherwise, a single-element array
<p>containing the string None selected is created and assigned to $interests. It
<p>needs to be an array, even though it contains only one element, because the next
<p>step expects an array.
<p><b>4. </b>To extract the values of the checkbox array, you can use the oddly named
<p>implode() function, which joins array elements. It takes two arguments: a string to
<p>be used as a separator and the array. So, implode(&#8216;, &#8216;, $interests) joins the elements
<p>of $interests as a comma-separated string. Add the following code shown
<p>in bold to the script that builds the body of the email:
<p>$message .= &#8220;Comments: $comments<b>\n\n</b>&#8220;;
<p><b>$message .= &#8216;Interests: &#8216;.implode(&#8216;, &#8216;, $interests);</b>
<p>Note that I added two new line characters at the end of the line that adds the
<p>user’s comments to the email. On the following line, I put Interests: in single
<p>quotes because there are no variables to be processed, and I used the concatenation
<p>operator to join the result of implode(&#8216;, &#8216;, $interests) to the end of the
<p>email message. You cannot include a function inside a string.
<p><b>5. </b>The next listing shows the code for the first two checkboxes in the body of the
<p>page. The code in bold preserves the user’s selections if a required field is missing.
<p>&lt;p&gt;
<p>&lt;input name=&#8221;interests[]&#8221; type=&#8221;checkbox&#8221; id=&#8221;interests-classical&#8221; <b>å</b>
<p>value=&#8221;Classical concerts&#8221;
<p><b>&lt;?php</b>
<p><b>$OK = isset($_POST['interests']) ? true : false;</b>
<p><b>if ($OK &amp;&amp; isset($missing) &amp;&amp; in_array(&#8216;Classical concerts&#8217;, </b><b>å</b>
<p><b>$_POST['interests'])) {</b>
<p><b>echo &#8216;checked=&#8221;checked&#8221;&#8216;;</b>
<p><b>} ?&gt;</b>
<p>/&gt;
<p>&lt;label for=&#8221;interests-classical&#8221;&gt;Classical concerts&lt;/label&gt;
<p>&lt;/p&gt;
<p>&lt;p&gt;
<p>&lt;input name=&#8221;interests[]&#8221; type=&#8221;checkbox&#8221; id=&#8221;interests-rock&#8221; <b>å</b>
<p>value=&#8221;Rock/pop&#8221;
<p><b>&lt;?php</b>
<p><b>if ($OK &amp;&amp; isset($missing) &amp;&amp; in_array(&#8216;Rock/pop&#8217;, </b><b>å</b>
<p><b>$_POST['interests'])) {</b>
<p><b>echo &#8216;checked=&#8221;checked&#8221;&#8216;;</b>
<p><b>} ?&gt;</b>
<p>/&gt;
<p>&lt;label for=&#8221;interests-rock&#8221;&gt;Rock/pop events&lt;/label&gt;
<p>&lt;/p&gt;
<p>USING PHP TO PROCESS A FORM
<p><b>355</b>
<p><b>11</b>
<p>The code in the first checkbox contains the following line:
<p>$OK = isset($_POST['interests']) ? true : false;
<p>This checks whether $_POST['interests'] exists (it won’t if the user didn’t select
<p>any checkboxes). If it does, $OK is set to true.
<p>The PHP code for each checkbox tests three conditions: the value of $OK, whether
<p>the $missing variable exists, and whether the value of the checkbox is in the
<p>$_POST['interests'] subarray. If all are true, echo inserts checked=&#8221;checked&#8221;
<p>into the &lt;input&gt; tag. (If you’re using HTML instead of XHTML, use just checked.)
<p>Although it looks like a lot of hand-coding, you can copy and paste the code after
<p>creating the first one. Just change the first argument of in_array() to the value of
<p>the checkbox. The complete code is in feedback_09.php.
<p>If you want to make the checkbox group required, add an alert in the same way as
<p>described in “Checking required fields” earlier in the chapter.
<p>Drop-down menus created with the &lt;select&gt; tag normally allow the user to pick only one
<p>option from several. One item is always selected, even if it’s only the first one inviting the
<p>user to select one of the others. Setting the value of this first &lt;option&gt; to 0 has the advantage
<p>that the empty() function, which is used to check required fields, returns true when
<p>0 is passed to it either as a number or string.
<p><b>1. </b>Add the name of the drop-down menu to the $expected array. Also add it to the
<p>$required array if you want a choice to be compulsory.
<p><b>2. </b>Add the value of the drop-down menu to the email message like this:
<p>$message .= &#8216;Interests: &#8216;.implode(&#8216;, &#8216;, $interests)<b>.&#8221;\n\n&#8221;</b>;
<p><b>$message .= &#8220;Visited: $visited&#8221;;</b>
<p>One option will always be selected, so this doesn’t need special treatment.
<p>However, change the value of the first &lt;option&gt; tag in the menu to No response if
<p>it isn’t a required field. Leave it as 0 if you want the user to make a selection.
<p><b>3. </b>The following code shows the first two items of the drop-down menu in
<p>feedback.php. The PHP code highlighted in bold assumes that the menu has been
<p>made a required field and resets the selected option if an incomplete form is submitted.
<p>When the page first loads, the $_POST array contains no elements, so you
<p>can select the first &lt;option&gt; by testing for !$_POST. Once the form is submitted,
<p>the $_POST array always contains an element from a drop-down menu, so you don’t
<p>need to test for it.
<p>&lt;label for=&#8221;visited&#8221;&gt;How often have you been to London? <b>&lt;?php</b>
<p><b>if (isset($missing) &amp;&amp; in_array(&#8216;visited&#8217;, $missing)) { ?&gt;</b>
<p><b>&lt;span class=&#8221;warning&#8221;&gt;Please select a value&lt;/span&gt;&lt;?php } ?&gt;</b>&lt;/label&gt;
<p>&lt;select name=&#8221;visited&#8221; id=&#8221;visited&#8221;&gt;
<p>&lt;option value=&#8221;0&#8243;
<p><b>&lt;?php</b>
<p><b>if (!$_POST || $_POST['visited'] == &#8216;0&#8242;) {</b>
<p><b>Getting data from a drop-down menu</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>356</b>
<p><b>echo &#8217;selected=&#8221;selected&#8221;&#8216;;</b>
<p><b>} ?&gt;</b>
<p>&gt;&#8211; Select one &#8211;&lt;/option&gt;
<p>&lt;option value=&#8221;Never&#8221;
<p><b>&lt;?php</b>
<p><b>if (isset($missing) &amp;&amp; $_POST['visited'] == &#8216;Never&#8217;) {</b>
<p><b>echo &#8217;selected=&#8221;selected&#8221;&#8216;;</b>
<p><b>} ?&gt;</b>
<p>&gt;Never been&lt;/option&gt;
<p>. . .
<p>&lt;/select&gt;
<p>When setting the second condition for each &lt;option&gt;, it’s vital that you use the
<p>same spelling and mixture of uppercase and lowercase as contained in the value
<p>attribute. PHP is case sensitive and won’t match the two values if there are any
<p>differences.
<p>The finished code is in feedback_10.php.
<p>Multiple-choice lists are similar to checkboxes: they allow the user to choose zero or more
<p>items, so the result is stored in an array. If no items are selected, the $_POST array contains
<p>no reference to the list, so you need to take that into consideration both in the form and
<p>when processing the message.
<p><b>1. </b>Add the name of the multiple-choice list to the $expected array. Also add it to the
<p>$required array if you want a choice to be compulsory.
<p><b>2. </b>In the code that processes the message, set a default value for a multiple-choice list
<p>in the same way as for an array of checkboxes.
<p>$interests = isset($interests) ? $interests : array(&#8216;None selected&#8217;);
<p><b>$views = isset($views) ? $views : array(&#8216;None selected&#8217;);</b>
<p><b>3. </b>When building the body of the message, use implode() to create a comma-separated
<p>string, and add it to the message like this:
<p>$message .= &#8220;Visited: $visited<b>\n\n</b>&#8220;;
<p><b>$message .= &#8216;Impressions of London: &#8216;.implode(&#8216;, &#8216;, $views);</b>
<p><b>4. </b>The following code shows the first two items from the multiple-choice list in
<p>feedback.php. The code works in an identical way to the checkboxes, except that
<p>you echo &#8217;selected=&#8221;selected&#8221;&#8216; instead of &#8216;checked=&#8221;checked&#8221;&#8216;. You can reuse
<p>$OK here, because its value is reset by the code in the first &lt;option&gt; tag.
<p>&lt;select name=&#8221;views[]&#8221; size=&#8221;6&#8243; multiple=&#8221;multiple&#8221; id=&#8221;views&#8221;&gt;
<p>&lt;option value=&#8221;Vibrant/exciting&#8221;
<p><b>&lt;?php</b>
<p><b>$OK = isset($_POST['views']) ? true : false;</b>
<p><b>if ($OK &amp;&amp; isset($missing) &amp;&amp; in_array(&#8216;Vibrant/exciting&#8217;, </b><b>å</b>
<p><b>$_POST['views'])) {</b>
<p><b>Getting data from a multiple-choice list</b>
<p>USING PHP TO PROCESS A FORM
<p><b>357</b>
<p><b>11</b>
<p><b>echo &#8217;selected=&#8221;selected&#8221;&#8216;;</b>
<p><b>} ?&gt;</b>
<p>&gt;A vibrant, exciting city&lt;/option&gt;
<p>&lt;option value=&#8221;Good food&#8221;
<p><b>&lt;?php</b>
<p><b>if ($OK &amp;&amp; isset($missing) &amp;&amp; in_array(&#8216;Good food&#8217;, </b><b>å</b>
<p><b>$_POST['views'])) {</b>
<p><b>echo &#8217;selected=&#8221;selected&#8221;&#8216;;</b>
<p><b>} ?&gt;</b>
<p>&gt;A great place to eat&lt;/option&gt;
<p>. . .
<p>&lt;/select&gt;
<p>The completed code is in feedback_11.php.
<p>If you want to make the multiple-choice list required, add an alert in the same way as
<p>described in “Checking required fields” earlier in the chapter.
<p>Radio button groups allow you to pick only one value. This makes it easy to retrieve the
<p>selected one. All buttons in the same group must share the same name attribute, so the
<p>$_POST array contains the value attribute of whichever radio button is selected. However,
<p>if you don’t set a default button in your form, the radio button group’s $_POST array element
<p>remains unset.
<p><b>1. </b>Add the name of the radio button group to the $expected array.
<p><b>2. </b>If you haven’t set a default button and you want a choice to be compulsory, also
<p>add it to the $required array. This isn’t necessary if a default choice is set in the
<p>form.
<p><b>3. </b>If you haven’t set a default button, you need to set a default value before building
<p>the body of the email message. You do this in a similar way to a checkbox group or
<p>multiple-choice list, but since a radio button group can have only one value, you
<p>set the default as a string, not an array, as shown in this example:
<p>$radio = isset($radio) ? $radio : &#8216;Not selected&#8217;;
<p><b>4. </b>Add the value of the radio button group to the body of the message like this:
<p>$message .= &#8216;Impressions of London: &#8216;.implode(&#8216;, &#8216;, $views).&#8221;\n\n&#8221;;
<p><b>$message .= &#8220;Subscribe: $subscribe&#8221;;</b>
<p><b>5. </b>Assuming a default button has been defined, amend the radio button group like
<p>this:
<p>&lt;input type=&#8221;radio&#8221; name=&#8221;subscribe&#8221; id=&#8221;subscribe-yes&#8221; value=&#8221;y&#8221;
<p><b>&lt;?php</b>
<p><b>if (isset($missing) &amp;&amp; $_POST['subscribe'] == &#8216;y&#8217;) {</b>
<p><b>echo &#8216;checked=&#8221;checked&#8221;&#8216;;</b>
<p><b>Getting data from radio button groups</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>358</b>
<p><b>} ?&gt;</b>
<p>/&gt;
<p>&lt;label for=&#8221;subscribe-yes&#8221;&gt;Yes&lt;/label&gt;
<p>&lt;input name=&#8221;subscribe&#8221; type=&#8221;radio&#8221; id=&#8221;subscribe-no&#8221; value=&#8221;n&#8221;
<p><b>&lt;?php</b>
<p><b>if (!$_POST || isset($missing) &amp;&amp; $_POST['subscribe'] == &#8216;n&#8217;) {</b>
<p><b>echo &#8216;</b>checked=&#8221;checked&#8221;<b>&#8216;;</b>
<p><b>} ?&gt;</b>
<p>/&gt;
<p>&lt;label for=&#8221;subscribe-no&#8221;&gt;No&lt;/label&gt;
<p>The conditional statement for the default radio button begins with !$_POST ||,
<p>which means “if the $_POST array is empty <i>or </i>. . .” So, if the form hasn’t been submitted,
<p>or if the user has selected No and the form is incomplete, this button will
<p>be checked.
<p>The completed script is in feedback_12.php.
<p>If no default button has been defined, add the same $OK check as for a checkbox group or
<p>multiple-choice list in the first &lt;input&gt; tag, as well as in the conditional statement for each
<p>radio button. You need to add a required alert only if no default has been defined in the
<p>original form.
<p><b>Redirecting to another page</b>
<p>Everything has been kept within the same page, even if the message is sent successfully. To
<p>redirect the visitor to a different page, change the code at the end of the messageprocessing
<p>section like this:
<p>// send it
<p>$mailSent = mail($to, $subject, $message, $headers);
<p>if ($mailSent) {
<p><b>// redirect the page with a fully qualified URL</b>
<p><b>header(&#8216;Location: http://www.example.com/thanks.php&#8217;);</b>
<p><b>exit;</b>
<p>}
<p>}
<p>}
<p>The HTTP/1.1 protocol stipulates a fully qualified URL for a redirect command, although
<p>most browsers will perform the redirect correctly with a relative pathname.
<p>When using the header() function, you must be careful that no output is sent to the
<p>browser before PHP attempts to call it. If, when testing your page, you see an error message
<p>warning you that headers have already been sent, check there are no characters,
<p>including new lines, spaces, or tabs ahead of the opening PHP tag.
<p>USING PHP TO PROCESS A FORM
<p><b>359</b>
<p><b>11</b>
<p><b>Time for a breather . . .</b>
<p>If that was your first encounter with PHP, your head will probably be reeling. This has been
<p>a tough chapter. In the next chapter, you’ll adapt this script so that it can be reused as an
<p>external file with most forms. The external file never changes, and the hand-coding is cut
<p>down to about a dozen lines. I could, of course, have given you the external file without
<p>explanation, but if you don’t understand the code, you can’t adapt it to your own requirements.
<p>Even if you never write an original PHP script of your own, you should know what
<p>the code in your page is doing. If you don’t, you’re storing up trouble for the future.
<p>What makes PHP pages dynamic—and so powerful—is the fact that your code makes decisions,
<p>even though you have no way of knowing in advance what is going to be input into
<p>the form. The Dreamweaver code that you’ll encounter in subsequent chapters tries to
<p>anticipate a lot of these unknown factors, but its beauty lies in the fact that it’s configurable.
<p>If you know how to hand-code, you can get Dreamweaver to do a lot of the hard
<p>work for you, and then take it beyond the basics.
<p>However, it’s no fun spending all your time churning out code. Life becomes simpler if you
<p>can reuse code. So that’s what the next chapter is about—saving time with includes and
<p>Dreamweaver templates.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>360</b>
<p>12 <b>WORKING WITH PHP INCLUDES</b>
<p><b>AND TEMPLATES</b>
<p>To give a unified look to a website, most pages have common elements, such as a header,
<p>navigation menu, and footer. Nobody likes repeating work just for the sake of it, so the
<p>ability to build page templates has long been one of Dreamweaver’s most popular features.
<p>All common features can be defined and locked, but Dreamweaver propagates to all
<p>child pages any changes that you make to the master template. The great disadvantage is
<p>that every time you make a change all the affected pages must be uploaded again to your
<p>remote server. On a large site, this can be a major undertaking.
<p>Wouldn’t it be wonderful if you could make changes to just a single page and have them
<p>reflected through the site in the same way as CSS? Well, with PHP includes, you can. As the
<p>name suggests, the contents of an include file are included and treated as an integral part
<p>of the page. They can contain anything that you would normally find in a PHP page: plain
<p>text, XHTML, and PHP code. The file name extension doesn’t even need to be .php,
<p>although for security it’s common practice to use it.
<p>Dreamweaver makes working with includes easy thanks to its ability to display the contents
<p>of an include in Design view (or Live Data view for dynamic content). Many people
<p>find includes so useful that they stop using templates. Nevertheless, templates can be useful,
<p>particularly for small sites, so this chapter covers both approaches.
<p>In this chapter, you’ll learn how to
<p>Use PHP includes for common page elements
<p>Store frequently used code in the Snippets panel
<p>Apply CSS to page fragments with Design Time Style Sheets
<p>Export a navigation menu to an external file
<p>Adapt the mail processing script to work with other forms
<p>Avoid the “headers already sent” error with includes
<p>Use Dreamweaver templates in a PHP site
<p>To start with, let’s take a quick look at how you create a PHP include.
<p><b>Including text and code from other files</b>
<p>The ability to include code from other files is a core part of PHP. All that’s necessary is to
<p>use one of PHP’s include commands and tell the server where to find the file.
<p><b>Introducing the PHP include commands</b>
<p>PHP has four separate commands for creating an include: include(), include_once(),
<p>require(), and require_once(). Why so many? And what’s the difference?
<p>They all do the same thing, but “require” is used in the sense of “mandatory”; everything
<p>comes to a grinding halt if the external file is missing or can’t be opened. The “include”
<p>pair of commands, on the other hand, soldier bravely on. The purpose of _once is to prevent
<p>variables being accidentally overwritten. The PHP engine uses the first instance it
<p>encounters and ignores any duplicates. If in doubt about which to use, choose
<p>include_once() or require_once(). Using them does no harm and could avoid problems.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>364</b>
<p><b>Telling PHP where to find the external file</b>
<p>The include commands take a single argument: a string containing the path of the external
<p>file. While this sounds simple enough, it confuses many Dreamweaver users. PHP looks for
<p>the external file in what’s known as the include_path. By default, this always includes the
<p>current directory (folder), and PHP expects either a relative or an absolute path. <i>It won’t</i>
<p><i>work with a path relative to the site root</i>.
<p>If Links relative to is set to Document in the Local Info category of your site definition (see
<p>Figure 12-1), Dreamweaver automatically uses the correct path for include files. However,
<p>if you have selected Site root as your default style for links, includes won’t work unless you
<p>override the default setting to change the path to a document-relative one or take alternative
<p>measures to set the include_path.
<p><b>Figure 12-1. </b>Dreamweaver’s site definition dialog box lets you specify the default
<p>format of internal links.
<p>A practical exercise should clarify the situation.
<p>In this exercise, you’ll see what happens if you use the wrong type of path for an include
<p>file. You’ll also learn how to override the default setting, so that you can use includes successfully
<p>even if your site definition specifies using links relative to the site root.
<p><b>1. </b>Create a new subfolder called includes in your workfiles folder, and copy
<p>include.txt from examples/includes to the new folder.
<p><b>2. </b>Go to File <b>ä </b>New. Select Blank Page and PHP as the Page Type. Choose any of the
<p>predefined layouts. The one I chose was 2 column fixed, left sidebar. This is only
<p>going to be a test page, so you can leave Layout CSS on Add to Head. Click Create
<p>and save the file as include_test.php in workfiles/ch12.
<p><b>3. </b>Position your cursor at the beginning of the first paragraph under the Main Content
<p>headline. Press Enter/Return to insert a new paragraph, and then press your up
<p>keyboard arrow to move the insertion point into the empty paragraph.
<p><b>4. </b>Select the PHP tab on the Insert bar, and click the Include button as shown in the
<p>following screenshot (alternatively use the menu option Insert <b>ä </b>PHP Objects <b>ä</b>
<p>Include). Dreamweaver opens Split view, inserts a PHP code block complete with an
<p>include() command, and positions the insertion point between the parentheses,
<p>ready for you to enter the path of the external file.
<p><b>Including a text file</b>
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>365</b>
<p><b>12</b>
<p><b>5. </b>The path needs to be a string, so enter a quotation mark (I prefer a single quote,
<p>but it doesn’t matter, as long as the closing quote matches). Dreamweaver’s syntax
<p>coloring turns all the subsequent code red, but this reverts to normal once you
<p>have finished. Position your mouse pointer over the insertion point, and right-click
<p>to bring up a context menu. Select Code Hint Tools <b>ä </b>URL Browser, as shown here:
<p><b>6. </b>This places a tiny Browse icon at the insertion point like this:
<p><b>7. </b>Click the Browse icon to open the Select File dialog box. Navigate to the
<p>workfiles/includes folder, and select include.txt. Before clicking OK, check the
<p>setting of Relative to at the bottom of the dialog box. It displays Document or Site
<p>Root, depending on the default in your site definition (see Chapter 4 and Figure 12-1).
<p>If necessary, change it to Site Root, as shown here, and click OK:
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>366</b>
<p><b>8. </b>Type a closing quote after the path that has just been entered into the include()
<p>command. Syntax coloring turns the rest of the code back to its normal color—a
<p>useful reminder of the importance of matching quotes. Move your cursor further
<p>along the line to remove the &amp;nbsp; just before the closing &lt;/p&gt; tag.
<p><b>9. </b>Click inside Design view. The gold PHP shield should disappear and be replaced by
<p>the content of the external text file. Magic . . . well, not quite.
<p><b>10. </b>Save include_test.php, and press F12/Opt+F12 to view it in a browser. You should
<p>see something like Figure 12-2.
<p><b>Figure 12-2. </b>If PHP can’t find the include file, it displays ugly warning messages.
<p>The first warning says there was no such file or directory, but of course, there is.
<p>The second warning gives a cryptic clue as to why PHP can’t open the file. The
<p>include_path is where PHP looks for include files. The default value on most web
<p>servers is . (a period), which is shorthand for the current working directory, and
<p>either the main PHP folder or pear (PEAR—the PHP Extension and Application
<p>Repository—is a library of extensions to PHP). PHP doesn’t understand a leading
<p>forward slash as meaning the site root, so it starts from the current folder and ends
<p>up in a nonexistent part of the site.
<p><b>11. </b>Go back to the Dreamweaver Document window, and remove the current path;
<p>right-click between the quotes, and use the URL Browser to navigate to
<p>include.txt again, but this time make sure that Relative to is set to Document. Save
<p>include_test.php, and reload it in a browser. The content of the include file
<p>should now be correctly displayed, as shown in Figure 12-3.
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>367</b>
<p><b>12</b>
<p><b>Figure 12-3. </b>The include file is displayed correctly when a relative path is used.
<p><b>12. </b>Go back to Dreamweaver, and change the command from include to require like
<p>this:
<p>&lt;?php <b>require</b>(&#8216;../includes/include/txt&#8217;); ?&gt;
<p><b>13. </b>Save the page, and load it into a browser. It should look identical to Figure 12-3.
<p><b>14. </b>Change the path to point to a nonexistent file, such as includ.txt. When you save
<p>the page and view it in a browser, it should look similar to Figure 12-2, but instead
<p>of the second warning, you should see Fatal error. The other difference is that
<p>there’s no text after the error message. As explained in “Understanding PHP error
<p>messages” in Chapter 10, any output preceding a fatal error is displayed, but once
<p>the error is encountered, everything else is killed stone dead.
<p><b>Using site-root-relative links with includes</b>
<p>As you have just seen, PHP cannot find include files referenced by a site-root-relative link.
<p>My recommendation is that, if you have selected links relative to the site root as your
<p>default, you simply select Relative to Document in the Select File dialog box (as described in
<p>step 10 of the preceding exercise) when creating an include.
<p>Nevertheless, there are a couple of alternatives if you have a pressing reason for wanting
<p>to use links relative to the site root. The problem is that they don’t work on all servers.
<p>The virtual() function accepts both document-relative and site-root-relative paths and
<p>can be used as a direct replacement for include() and require(). It works only when PHP
<p>is run as an Apache module.
<p>$_SERVER['DOCUMENT_ROOT'] is a predefined PHP variable that contains the path of the
<p>server’s root folder, so adding it to the beginning of a site-root-relative link has the effect
<p>of turning it into an absolute path. The following works on most servers:
<p>&lt;?php include(<b>$_SERVER['DOCUMENT_ROOT'].</b>&#8216;/workfiles/includes/ <b>å</b>
<p>include/txt&#8217;); ?&gt;
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>368</b>
<p>Unfortunately, $_SERVER['DOCUMENT_ROOT'] isn’t supported by IIS running PHP in CGI
<p>mode.
<p>To check whether your server supports either method, run server_check.php in
<p>examples/ch12. If both are supported, you should see output similar to this.
<p>If neither is supported and you still want to use site-root-relative links, you need to define
<p>a <b>constant </b>containing the path to the site root. A constant is like a variable, except that
<p>once defined in a script, its value cannot be changed. Constants don’t begin with a dollar
<p>sign, and by convention, they are always in uppercase. You define a constant like this:
<p>define(&#8216;SITE_ROOT&#8217;, &#8216;C:\inetpub\wwwroot\egdwcs3&#8242;);
<p>You could then use SITE_ROOT with a site-root-relative link like this:
<p>&lt;?php include(<b>SITE_ROOT.</b>&#8216;/workfiles/includes/include/txt&#8217;); ?&gt;
<p>The disadvantage with this approach is that you need to include the definition of the constant
<p>in every page that uses includes.
<p><b>Lightening your workload with includes</b>
<p>So far, you have seen only a fairly trivial use of an include to insert a block of text inside a
<p>paragraph. This might be useful in a situation where you want to change the content of
<p>part of a page on a frequent basis without going to the bother of building a databasedriven
<p>content management system. A much more practical use of includes is for content
<p>that appears on many pages, for example a navigation menu or footer. Any changes made
<p>to the include file are immediately reflected throughout the site.
<p><b>Choosing the right file name extension for include files</b>
<p>As I explained at the beginning of the chapter, the external file doesn’t need to have a
<p>.php file name extension. Many developers use .inc as the default file name extension to
<p>make it clear that the file is an include. Although this a common convention, Dreamweaver
<p>doesn’t automatically recognize an .inc file as containing PHP code, so you don’t get code
<p><i>The restriction on site-root-relative links applies only to the include command. Inside</i>
<p><i>include files, </i>all <i>links should be site-root-relative. Document-relative links inside an</i>
<p><i>include file will be broken if the file is included at a different level of the site hierarchy.</i>
<p><i>See “Creating and editing a template-based page” later in the chapter.</i>
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>369</b>
<p><b>12</b>
<p>hints or syntax coloring. More importantly, browsers don’t understand .inc files. So, if
<p>anybody accesses an .inc file directly through a browser (as opposed to it being included
<p>as part of a PHP page), everything is displayed as plain text.
<p>This is a potential security risk if you put passwords or other sensitive information in external
<p>files. One way around this problem is to store include files outside the server root
<p>folder. Many hosting companies provide you with a private folder, which cannot be
<p>reached by a browser. As long as the PHP script knows where to find the external file <i>and</i>
<p>has permission to access it, include files can be outside the server root. However, this
<p>creates problems for Dreamweaver site management.
<p>A simpler, widely adopted solution is to use .inc.php as the file name extension. Browsers
<p>and servers treat only the final .php as the file name extension and automatically pass
<p>the file to the PHP engine if requested directly. The .inc is simply a reminder to you as the
<p>developer that this is an include file.
<p>As long as you store passwords and other sensitive information as PHP variables within PHP
<p>code blocks, and use .php as the final file name extension, your data cannot be seen by
<p>anyone accessing the page directly in a browser (of course, it will be revealed if your code
<p>uses echo or print to display that information, but I assume that you have the sense not
<p>to do that).
<p><b>Displaying XHTML output</b>
<p>When PHP includes an external file, it automatically treats the contents of the external file
<p>as plain text or XHTML. This means that you can cut a section out of an existing page built
<p>in XHTML and convert it into an include file. In order to preserve your sanity, it’s important
<p>to put only complete, logical elements in external files. Putting the opening part of a &lt;div&gt;
<p>in one external file and the closing part in another file is a disaster waiting to happen. It
<p>becomes impossible to keep track of opening and closing tags, and Dreamweaver is likely
<p>to start trying to replace what it regards as missing tags.
<p>Usually, I find the best approach is to build the complete page first, and then convert common
<p>elements into include files.
<p>This exercise shows you how to extract the menu from the “Stroll along the Thames” site
<p>in Chapter 7 and convert it into an include file.
<p><b>1. </b>Copy stroll_horiz.html from examples/ch07 to workfiles/ch12. Also make
<p>sure you have the dependent files: styles/stroll_horiz.css, SpryAssets/
<p>SpryMenuBar.js, and SpryAssets/SpryMenuBarHorizontal_stroll.css.
<p><b>2. </b>Save stroll_horiz.html as stroll_horiz.php. You need to change the file name
<p>extension so that the PHP engine knows to process it and include the external files
<p>you are about to create. Test the page in a browser to make sure that it displays
<p>correctly. It should look like Figure 12-4.
<p><b>Converting a navigation menu into an include</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>370</b>
<p><b>Figure 12-4. </b>The menu is the same on every page of the site, so it is a prime candidate for an
<p>include file.
<p><b>3. </b>Create a new PHP file, and save it in the workfiles/includes folder as
<p>menu.inc.php. You don’t need one of the CSS layouts, as you need a completely
<p>blank page. Switch to Code view in menu.inc.php, and delete everything, including
<p>the DOCTYPE declaration. There should be nothing left in the page.
<p><b>4. </b>Switch to stroll_horiz.php in the Document window. Click anywhere inside the
<p>navigation menu, and click &lt;div#nav&gt; in the Tag selector to select the entire menu.
<p>Switch to Code view, and then cut the menu to your computer clipboard
<p>(Ctrl+X/Cmd+X or Edit <b>ä </b>Cut).
<p>You must be in Code view when cutting the
<p>menu to the clipboard. If you remain in
<p>Design view, Dreamweaver cuts all the Spryrelated
<p>code and pastes it into the include file.
<p>You want to move only the XHTML code and
<p>the Spry object initialization, but they’re in
<p>different parts of the page, so it has to be
<p>done in two steps. Click No, if Dreamweaver
<p>displays the warning shown alongside at any
<p>time during the next few steps. Once you
<p>move the initialization script, the warning
<p>message no longer appears.
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>371</b>
<p><b>12</b>
<p><b>5. </b>Without moving the insertion point, click the Include button on the PHP tab of the
<p>Insert bar (or use the menu alternative). This inserts a PHP code block and positions
<p>your cursor between the parentheses of an include() command.
<p><b>6. </b>Type a single quote, right-click, and use Code Hint Tools <b>ä </b>URL Browser to navigate
<p>to menu.inc.php in the workfiles/includes folder in the same way as in
<p>“Including a text file” earlier in the chapter. In the Select File dialog box, make sure
<p>that Relative to is set to Document. Click OK, and type a closing quote after the path.
<p>Save stroll_horiz.php.
<p><b>7. </b>Switch to menu.inc.php in the Document window. Make sure you are in Code view,
<p>and paste the menu that you cut from stroll_horiz.php. (If you are in Design
<p>view, you won’t get all the XHTML code. Always cut and paste in the same view in
<p>Dreamweaver—Design view to Design view or Code view to Code view.)
<p><b>8. </b>Go back to stroll_horiz.php, scroll down to the bottom of the page, and cut to
<p>your clipboard the section of code highlighted on lines 54–58 in the following
<p>screenshot.
<p>This is the initialization script for the Spry menu bar. Make sure that you have the
<p>opening and closing &lt;script&gt; tags.
<p><b>9. </b>Paste the Spry object initialization script into menu.inc.php after the closing
<p>&lt;/div&gt; tag. Save menu.inc.php, and close the file.
<p><b>10. </b>Switch to Design view in stroll_horiz.php. The menu should be visible as it was
<p>before. If you can’t see the menu, open Preferences from the Edit menu
<p>(Dreamweaver menu on a Mac), select the Invisible Elements category, and make
<p>sure there’s a check mark in Server-Side includes: Show contents of included file.
<p><b>11. </b>Hover your mouse pointer over the navigation menu, and click the turquoise Spry
<p>Menu Bar tab at the top left corner (see Figure 12-5). The Property inspector recognizes
<p>it as a server-side include (SSI) and displays the name of the file, together
<p>with an Edit button. Clicking the Edit button opens the include file in the Document
<p>window ready for editing.
<p><b>12. </b>Test stroll_horiz.php in a browser. It should look like Figure 12-4, and the menu
<p>should work as before. You can check your code against stroll_horiz_menu.php
<p>in examples/ch12 and menu.inc.php in examples/includes.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>372</b>
<p><b>Figure 12-5. </b>When you select the contents of an include file in Design view, the Property inspector
<p>provides a direct link to edit it.
<p>Putting the Spry object initialization script at the end of menu.inc.php results in it being
<p>called earlier than it was in the original page, but it’s still in the right order and doesn’t
<p>result in invalid code. It also prevents the warning in step 4 from being displayed every
<p>time that you open the parent page.
<p>An added advantage is that you can edit the Spry menu through the Property inspector in
<p>the same way as in Chapter 7. Even though the include file has no direct link to the Spry
<p>menu bar external JavaScript file, Dreamweaver automatically finds it because the
<p>Spry assets folder is specified in the site definition.
<p>However, what you put in an external file doesn’t always have such benign consequences.
<p><b>Avoiding problems with include files</b>
<p>The server incorporates the content of an include file into the page at the point of the
<p>include command. If you pasted all the Spry-related code into menu.inc.php, rather than
<p>just the constructor, you would end up with the link to the external style sheet within the
<p>&lt;body&gt; of stroll_horiz.php. Although some browsers might render the page correctly,
<p>&lt;style&gt; blocks are invalid outside the &lt;head&gt; of a web page. If it doesn’t break now, it
<p>probably will sooner or later as browsers get increasingly standards-compliant.
<p>The most common mistake with include files is adding duplicate &lt;head&gt; and &lt;body&gt; tags.
<p>Keep your include files free of extraneous code, and make sure that when everything fits
<p>back together that you have a DOCTYPE declaration, a single &lt;head&gt; and &lt;body&gt;, and that
<p>everything is in the right order.
<p>Dreamweaver depends on the DOCTYPE declaration at the top of a page to determine
<p>whether to use XHTML rules. Code added to an include will normally use HTML style, so
<p>when editing an include, you need to keep a close eye on what is happening in Code view.
<p>This is why I recommend extracting code into include files only toward the end of a project
<p>or if the external file uses mainly dynamic code.
<p><i>An annoying quirk in the way Dreamweaver handles PHP includes in Design view</i>
<p><i>is that the include command must be in its own PHP code block. If you put any</i>
<p><i>other PHP code in the same block—even a comment—Dreamweaver just displays</i>
<p><i>the gold PHP shield.</i>
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>373</b>
<p><b>12</b>
<p>Another common problem is a broken link in an include file. Always use site-root-relative
<p>links inside include files. As explained in Chapter 4, site-root-relative links provide a constant
<p>reference to a page or an asset, such as an image. If you use document-relative links
<p>inside an include file, the relationship—and therefore the link—is broken if the file is
<p>included at a different level of the site hierarchy than where it was originally designed.
<p><b>Applying styles with Design Time Style Sheets</b>
<p>Although Dreamweaver displays the menu normally in stroll_horiz.php, it looks completely
<p>different in menu.inc.php. As Figure 12-6 shows, the menu is completely unstyled;
<p>all you can see is the underlying series of nested unordered lists. Design Time Style Sheets
<p>let you apply the styles in an external style sheet to a page or code fragment without the
<p>need to attach the style sheet directly to the page. As the name suggests, the style sheet is
<p>applied only at design time; in other words, in Design view.
<p><b>Figure 12-6. </b>The include file is completely unstyled.
<p>To apply Design Time Style Sheets to a page or an include file, select CSS Styles <b>ä </b>Designtime
<p>from either the Text menu or from the context menu when right-clicking in Design
<p>view. This opens the Design Time Style Sheets dialog box, as shown in the following
<p>screenshot:
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>374</b>
<p>The dialog box has two sections. The first one, Show only at design time, lets you apply a
<p>style sheet without attaching it to the file. The second one, Hide at design time, works with
<p>style sheets that are attached to a file, letting you hide the effect of selected style sheets
<p>while working in Design view. It’s particularly useful when working with style sheets for different
<p>media, such as print and screen.
<p>Both sections work the same way: add a style sheet to the list by clicking the plus (+)
<p>button and navigating to the style sheet in the site file system. The rules of the CSS
<p>cascade apply, so add multiple style sheets in the same order as to the original page. To
<p>remove a style sheet, highlight it, and click the minus (–) button. Figure 12-7 shows
<p>menu.inc.php after applying workfiles/styles/stroll_horiz.css and SpryAssets/
<p>SpryMenuBarHorizontal_stroll.css as Design Time Style Sheets. It now looks the same
<p>as in the page it was extracted from.
<p><b>Figure 12-7. </b>After applying Design Time Style Sheets, the include file looks the same as in the
<p>original page.
<p>With the Design Time Style Sheets applied, you can manipulate the styles of the include
<p>file by changing the class or ID of individual elements. You can also change the style rules
<p>in the external style sheets through the CSS Styles panel. But—and it’s a rather large
<p>one—you should remember that the code fragment that you’re working with is no longer
<p>in the context of its parent page. As a result, the full effect of the CSS cascade may not be
<p>accurately reflected. Also, changes made to the external style sheet may have unexpected
<p>consequences on other parts of your design. Although useful, Design Time Style Sheets
<p>have their limitations.
<p>Another drawback is that Design Time Style Sheets can be applied to only one page at a
<p>time. There is a commercial extension available that lets you apply Design Time Style
<p>Sheets to an entire site. See www.communitymx.com/abstract.cfm?cid=61265 for details.
<p>Dreamweaver stores details of style sheets applied to a page in this way in a subfolder
<p>called _notes. The subfolder is hidden in the Files panel but can be inspected in Windows
<p>Explorer or Finder.
<p><b>Adding dynamic code to an include</b>
<p>The footer of a page frequently contains details that might change, such as company
<p>address or telephone number, making it an ideal candidate for an include file.
<p>The footer in stroll_horiz.php contains only a copyright notice, which normally changes
<p>only once a year, but with a little PHP magic, you can get it to update automatically at the
<p>stroke of midnight on New Year’s Eve every year. Continue working with the files from the
<p>previous exercise.
<p><b>Automatically updating a copyright notice</b>
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>375</b>
<p><b>12</b>
<p><b>1. </b>Create a PHP page, and save it in workfiles/includes as footer.inc.php. Switch
<p>to Code view and remove all code, so the file is completely blank. Switch to Design
<p>view.
<p><b>2. </b>Open stroll_horiz.php in Design view, and click anywhere inside the copyright
<p>notice at the bottom of the page. Select the entire footer by clicking &lt;div#footer&gt;
<p>in the Tag selector, and cut it to your clipboard.
<p><b>3. </b>Without moving the insertion point, click the Include button on the PHP tab of the
<p>Insert bar. Dreamweaver opens Split view with the cursor placed between the
<p>parentheses of an include() block. Type a single quote, use the URL Browser as
<p>before to insert the path to footer.inc.php, and type a closing quote.
<p><b>4. </b>Switch to footer.inc.php, and paste the contents of your clipboard into Design
<p>view. The footer is unstyled, but if you save footer.inc.php, switch to
<p>stroll_horiz.php, and click in Design view, you’ll see the footer properly styled as
<p>though you had never moved it. Click the copyright notice. The entire text is
<p>selected, and the Property inspector displays the path of the include together with
<p>an Edit button.
<p><b>5. </b>Click the Edit button to open footer.inc.php, and switch to Code view. It contains
<p>the following XHTML:
<p>&lt;div id=&#8221;footer&#8221;&gt;
<p>&lt;p&gt;&amp;copy; Footsore in London&lt;/p&gt;
<p>&lt;!&#8211; end #footer &#8211;&gt;
<p>&lt;/div&gt;
<p><b>6. </b>A copyright notice should have a year. You could just type it in, but the PHP date()
<p>function generates the current year automatically. Add the following code like this:
<p>&lt;p&gt;&amp;copy;
<p><b>&lt;?php</b>
<p><b>ini_set(&#8216;date.timezone&#8217;, &#8216;Europe/London&#8217;);</b>
<p><b>echo date(&#8216;Y&#8217;);</b>
<p><b>?&gt;</b>
<p>Footsore in London&lt;/p&gt;
<p>Chapter 17 explains dates in PHP and MySQL in detail, but let’s take a quick look at
<p>what’s happening here. The core part of the code is this line:
<p>echo date(&#8216;Y&#8217;);
<p>This displays the year using four digits. Make sure you use an uppercase Y. If you
<p>use a lowercase y instead, only the final two digits of the year will be displayed.
<p>The reason for the preceding line is because PHP 5.1.0 or higher requires a valid
<p>time-zone setting. This should be set in php.ini, but if your hosting company forgets
<p>to do this, you may end up with ugly error messages in your page.
<p>What if your hosting company is using an earlier version of PHP? No problem.
<p>Earlier versions simply ignore this line.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>376</b>
<p>Setting the time zone like this is not only good insurance against error messages, it
<p>also allows you to override the hosting company setting, if your host is in a different
<p>time zone from your own. The second argument for ini_set() must be one of
<p>the time zones listed at www.php.net/manual/en/timezones.php.
<p><b>7. </b>Switch to Design view, and click the Live Data view button. You should see the current
<p>year displayed alongside the copyright symbol, as shown here.
<p>Click the Live Data view button again to toggle it off.
<p><b>8. </b>Copyright notices normally cover a range of years, indicating when a site was first
<p>launched. To improve the copyright notice, you need to know two things: the start
<p>year and the current year. Change the PHP code in the paragraph like this:
<p>&lt;p&gt;&amp;copy;
<p>&lt;?php
<p>ini_set(&#8216;date.timezone&#8217;, &#8216;Europe/London&#8217;);
<p><b>$startYear = 2007;</b>
<p><b>$thisYear = date(&#8216;Y&#8217;);</b>
<p><b>if ($startYear == $thisYear) {</b>
<p><b>echo $startYear;</b>
<p><b>}</b>
<p><b>else {</b>
<p><b>echo &#8220;{$startYear}-{$thisYear}&#8221;;</b>
<p><b>}</b>
<p>?&gt;
<p>Footsore in London&lt;/p&gt;
<p>This uses simple conditional logic (if you’re new to PHP, see “Using comparisons to
<p>make decisions” in Chapter 10, and take particular note of the use of two equal
<p>signs in the conditional statement). The static value of $startYear is compared to
<p>the dynamically generated value of $thisYear. If both are the same, only the start
<p>year is displayed; if they’re different, you need to display both with a hyphen
<p>between them.
<p>I’ve used curly braces around the variables in the following line:
<p>echo &#8220;{$startYear}-{$thisYear}&#8221;;
<p>This is because they’re in a double-quoted string that contains no whitespace. The
<p>curly braces enable the PHP engine to identify the beginning and end of the variables.
<p>Since hyphens aren’t permitted in variable names, you could omit the curly
<p>braces on this occasion. However, their presence makes the code easier to read.
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>377</b>
<p><b>12</b>
<p><b>9. </b>Switch back to Design view, and toggle Live Data view on again. Assuming that you
<p>used the current year for $startYear, you’ll see no difference, so experiment by
<p>changing the value of $startYear and alternating between uppercase and lowercase
<p>y in the date() function to see the different output, as shown here:
<p>The values of $startYear, $thisYear, and the name of the copyright owner are the
<p>only things you need to change, and you have a fully automated copyright notice.
<p>You can check your code against footer.inc.php in examples/includes and
<p>stroll_horiz_footer.php in examples/ch12.
<p><b>Using includes to recycle frequently used PHP code</b>
<p>Up to now, all the examples in this chapter have shown you how to include plain text or
<p>XHTML. The last example makes use of PHP code but is specific to one particular site.
<p>Includes become really useful when you create PHP code that can be used in any site. A
<p>simple example is the POST stripslashes snippet that you used in the last chapter. Instead
<p>of putting the code directly inside your script, you could put it in an external file and use
<p>include() to incorporate it.
<p>Let’s take a look at the code again:
<p>// remove escape characters from POST array
<p>if (get_magic_quotes_gpc()) {
<p>function stripslashes_deep($value) {
<p>$value = is_array($value) ? array_map(&#8217;stripslashes_deep&#8217;, <b>å</b>
<p>$value) : stripslashes($value);
<p>return $value;
<p>}
<p>$_POST = array_map(&#8217;stripslashes_deep&#8217;, $_POST);
<p>}
<p>It contains nothing but PHP code, and the code itself consists of a conditional statement
<p>that removes backslashes from the $_POST array if magic quotes are enabled on the server.
<p>To use it successfully as an include, you must do the following two things:
<p>The code in the external file must be surrounded by PHP tags. Although include()
<p>and its related commands are part of PHP, the PHP engine treats everything in an
<p>include file as plain text or XHTML until it encounters an opening PHP tag.
<p>The opening tag must be matched by a closing one at or before the end of the
<p>include file.
<p>The code must be included at the point in the script where you want to run it. In
<p>this respect, it’s the same as the text and XHTML includes earlier in the chapter.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>378</b>
<p>PHP can be used in two main ways: as a <b>procedural </b>language and as an <b>object-oriented</b>
<p>one. In a procedural language, everything is usually in the same page and the code is
<p>executed from top to bottom. However, to avoid the need to retype frequently used sections
<p>of script, you can package them up as custom-built functions. An object-oriented
<p>language takes the concept of functions much further, and packages most of the code in
<p>libraries called classes.
<p>That’s a vast over-simplification, but in both approaches, unless the contents of an external
<p>file define functions or classes, the include command must come at the point in the
<p>code where you want to run it. The POST stripslashes snippet does include the definition
<p>of the stripslashes_deep() function, but it’s buried inside a conditional statement. So,
<p>the snippet itself is a chunk of procedural code that must be included at the point of the
<p>script where it’s needed.
<p>However, you can convert the snippet into a new function called nukeMagicQuotes() like
<p>this:
<p><b>&lt;?php</b>
<p><b>function nukeMagicQuotes() {</b>
<p>// remove escape characters from POST array
<p>if (get_magic_quotes_gpc()) {
<p>function stripslashes_deep($value) {
<p>$value = is_array($value) ? array_map(&#8217;stripslashes_deep&#8217;, <b>å</b>
<p>$value): stripslashes($value);
<p>return $value;
<p>}
<p>$_POST = array_map(&#8217;stripslashes_deep&#8217;, $_POST);
<p>}
<p><b>}</b>
<p><b>?&gt;</b>
<p>If you save this as nukeQuotes.inc.php, you can include the external file at the beginning
<p>of your script and run this function at any stage in your script like this (you can see the
<p>code in feedback_nuke.php in examples/ch12 and nukeQuotes.inc.php in examples/
<p>includes):
<p>nukeMagicQuotes();
<p>The difference of this approach is that the include file initializes the function, but the function
<p>doesn’t actually run until it’s called in the main body of the script. Since this particular
<p>piece of code runs only once, there’s no immediate advantage of doing it this way.
<p>However, let’s say that you find a way of improving this script, the changes need to be
<p>made only in the external file, saving you the effort of hunting through every page where
<p>it might have been used. External files can define more than one function, so you can store
<p>frequently used functions together. In this respect, includes are the PHP equivalent of linking
<p>external JavaScript files or style sheets.
<p><i>When functions or classes are stored in an external file, the include command must</i>
<p><i>come </i>before <i>you use the functions or classes in your main script.</i>
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>379</b>
<p><b>12</b>
<p>Although building your own function library is an important use of includes, you shouldn’t
<p>ignore the opportunity to recycle procedural code. The next section shows you how to
<p>adapt the mail processing script from the last chapter and make it generic, so that it can
<p>handle the output of any feedback form.
<p><b>Adapting the mail processing script as an include</b>
<p>The mail processing script in the last chapter performs a series of tasks, some of them specific
<p>to the feedback form, others more generic in nature.
<p><b>Analyzing the script</b>
<p>To make the script reusable, you need to identify what’s specific, what’s generic, and
<p>whether any of the specific tasks can be made generic. Once you have identified the
<p>nature of each task, you need to concentrate the generic ones into a single unit that can
<p>be exported to an external file.
<p>Table 12-1 lists the tasks in the order they are currently performed and identifies their
<p>roles. You can study the code in feedback_orig.php in examples/ch12.
<p><b>Table 12-1. </b>Analysis of the mail processing script
<p><b>Step Description Type</b>
<p>1 Check if form has been submitted Specific
<p>2 Remove magic quotes Generic
<p>3 Set to address and subject Specific
<p>4 List expected and required fields Specific
<p>5 Initialize missing array Generic
<p>6 Filter suspect content Generic
<p>7 Process $_POST variables and check for missing fields Generic
<p>8 Validate email address Generic
<p>9 Build the message body Specific
<p>10 Create additional headers Specific
<p>11 Send email Generic
<p>As you can see from Table 12-1, most tasks are generic, but they don’t form a single block.
<p>However, step 2 can easily be moved after steps 3 and 4. That leaves just steps 9 and 10
<p>that get in the way.
<p>Step 9 builds the body of the message, which would appear to be something that’s always
<p>specific to each form. Let’s take another look at that part of the script:
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>380</b>
<p>// set default values for variables that might not exist
<p>$interests = isset($interests) ? $interests : array(&#8216;None selected&#8217;);
<p>$views = isset($views) ? $views : array(&#8216;None selected&#8217;);
<p>// build the message
<p>$message = &#8220;Name: $name\n\n&#8221;;
<p>$message .= &#8220;Email: $email\n\n&#8221;;
<p>$message .= &#8220;Comments: $comments\n\n&#8221;;
<p>$message .= &#8216;Interests: &#8216;.implode(&#8216;, &#8216;, $interests).&#8221;\n\n&#8221;;
<p>$message .= &#8220;Visited: $visited\n\n&#8221;;
<p>$message .= &#8216;Impressions of London: &#8216;.implode(&#8216;, &#8216;, $views).&#8221;\n\n&#8221;;
<p>$message .= &#8220;Subscribe: $subscribe&#8221;;
<p>It doesn’t take a genius to work out that the message is built using text labels followed by
<p>variables with the same name as the label. Since the variable names come from the name
<p>attributes in the form, all you need is a way of displaying the name attributes as well as the
<p>values of each input field. That’s easily done with PHP. It’s also easy to set default values for
<p>variables that might not exist.
<p>That leaves just step 10, the creation of additional headers. With the exception of the
<p>return email address, it doesn’t matter when you specify the additional headers. They simply
<p>need to be passed to the mail() function in step 11. So you can move the creation of
<p>most headers to the form-specific section at the beginning of the script. Table 12-2 shows
<p>the revised order of tasks.
<p><b>Table 12-2. </b>The revised mail processing script
<p><b>Step Description Type</b>
<p>1 Check if form has been submitted Specific
<p>2 Set to address and subject Specific
<p>3 Set form-specific email headers Specific
<p>4 List expected and required fields Specific
<p>5 Remove magic quotes Generic
<p>6 Initialize missing array Generic
<p>7 Filter suspect content Generic
<p>8 Process $_POST variables and check for missing fields Generic
<p>9 Validate email address Generic
<p>10 Build the message body Generic
<p>11 Add return email address to headers Generic
<p>12 Send email Generic
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>381</b>
<p><b>12</b>
<p><b>Building the message body with a generic script</b>
<p>Loops and arrays take a lot of the hard work out of PHP scripts, although they can be difficult
<p>to understand when you’re new to PHP. You may prefer just to use the completed
<p>script, but if you’re interested in the details, take a look at the following code, and I’ll
<p>explain how it works:
<p>// initialize the $message variable
<p>$message = &#8221;;
<p>// loop through the $expected array
<p>foreach($expected as $item) {
<p>// assign the value of the current item to $val
<p>if (isset(${$item})) {
<p>$val = ${$item};
<p>}
<p>// if it has no value, assign &#8216;Not selected&#8217;
<p>else {
<p>$val = &#8216;Not selected&#8217;;
<p>}
<p>// if an array, expand as comma-separated string
<p>if (is_array($val)) {
<p>$val = implode(&#8216;, &#8216;, $val);
<p>}
<p>// add label and value to the message body
<p>$message .= ucfirst($item).&#8221;: $val\n\n&#8221;;
<p>}
<p>This replaces the code for step 9 that was listed in the preceding section. It begins by
<p>initializing $message as an empty string. Everything else is inside a foreach loop
<p>(see “Looping through arrays with foreach” in Chapter 10), which iterates through
<p>the $expected array. This array consists of the name attributes of each form field (name,
<p>email, etc.).
<p>A foreach loop assigns each element of an array to a temporary variable. In this case, I
<p>have used $item. So, the first time the loop runs, $item is name; the next time it’s email,
<p>and so on. This means that you can use $item as the text label for each form field, but
<p>before you can do that, you need to know whether the field contains any value. The code
<p>that processes the $_POST variables (step 8 in the revised script) assigns the value of each
<p>field to a variable based on its name attribute ($name, $email, etc.). The rather odd-looking
<p>${$item} is what’s known as a variable variable (the repetition is deliberate, not a misprint).
<p>Since the value of $item is name the first time the loop runs, ${$item} refers to
<p>$name. On the next pass through the loop, it refers to $email, and so on.
<p>In effect, what happens is that on the first iteration the following conditional statement
<p>if (isset(${$item})) {
<p>$val = ${$item};
<p>}
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>382</b>
<p>becomes this
<p>if (isset($name)) {
<p>$val = $name;
<p>}
<p>If the variable doesn’t exist (which would happen if nothing was selected in a checkbox
<p>group), the else clause assigns $val the string Not selected.
<p>So you now have $item, which contains the label for the field, and $val, which contains
<p>the field’s value.
<p>The next conditional statement uses is_array() to check whether the field value is an
<p>array (as in the case of checkboxes or a multiple-choice list). If it is, the values are converted
<p>into a comma-separated string by implode().
<p>Finally, the label and field value are added to $message using the combined concatenation
<p>operator (.=). The label ($item) is passed to the ucfirst() function, which converts the
<p>first character to uppercase. The concatenation operator (.) joins the label to a doublequoted
<p>string, which contains a colon followed by the field value ($val) and two new line
<p>characters.
<p>This code handles all types and any number of form fields. All it needs is for the name
<p>attributes to make suitable labels and to be added to the $expected array.
<p>The following instructions show you how to adapt feedback.php from the previous chapter,
<p>so that it can be recycled for use with most forms. If you don’t have a copy of the file
<p>from the previous chapter, copy feedback_orig.php from examples/ch12 to workfiles/
<p>ch12, and save it as feedback.php.
<p><b>1. </b>Create a new PHP file, and save it as process_mail.inc.php in workfiles/
<p>includes. Switch to Code view, and strip out all existing code.
<p><b>2. </b>Insert the following code:
<p>&lt;?php
<p>if (isset($_SERVER['SCRIPT_NAME']) &amp;&amp; strpos($_SERVER['SCRIPT_NAME'],<b>å</b>
<p>&#8216;.inc.php&#8217;)) exit;
<p>?&gt;
<p>This uses the predefined variable $_SERVER['SCRIPT_NAME'] and the strpos()
<p>function to check the name of the current script. If it contains .inc.php, that
<p>means somebody is trying to access the include file directly through a browser, so
<p>the exit command brings the script to a halt. When accessed correctly as an
<p>include file, $_SERVER['SCRIPT_NAME'] contains the name of the parent file, so
<p>unless you also give that the .inc.php file name extension, the conditional statement
<p>returns false and runs the rest of the script as normal.
<p><b>Converting feedback.php to use the generic script</b>
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>383</b>
<p><b>12</b>
<p>Calling process_mail.inc.php directly shouldn’t have any negative effect, but if
<p>display_errors is enabled on your server, it generates error messages that might
<p>be useful to a malicious attacker. This simple security measure prevents the script
<p>running unless it’s accessed correctly.
<p><b>3. </b>Cut the POST stripslashes code from the top of feedback.php, and paste it on the
<p>blank line before the closing PHP tag in process_mail.inc.php.
<p><b>4. </b>Leave $to, $subject, $expected, and $required in feedback.php. Cut the remaining
<p>PHP code above the DOCTYPE declaration (DTD), except for the closing curly
<p>brace and PHP tag. The following code should be left above the DTD in
<p>feedback.php:
<p>&lt;?php
<p>if (array_key_exists(&#8217;send&#8217;, $_POST)) {
<p>//mail processing script
<p>$to = &#8216;me@example.com&#8217;; // use your own email address
<p>$subject = &#8216;Feedback from Essential Guide&#8217;;
<p>// list expected fields
<p>$expected = array(&#8216;name&#8217;, &#8216;email&#8217;, &#8216;comments&#8217;, &#8216;interests&#8217;, <b>å</b>
<p>&#8216;visited&#8217;, &#8216;views&#8217;, &#8217;subscribe&#8217;);
<p>// set required fields
<p>$required = array(&#8216;name&#8217;, &#8216;comments&#8217;, &#8216;visited&#8217;);
<p>}
<p>?&gt;
<p><b>5. </b>Paste into process_mail.inc.php just before the closing PHP tag the code you cut
<p>from feedback.php.
<p><b>6. </b>Cut the line that sets the From header, and paste it in feedback.php after the
<p>$required array. Replace the code that builds the message with the generic version.
<p>The full listing for process_mail.inc.php follows, with the new code highlighted
<p>in bold:
<p>&lt;?php
<p><b>if (isset($_SERVER['SCRIPT_NAME']) &amp;&amp; strpos($_SERVER['SCRIPT_NAME'],</b><b>å</b>
<p><b>&#8216;.inc.php&#8217;)) exit;</b>
<p>// remove escape characters from POST array
<p>if (get_magic_quotes_gpc()) {
<p>function stripslashes_deep($value) {
<p>$value = is_array($value) ? array_map(&#8217;stripslashes_deep&#8217;, <b>å</b>
<p>$value) : stripslashes($value);
<p>return $value;
<p>}
<p>$_POST = array_map(&#8217;stripslashes_deep&#8217;, $_POST);
<p>}
<p>// create empty array for any missing fields
<p>$missing = array();
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>384</b>
<p>// assume that there is nothing suspect
<p>$suspect = false;
<p>// create a pattern to locate suspect phrases
<p>$pattern = &#8216;/Content-Type:|Bcc:|Cc:/i&#8217;;
<p>// function to check for suspect phrases
<p>function isSuspect($val, $pattern, &amp;$suspect) {
<p>// if the variable is an array, loop through each element
<p>// and pass it recursively back to the same function
<p>if (is_array($val)) {
<p>foreach ($val as $item) {
<p>isSuspect($item, $pattern, $suspect);
<p>}
<p>}
<p>else {
<p>// if one of the suspect phrases is found, set Boolean to true
<p>if (preg_match($pattern, $val)) {
<p>$suspect = true;
<p>}
<p>}
<p>}
<p>// check the $_POST array and any subarrays for suspect content
<p>isSuspect($_POST, $pattern, $suspect);
<p>if ($suspect) {
<p>$mailSent = false;
<p>unset($missing);
<p>}
<p>else {
<p>// process the $_POST variables
<p>foreach ($_POST as $key =&gt; $value) {
<p>//assign to temporary variable and strip whitespace if not an array
<p>$temp = is_array($value) ? $value : trim($value);
<p>// if empty and required, add to $missing array
<p>if (empty($temp) &amp;&amp; in_array($key, $required)) {
<p>array_push($missing, $key);
<p>}
<p>// otherwise, assign to a variable of the same name as $key
<p>elseif (in_array($key, $expected)) {
<p>${$key} = $temp;
<p>}
<p>}
<p>}
<p>// validate the email address
<p>if (!empty($email)) {
<p>// regex to identify illegal characters in email address
<p>$checkEmail = &#8216;/^[^@]+@[^\s\r\n\'";,@%]+$/&#8217;;
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>385</b>
<p><b>12</b>
<p>// reject the email address if it deosn&#8217;t match
<p>if (!preg_match($checkEmail, $email)) {
<p>$suspect = true;
<p>$mailSent = false;
<p>unset($missing);
<p>}
<p>}
<p>// go ahead only if not suspsect and all required fields OK
<p>if (!$suspect &amp;&amp; empty($missing)) {
<p><b>// initialize the $message variable</b>
<p><b>$message = &#8221;;</b>
<p><b>// loop through the $expected array</b>
<p><b>foreach($expected as $item) {</b>
<p><b>// assign the value of the current item to $val</b>
<p><b>if (isset(${$item})) {</b>
<p><b>$val = ${$item};</b>
<p><b>}</b>
<p><b>// if it has no value, assign &#8216;Not selected&#8217;</b>
<p><b>else {</b>
<p><b>$val = &#8216;Not selected&#8217;;</b>
<p><b>}</b>
<p><b>// if an array, expand as comma-separated string</b>
<p><b>if (is_array($val)) {</b>
<p><b>$val = implode(&#8216;, &#8216;, $val);</b>
<p><b>}</b>
<p><b>// add label and value to the message body</b>
<p><b>$message .= ucfirst($item).&#8221;: $val\n\n&#8221;;</b>
<p><b>}</b>
<p>// limit line length to 70 characters
<p>$message = wordwrap($message, 70);
<p><b>// create Reply-To header</b>
<p>if (!empty($email)) {
<p>$headers .= &#8220;\r\nReply-To: $email&#8221;;
<p>}
<p>// send it
<p>$mailSent = mail($to, $subject, $message, $headers);
<p>if ($mailSent) {
<p>// $missing is no longer needed if the email is sent, so unset it
<p>unset($missing);
<p>}
<p>}
<p>?&gt;
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>386</b>
<p><b>7. </b>All that remains is to include the mail processing script. Since the form won’t work
<p>without it, it’s a wise precaution to check that the file exists and is readable before
<p>attempting to include it. The following is a complete listing of the amended code
<p>above the DOCTYPE declaration in feedback.php. The new code, including the
<p>$header pasted in the previous step, is highlighted in bold.
<p>&lt;?php
<p>if (array_key_exists(&#8217;send&#8217;, $_POST)) {
<p>//mail processing script
<p>$to = &#8216;me@example.com&#8217;; // use your own email address
<p>$subject = &#8216;Feedback from Essential Guide&#8217;;
<p>// list expected fields
<p>$expected = array(&#8216;name&#8217;, &#8216;email&#8217;, &#8216;comments&#8217;, &#8216;interests&#8217;, <b>å</b>
<p>&#8216;visited&#8217;, &#8216;views&#8217;, &#8217;subscribe&#8217;);
<p>// set required fields
<p>$required = array(&#8216;name&#8217;, &#8216;comments&#8217;, &#8216;visited&#8217;);
<p><b>$headers = &#8216;From: Essential Guide&lt;feedback@example.com&gt;&#8217;;</b>
<p><b>$process = &#8216;../includes/process_mail.inc.php&#8217;;</b>
<p><b>if (file_exists($process) &amp;&amp; is_readable($process)) {</b>
<p><b>include($process);</b>
<p><b>}</b>
<p><b>else {</b>
<p><b>$mailSent = false;</b>
<p><b>}</b>
<p>}
<p>?&gt;
<p>The path to process_mail.inc.php is stored in $process. This avoids the need to
<p>type it out three times. The conditional statement uses two functions with selfexplanatory
<p>names: file_exists() and is_readable(). If the file is OK, it’s
<p>included. If not, $mailSent is set to false. This displays the warning that there was
<p>a problem sending the message. Because $missing is set inside the processing
<p>script, the user’s input won’t be redisplayed. You could move the initialization of
<p>$missing to feedback.php, but if the script can’t be accessed, your form is broken
<p>anyway.
<p><b>8. </b>To be super-efficient, send yourself an email alerting you to the problem with the
<p>include file by amending the conditional statement like this:
<p>if (file_exists($process) &amp;&amp; is_readable($process)) {
<p>include($process);
<p>}
<p>else {
<p>$mailSent = false;
<p><b>mail($to, &#8216;Server problem&#8217;, &#8220;$process cannot be read&#8221;, $headers);</b>
<p>}
<p>You can check the final code in feedback_process.php in examples/ch12 and
<p>process_mail.inc.php in examples/includes.
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>387</b>
<p><b>12</b>
<p>Because process_mail.inc.php uses generic variables, you can slot this include file into
<p>any page that processes a form and sends the results by email. The only proviso is that you
<p>must use the same variables as in step 7, namely $to, $subject, $expected, $required,
<p>$headers, and $mailSent. You also need to use $missing for the error-checking routine,
<p>as described in the previous chapter.
<p>Programming purists would criticize this use of procedural code, arguing that a more
<p>robust solution should be built with object-oriented code. An object-oriented solution
<p>would probably be better, but it would also be more difficult for a PHP beginner to adapt.
<p>The purpose of this exercise has been to demonstrate how even procedural code can be
<p>recycled with relatively little effort. It also prepares the ground for customizing the
<p>PHP code automatically generated by Dreamweaver. With the exception of the
<p>XSL Transformations server behavior (covered in Chapter 18), Dreamweaver uses procedural
<p>code.
<p><b>Avoiding the “headers already sent” error</b>
<p>A problem that you’re bound to encounter sooner or later is this mysterious error
<p>message:
<p>Warning: Cannot add header information &#8211; headers already sent
<p>It happens when you use header() to redirect a page, as described in the previous chapter,
<p>or with PHP sessions (covered in Chapter 15). More often than not, the cause of the
<p>problem lies in an include file.
<p>Using header() or starting a PHP session must be done before any output is sent to the
<p>browser. This includes not only XHTML but also any whitespace. As far as PHP is concerned,
<p><i>whitespace means any space, tab, carriage return, or new line character</i>. Why the
<p>error message is so mysterious—and causes so much head banging—is because the whitespace
<p>is often at the end of an include file. Use the line numbers in Code view, as shown
<p>in Figure 12-8, to make sure there are no blank lines at the end of an include file. Also
<p>make sure that there is no whitespace after the closing PHP tag on the final line.
<p>Whitespace <i>inside </i>the PHP tags is unimportant, but the PHP code must not generate any
<p>XHTML output before using header() or starting a session. The same applies to the parent
<p>page: there must be no whitespace before the opening PHP tag.
<p>On rare occasions, the error is triggered by an invisible control character at the beginning
<p>of the file. Use View <b>ä </b>Code View Options <b>ä </b>Hidden Characters to check, and delete the
<p>character.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>388</b>
<p><b>Figure 12-8. </b>Eliminate whitespace at the beginning and end of include files to avoid the “headers
<p>already sent” error.
<p><b>Using Dreamweaver templates in a PHP site</b>
<p>Earlier in the chapter, I showed you how to extract two sections from the “Stroll along the
<p>Thames” site and turn them into includes. You could go further, and convert the header
<p>and fixed parts of the document &lt;head&gt; into includes, so that each page consists of several
<p>includes, with just the sidebar and main content forming the actual content of the page.
<p>As long as you keep each include as a coherent block, it’s relatively easy to manage, and
<p>Design view preserves the unified look of the page.
<p>However, it’s not an approach that everybody feels comfortable with. That’s where
<p>Dreamweaver templates can be a useful alternative. A template locks the fixed elements
<p>of the design, but lets you designate editable regions for the content that you want to
<p>change on each page. Dreamweaver templates allow you to control what can and can’t be
<p>edited with a great degree of precision, right down to the individual attributes of a tag. If
<p>you change anything in a locked region of a master template, Dreamweaver automatically
<p>updates all child pages (as long as you accept the option to do so). Although this is convenient,
<p>you still need to upload the changed pages manually to the live website.
<p>I don’t intend to go into the finer details of working with templates but simply give a
<p>broad overview of creating a template, designating editable regions, and creating child
<p>pages. I’ll also touch on issues that apply specifically to working with PHP in a
<p>Dreamweaver template.
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>389</b>
<p><b>12</b>
<p><b>Creating a template</b>
<p>The easiest way to create a Dreamweaver template is to design a page in the Document
<p>window in the normal way. It’s then a simple matter of saving the page as a template and
<p>designating the editable regions. Let’s do that with the “Stroll along the Thames” page
<p>from earlier in the chapter.
<p>This exercise combines the benefits of both approaches. The menu and footer are PHP
<p>includes, so can be edited separately, while the rest of the page as a template locks down
<p>the main design elements.
<p><b>1. </b>Open stroll_horiz_footer.php from examples/ch12 in the Document window.
<p>There is no need to copy or move it, because converting it into a template takes
<p>care of that.
<p><b>2. </b>Choose Make Template from the Common tab of the Insert bar, as shown in the following
<p>screenshot. Alternatively, use the menu option File <b>ä </b>Save as Template.
<p><b>3. </b>This opens the following dialog box:
<p>In theory, you can choose to save the template in a different site, but this is likely
<p>to cause problems with images, so leave Site unchanged. Existing templates displays
<p>a list of templates that you have already defined, if any. Optionally enter a description
<p><b>Converting stroll_horiz_footer.php into a template</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>390</b>
<p>of the template in the Description field. The Save as field suggests using the current
<p>file name. You can change this, if you like, but don’t add a file name extension, as
<p>Dreamweaver uses a special extension for templates. Click Save.
<p><b>4. </b>Dreamweaver asks if you want to update links. You must click Yes, or your template
<p>will have broken links and cause endless trouble.
<p><b>5. </b>Although it may appear as though nothing happens, the Dreamweaver title bar
<p>changes to display &lt;&lt;Template&gt;&gt; in front of the file name, which now has a
<p>.dwt.php extension, as shown here.
<p>Dreamweaver also saves the new template in the Templates folder in the site root.
<p>If the folder doesn’t exist, Dreamweaver creates it silently.
<p><b>Adding editable regions to the master template</b>
<p>Everything in a template is locked, except for the &lt;title&gt; tag and an editable region in the
<p>&lt;head&gt; of the document. This is needed so that external JavaScript files and style sheets
<p>can be added to a child page. It’s also where Dreamweaver behaviors insert the JavaScript
<p>functions that they require.
<p>It goes without saying that you must unlock at least one part of the page for the template
<p>to be of any real value. Otherwise, every child page would be identical. Deciding what to
<p>lock and unlock depends entirely on the level of control that you want over a page. For
<p>instance, you could create separate editable regions for each of the headings on the page.
<p><i>An important exception to this basic principle is that the area above the DTD and</i>
<p><i>below the closing </i>&lt;/html&gt; <i>tag is not locked in templates for server-side languages,</i>
<p><i>such as PHP. I’ll come back to this issue a little later, as it causes a lot of confusion.</i>
<p><i>The file with the </i>.dwt.php <i>file name extension is now the master template from which</i>
<p><i>you create child pages. Any changes to the design of this page will affect all child</i>
<p><i>pages created from it—as long as you accept the option to update them. You must</i>
<p><i>not move the template from the </i>Templates <i>folder. This is perhaps the single most</i>
<p><i>common mistake with templates—moving the master template to another folder will</i>
<p><i>cause you endless grief. </i>Don’t do it<i>.</i>
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>391</b>
<p><b>12</b>
<p>If you select the entire heading, including its surrounding tags, the heading can be
<p>replaced by anything: a table, a &lt;div&gt;, an &lt;iframe&gt;, or whatever you like. If you select just
<p>the content of an &lt;h2&gt; tag and convert it into an editable region, only the content can be
<p>changed in a child page. You can’t even change it to an &lt;h1&gt; tag.
<p>Since the remaining chapters of this book are about building dynamic content with PHP,
<p>you don’t want such rigid control. So you could make everything inside the container
<p>&lt;div&gt; one big editable region. However, we’ll take a slightly different approach.
<p>This exercise shows you how to create separate editable regions for the sidebar heading
<p>and content, as well as for the whole main content area.
<p><b>1. </b>Open stroll_horiz_footer.dwt.php in the Templates folder if it’s not already
<p>open.
<p><b>2. </b>Open Split view. Click immediately to the left of the heading that reads The pleasures
<p>of London. Hold down your mouse button and drag to the end of the heading.
<p>Alternatively, hold down the Shift key while pressing the keyboard right arrow to
<p>select the content of the heading. Make sure you have just the text and not the surrounding
<p>&lt;h3&gt; tags, as shown in the following screenshot.
<p><b>3. </b>There are several ways to make this an editable region. If you’re a fan of the Insert
<p>bar, click the down arrow next to the Make Template button on the Common tab,
<p>and select Editable Region. The Insert bar remembers your last selection, so the
<p>Editable Region button remains displayed, ready for the creation of more editable
<p>regions.
<p>Alternatively, right-click and select Templates <b>ä </b>New Editable Region from the context
<p>menu, or go to Insert <b>ä </b>Template Objects <b>ä </b>Editable Region.
<p><b>4. </b>This opens the New Editable Region dialog box. It has just one field for a name for
<p>the editable region. It can be anything you like, but each region must have a different
<p>name. Enter sidebarHead, and click OK.
<p><b>5. </b>This wraps the contents of the &lt;h3&gt; tag in two special HTML comment tags, as
<p>shown in Figure 12-9. These tell Dreamweaver to treat this as an editable region in
<p>child pages. Dreamweaver also displays a turquoise border around the region in
<p>Design view, with a tab at the top left indicating the name of the editable region.
<p><b>Making the sidebar and main content areas editable</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>392</b>
<p><b>Figure 12-9. </b>Editable regions are easily identified in both Code view and Design view.
<p><b>6. </b>Select the paragraphs and &lt;blockquote&gt; in the sidebar. If you’re still in Split view,
<p>you’ll see that selecting the text in Design view misses the opening tag of the first
<p>paragraph and the closing tag of the final one. This doesn’t matter. Since more than
<p>one paragraph is selected, Dreamweaver is normally clever enough to realize that
<p>you want the surrounding tags and includes them when you create the editable
<p>region.
<p><b>7. </b>Use one of the previous methods to make this an editable region named
<p>sidebarContent. Switch to Code view to make sure that the opening and closing
<p>&lt;p&gt; tags were included. If they weren’t, move them inside the template comments.
<p><b>8. </b>Select all the content in the mainContent &lt;div&gt;, but not the surrounding &lt;div&gt;
<p>tags, and create an editable region called mainContent. Check that the template
<p>comments are in the right place in Code view, and save stroll_horiz_footer.
<p>dwt.php.
<p><b>9. </b>Dreamweaver should display a warning that sidebarHead is inside a block tag, and
<p>that users of the template won’t be able to create new blocks in this region. This is
<p>because the &lt;h3&gt; tags are outside the sidebarHead editable region, which prevents
<p>anything other than a level three heading being created. That’s fine. So click OK.
<p><b>Creating child pages from a template</b>
<p>Now that you have a template, you can build pages based on it. The editable regions can
<p>be freely changed, but the other areas remain locked and can be changed only by editing
<p>the master template.
<p><i>Always check the position of the </i>TemplateBeginEditable <i>and </i>TemplateEndEditable
<p><i>comments in Code view, as you can easily move them or any of the surrounding code</i>
<p><i>while still in the template. Checking now saves a lot of frustration later, when you discover</i>
<p><i>that you didn’t select the region accurately in Design view, and your child pages</i>
<p><i>don’t work the way you expect. These comments are an integral part of the template</i>
<p><i>control mechanism and are propagated to the child pages, where they remain part of</i>
<p><i>the XHTML (see Figure 12-13).</i>
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>393</b>
<p><b>12</b>
<p>This exercise uses the template from the previous exercise to create a child page and
<p>explores the way editable regions are displayed in both Design view and Code view. It also
<p>demonstrates the importance of using site-root-relative links in PHP includes,
<p><b>1. </b>Go to File <b>ä </b>New. When the New Document dialog box opens, select Page from
<p>Template from the options on the left side. Assuming that you created the template
<p>in the preceding exercises, the dialog box should look similar to Figure 12-10.
<p><b>Figure 12-10. </b>The New Document dialog box gives you access to all the templates you have created.
<p>If you have created templates in several sites, select the site and the template that
<p>you want to use as the basis for a new page (you can have as many templates as
<p>you like in a site, using different designs for pages that serve different functions).
<p>The New Document dialog box shows a preview of the selected template, together
<p>with the description you entered when it was first created.
<p>The idea of a template is that all changes to common elements are propagated
<p>automatically to child pages when the master template is updated. Unless you want
<p>to create a page that doesn’t automatically update, make sure that there’s a check
<p>mark in Update page when template changes, and click Create.
<p><b>2. </b>A new page is created in the Document window. At first glance, it looks identical to
<p>the template, but several features tell you that it’s a child page (see Figure 12-11)
<p>and that you can make changes only to the editable regions indicated by the
<p>turquoise borders and tabs. Whenever your mouse is over a locked part of the
<p>page, the pointer turns into a circle with a diagonal bar to warn you that no
<p>changes can be made.
<p><b>Creating and editing a template-based page</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>394</b>
<p><b>Figure 12-11. </b>The child page is identical to the master template, but locked areas
<p>can no longer be edited.
<p><b>3. </b>Save the page as stroll_index.php in workfiles/ch12.
<p><b>4. </b>Repeat step 1 to create another child page from the template. Save it as stroll_
<p>restaurants.php in a new folder called workfiles/ch12/food.
<p><b>5. </b>Make some changes to stroll_restaurants.php. Experiment to see what you can
<p>and can’t change. For instance, the sidebarHead cannot be changed to a different
<p>format, but the &lt;h2&gt; at the top of the mainContent &lt;div&gt; can be changed or
<p>deleted altogether. You can also change the Title field in the Document toolbar.
<p>Give the pages different titles by adding Home to stroll_index.php and
<p>Restaurants to stroll_restaurants.php. Make sufficient changes to one of the
<p>pages so that you can tell them apart, and then save both of them.
<p><b>6. </b>The navigation menu contains only dummy links at the moment, so open
<p>menu.inc.php in workfiles/includes. Update the link for Home so that it points
<p>to stroll_index.php and for Restaurants to point to stroll_restaurants.php.
<p>Because the navigation menu is shared by files in different levels of the site hierarchy,
<p>you must make the links relative to the site root, even if you have set the site
<p>default to use links relative to the current document. Use the Browse icon (it looks
<p>like a folder) alongside the Link field in the Property inspector to select the target
<p>files, and set the Relative to drop-down menu to Site Root as shown in Figure 12-12.
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>395</b>
<p><b>12</b>
<p><b>Figure 12-12. </b>Links for the navigation menu must be relative to the site root.
<p><b>7. </b>Save menu.inc.php, and switch back to stroll_index.php in the Document window.
<p>You want to test the navigation menu links, so your Dreamweaver preferences
<p>shouldn’t use temporary files for preview. (If you’re not sure, open Preferences
<p>from the Edit menu or Dreamweaver menu on a Mac; then select Preview in Browser,
<p>and make sure Preview using temporary file is deselected.) Press F12/Opt+F12 to preview
<p>stroll_index.php in a browser.
<p><b>8. </b>Test the Restaurants link. If you have followed the instructions carefully, it <i>won’t</i>
<p>work. Don’t worry; I’ve done something deliberately to demonstrate an important
<p>feature of building pages from templates.
<p><b>9. </b>Open stroll_index.php in Code view. The first thing you’ll notice is that several
<p>parts of code are colored light gray. All the code in gray is locked. Try editing one
<p>of these areas. Although Dreamweaver puts the insertion point wherever you click,
<p>you cannot type anything. The only exception is between the template comments
<p>shown on line 25 of Figure 12-13. This is where you can add extra style sheets or
<p>JavaScript. It’s also where you should insert any other elements that normally go in
<p>the &lt;head&gt; of a web page, such as keywords and description &lt;meta&gt; tags.
<p><b>Figure 12-13. </b>Locked areas in a child page cannot be edited (lines 8–22 and 27–35 are hidden
<p>using Code collapse).
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>396</b>
<p>Another thing to note is the codeOutsideHTMLIsLocked attribute shown on line 2
<p>of Figure 12-13. By default, this is set to false. This is to allow you to apply server
<p>behaviors to pages created from a template. When you start working with server
<p>behaviors in Chapter 14, you’ll see that Dreamweaver puts most of the PHP code
<p>outside the &lt;html&gt; tags, so if this were set to true, you wouldn’t be able to apply
<p>server behaviors to your pages. I’ll explain the implications of this shortly.
<p>Finally, look at the include command for menu.inc.php (it’s on line 36 in Figure 12-13).
<p>It’s pointing to the version of the file in examples/includes, but the menu that you
<p>edited in step 6 is in workfiles/includes. Because this code is in a locked area,
<p>you can’t edit it. You need to do that in the master template.
<p><b>10. </b>Open stroll_horiz_footer.dwt.php in the Templates folder, and click the navigation
<p>menu. The Property inspector displays the name of the include file. Click the
<p>folder icon to the right of the Filename field, and browse to the workfiles/
<p>includes folder. Select menu.inc.php, and make sure that Relative to is set to
<p>Document (PHP includes need a relative path).
<p><b>11. </b>Save stroll_horiz_footer.dwt.php. Dreamweaver will remind you again that
<p>sidebarHead is inside a block tag. Just click OK. The next dialog box asks you if you
<p>want to update all files based on the template, and lists all of the child pages. The
<p>whole point of a template is automatic updating, so click Update.
<p><b>12. </b>When all the files have been updated, Dreamweaver displays a report like this:
<p>If you don’t see the list of updated files at the bottom of the dialog box, select the
<p>Show log checkbox. If anything goes wrong, Dreamweaver reports which files it
<p>wasn’t able to update. As you can see from the preceding screenshot, the update
<p>process is almost instantaneous with only a couple of child pages, but the time
<p>taken depends on the number of pages and the complexity of the updates. Click
<p>Close.
<p><b>13. </b>Reload stroll_index.php in your browser, and click the Restaurant link. You
<p>should be taken to stroll_restaurants.php, and the Home link should take
<p>you back to stroll_index.php. You can check your files against the versions in
<p>examples/ch12.
<p>WORKING WITH PHP INCLUDES AND TEMPLATES
<p><b>397</b>
<p><b>12</b>
<p>This is only a trivial example of how a change to the master template is propagated to all
<p>child pages, but it should be sufficient to demonstrate how templates control the look and
<p>shape of a site. However, the real power of this sample layout lies not so much in the template,
<p>but in the use of an include file for the navigation menu. If you were to leave the
<p>navigation menu in the main template, you would need to update every single child page
<p>each time you edit the menu. With an include, the edits take place in the external file but
<p>are immediately available in all pages that include it.
<p><b>Locking code outside the &lt;html&gt; tags</b>
<p>Often, questions appear in online forums from people puzzled by the fact that the code
<p>isn’t propagated to child pages when a server behavior is applied to a template. Although
<p>coverage of server behaviors begins in Chapter 14, it makes sense to discuss this issue
<p>here, while still on the subject of templates.
<p>Dreamweaver uses the space above the DTD and below the closing &lt;/html&gt; tag to create
<p>the PHP scripts used for server behaviors, such as inserting or updating records in a database.
<p>This is the same technique as you used in the last chapter to build the mail processing
<p>script. The reason for doing this is quite simple: the PHP engine reads the page from
<p>top to bottom and processes the dynamic code in the order that it encounters it. So, if you
<p>have a page that displays the results of a database search, it stands to reason that
<p>you need to conduct the search before displaying the results as XHTML. Dreamweaver
<p>uses the area after the closing &lt;/html&gt; tag to clean up any resources used by the script.
<p>Templates are intended to lock common elements, but dynamic code is almost always
<p>unique to a page. As a result, Dreamweaver doesn’t lock the code outside the &lt;html&gt; tags.
<p>So, even if you apply a server behavior to a master template (or write your own custom
<p>script above the DTD), the code outside the &lt;html&gt; tags will not be propagated to any
<p>child pages.
<p>If, for any reason, you want to create a template that propagates code outside the &lt;html&gt;
<p>tags, add the following code anywhere inside the &lt;head&gt; of the master template:
<p>&lt;!&#8211; TemplateInfo codeOutsideHTMLIsLocked=&#8221;true&#8221; &#8211;&gt;
<p>This is an all or nothing option. The PHP code will be propagated to child pages, but you
<p>cannot apply any other server behaviors to such child pages. The circumstances in which
<p>this option is useful are extremely rare, so use with care—if at all.
<p><b>Choosing the right tool</b>
<p>The considerably large space I have devoted to PHP includes in this chapter should give
<p>you a fair indication of my personal preference for includes. However, some people find
<p>the idea of splitting a page into its various component parts a difficult concept to come to
<p>terms with. So templates do have an important role to play. They also offer a more secure
<p>solution if you work in a team environment. You can generate a child page and hand it to
<p>a less experienced developer in the knowledge that only the editable regions can be
<p>changed. With includes, nothing is locked. But as a site gets larger, so too do the efficiency
<p>savings offered by includes.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>398</b>
<p>13 <b>SETTING UP MYSQL AND</b>
<p><b>PHPMYADMIN</b>
<p>Dynamic websites take on a whole new meaning in combination with a database. Drawing
<p>content from a database allows you to present material in ways that would be impractical—
<p>if not impossible—with a static website. Examples that spring to mind are online stores,
<p>such as Amazon.com; news sites, such as the International Herald Tribune (www.iht.com);
<p>and the big search engines, including Google and Yahoo! Database technology allows these
<p>websites to present thousands, sometimes millions, of unique pages with remarkably little
<p>underlying code. Even if your ambitions are nowhere near as grandiose, a database can
<p>increase your website’s richness of content with relatively little effort.
<p>Although PHP is capable of interacting with most popular databases (and some less wellknown
<p>ones, too), Dreamweaver has made the choice for you. All the server behaviors are
<p>designed to work with MySQL—a good choice, because it’s widely available, free, very fast,
<p>and offers an excellent range of features.
<p>In this chapter, you will learn how to
<p>Install MySQL on Windows and Mac OS X
<p>Secure access to MySQL
<p>Set up the phpMyAdmin graphical interface
<p>Back up and transfer data to another server
<p><b>Introducing MySQL</b>
<p>If you have ever worked with Microsoft Access, your first encounter with MySQL might
<p>come as something of a shock. For one thing, it doesn’t have a glossy interface. As
<p>Figure 13-1 shows, it looks like a throwback to the old days of DOS before the friendly
<p>interfaces of Mac and Windows. Its beauty lies, however, in its simplicity. What’s more,
<p>most of the time you’ll never see MySQL in its raw state like this. You’ll either use
<p>Dreamweaver or a graphic front end called phpMyAdmin. Best of all, you’ll be designing
<p>your own personalized interface by creating PHP pages.
<p><b>Figure 13-1. </b>The unadorned interface of MySQL as seen in the Windows MySQL Command
<p>Line Client
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>402</b>
<p>The other thing that comes as a surprise to Access users is that your database is not kept
<p>in a single file that you can upload to your remote server. MySQL keeps all databases in a
<p>central data folder, and each database table normally consists of three separate files. The
<p>way you transfer data from one server to another is by creating a text file that contains all
<p>the necessary commands to build the database and its contents—in other words, a backup
<p>file. All you need to know now is that there isn’t “a database file”—there are lots of them,
<p>and normally, you should never handle them directly.
<p><b>Understanding basic MySQL terminology</b>
<p>If you’ve not worked with a relational database before, you may find your head spinning
<p>with some of the names that crop up throughout the rest of this book. So here’s a quick
<p>guide:
<p><b>SQL</b>: Structured Query Language is the international standard behind all major relational
<p>databases. It’s used to insert and otherwise manipulate data and is based on
<p>natural English. For instance, to get the values of first_name and family_name
<p>from a database table called members, where username is equal to dpowers, you
<p>would use the following command (or SQL query):
<p>SELECT first_name, family_name
<p>FROM members
<p>WHERE username = &#8216;dpowers&#8217;
<p>As you can see, it’s very human readable, unlike many other computer languages.
<p>Although SQL is a standard, all of the main databases have added enhancements
<p>on top of the basic language. If you have been using Access or Microsoft SQL
<p>Server, be prepared for some slight differences in the use of functions. Some people
<p>pronounce SQL “sequel,” while others say “Ess-queue-ell.” Both are right.
<p><b>MySQL</b>: This refers to the entire database system created by MySQL AB of Sweden.
<p>It’s always spelled in uppercase, except for the “y,” and the official pronunciation is
<p>“My-ess-queue-ell.” It’s not just a single program, but also a client/server system
<p>with a number of related programs that perform various administrative tasks. The
<p>two main components are mysql and mysqld, with both terms entirely in lowercase.
<p>mysqld: This is the server (or, to give it its proper technical name, <b>daemon</b>) that
<p>runs in the background listening for requests made to the database. Once it has
<p>been started, you can ignore it.
<p>mysql: This has three distinct meanings. The first is the client program used to feed
<p>requests to the database. mysql is also the name of the main administrative database
<p>that controls user accounts, and on Windows, it is the name of the Windows
<p>service that starts and stops the database server. Once you start working with
<p>MySQL, differentiating between the different meanings of “mysql” is not as confusing
<p>as it first seems.
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>403</b>
<p><b>13</b>
<p><b>Installing MySQL</b>
<p>So, let’s press ahead and install MySQL. There are separate instructions for Windows and
<p>Mac OS X. If you plan to use a remote server as your testing server, and already have
<p>MySQL and phpMyAdmin set up, you can skip ahead to the next chapter.
<p>You can get MySQL from the downloads page at http://dev.mysql.com/downloads/.
<p>Select the Download link for MySQL Community Server, as shown in the following screenshot.
<p>This link takes you to the latest stable version of MySQL (currently the 5.0.x series).
<p>If, for any reason, you want to install an older version, don’t click this link, but scroll down
<p>the page to the link to archives of older releases.
<p>MySQL Enterprise is the commercial version, but the technical features in the Community
<p>Server are identical. The main difference is that MySQL Enterprise comes with technical
<p>support. With the Community Server, you’re on your own, but you have this book to guide
<p>you. There is also a large community of MySQL users who are able to offer help online.
<p>The installation instructions for MySQL are different for Windows and Mac OS X, so Mac
<p>users should skip ahead to the relevant section of the chapter.
<p><b>Installing MySQL on Windows</b>
<p>MySQL comes in a range of versions, but the one you should choose is <b>Windows Essentials</b>.
<p>It contains all the important stuff and certainly everything you need for this book. If you
<p>have a version older than MySQL 4.1.5 already installed on your computer, you <i>must </i>uninstall
<p>the old version first.
<p><b>Deciding whether to enable InnoDB support</b>
<p>MySQL is capable of storing database tables in a variety of formats. Most of the time, you
<p>don’t need to worry about this. The default MySQL format, MyISAM, is fast and highly reliable.
<p>Moreover, if you’re on shared hosting, this is frequently your only choice. However, if
<p>you have your own dedicated server, you will almost certainly also have the option of
<p>InnoDB tables, which offer extra features including foreign key constraints (see Chapter 16
<p>for details). Some hosting companies also offer support for InnoDB, so it’s worth checking
<p><i>Because new versions are coming out all the time, I recommend that you check my</i>
<p><i>website at </i>http://foundationphp.com/egdwcs3/updates.php <i>before going ahead.</i>
<p><i>Any major updates to the instructions will be listed there.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>404</b>
<p>before installing MySQL on your local computer. The Windows Essentials version of MySQL
<p>automatically enables support for InnoDB, but you can save 60MB of disk space if you
<p>don’t need to use it.
<p>You can either check with your hosting company directly, or you can do a simple test by
<p>running a SQL query on your remote server. Most companies provide phpMyAdmin to you
<p>to administer your database(s). Launch phpMyAdmin, and click the SQL tab. Delete any
<p>existing query in the Run SQL query field, and type the following:
<p>SHOW VARIABLES LIKE &#8216;have_inno%&#8217;
<p>Click Go. If you see a result like the one shown in Figure 13-2, it means InnoDB tables are
<p>supported. If your remote server is very old, the Variable_name column may read
<p>have_innobase. This is the same as InnoDB.
<p><b>Figure 13-2. </b>Confirmation that the MySQL server supports InnoDB tables
<p>If the Value column says NO, InnoDB is not supported. The instructions in later chapters
<p>show you how to emulate foreign key constraints by using PHP conditional logic.
<p>Don’t worry if you can’t find out whether your remote server supports InnoDB. You can
<p>easily add or remove InnoDB from your local setup later.
<p><i>These instructions are based on the 5.0 series of MySQL, which is installed in</i>
<p>C:\Program Files\MySQL\MySQL Server 5.0<i>. I expect MySQL 5.1 to become the recommended</i>
<p><i>release shortly after publication of this book. On past experience, the</i>
<p><i>default location changes for each series of Windows Essentials, so 5.1 is likely to be</i>
<p><i>installed in </i>C:\Program Files\MySQL\MySQL Server 5.1<i>, and Windows treats different</i>
<p><i>series as completely separate programs. If you upgrade from one series to another, any</i>
<p><i>existing databases need to be transferred to the new version as if it were a different</i>
<p><i>server (see the section titled “Backup and data transfer” near the end of this chapter).</i>
<p><b>Installing the Windows Essentials version of MySQL</b>
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>405</b>
<p><b>13</b>
<p><b>1. </b>Go to the MySQL download site, and select the link for MySQL Community Server.
<p><b>2. </b>In the page that opens, scroll down to find the section marked Windows downloads.
<p>Choose Windows Essentials, and click the download link. (You may be invited to
<p>Pick a mirror instead. This directs you to a mirror site closer to your location and
<p>usually offers a faster download.)
<p><b>3. </b>Download the MySQL file to your hard disk. It will have a name like mysqlessential-
<p>x.x.x-win32.msi, where x.x.x represents the version number.
<p><b>4. </b>Exit all other Windows programs; make sure you are logged in as an administrator
<p>(in Windows Vista; turn off User Account Control temporarily—see Chapter 3 for
<p>instructions), and double-click the icon of the file you have just downloaded. This
<p>is a self-extracting Windows Installer package.
<p><b>5. </b>Windows Installer will begin the installation process and open a welcome dialog
<p>box. If you are upgrading an existing version of the <i>same series </i>of Windows
<p>Essentials to a more recent one, the dialog box will inform you that it has detected
<p>your current installation and will remove it before installing the new one. However,
<p>all your databases will remain intact. Click Next to continue.
<p><b>6. </b>Dialog boxes will give you the opportunity to change the installation destination
<p>and select the type of setup. Accept the defaults, and click Next.
<p><b>7. </b>If you’re happy to go ahead with installation, click Install in the next dialog box.
<p><b>8. </b>Before launching into the actual installation, MySQL invites you to sign up for a free
<p>MySQL.com account. I suggest that you select Skip Sign-Up and click Next. After
<p>you finish setting up everything, visit www.mysql.com/register.php to see if you’re
<p>interested in the benefits offered. The main advantage is that you get automatic
<p>notification of new versions and links to helpful articles about new features of
<p>MySQL.
<p><b>9. </b>The actual installation now takes place and is normally very quick. When everything’s
<p>finished, you’re presented with a final dialog box.
<p>If this is a new installation or if you are upgrading from one series to another,
<p>click Finish to launch the configuration wizard, which is described in the next
<p>section.
<p>If you are upgrading to a later version of the same series (such as from 5.0.10 to
<p>5.0.37), deselect the checkbox labeled Configure the MySQL Server now before
<p>clicking Finish. MySQL should be ready to use but needs to be restarted manually
<p>(see “Starting and stopping MySQL manually on Windows” later in the chapter).
<p>If you have a software firewall, you might also be prompted to allow
<p>connections to and from MySQL. You must permit connections in order to work
<p>with the database.
<p>There are a lot of dialog boxes to go through, although all you usually need to do is accept
<p>the default setting. These instructions are based on version 1.0.8 of the Configuration
<p>Wizard.
<p><b>Configuring MySQL Windows Essentials</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>406</b>
<p><b>1. </b>The Configuration Wizard opens with a welcome screen. Click Next to proceed.
<p><b>2. </b>The first dialog box asks whether you want a detailed or standard configuration.
<p>Choose the default Detailed Configuration option, and click Next.
<p><b>3. </b>The three options on the next screen affect the amount of computer resources
<p>devoted to MySQL. Accept the default Developer Machine, and click Next. If you
<p>choose either of the other options, all other programs will slow down to a crawl.
<p><b>4. </b>The next dialog box asks you to select from the following three types of database:
<p>Multifunctional Database: Allows you to use both InnoDB and MyISAM tables.
<p>Transactional Database Only: InnoDB tables only. MyISAM is disabled.
<p>Non-Transactional Database Only: MyISAM tables only. InnoDB is disabled.
<p>Your choice depends on whether your remote server supports InnoDB tables (see
<p>“Deciding whether to enable InnoDB support” earlier in the chapter). If it does,
<p>choose Multifunctional Database. Otherwise, choose Non-Transactional Database Only.
<p>Do <i>not </i>choose Transactional Database Only. You should use InnoDB tables only
<p>when you need the extra features they provide, so you need support for MyISAM
<p>tables as well.
<p>If you’re not sure which to choose, and disk space is not a problem, choose
<p>Multifunctional Database. However, you should be aware that this option requires an
<p>extra 60MB of disk space to create the InnoDB tablespace.
<p><b>5. </b>What you see next may vary. If you chose Non-Transactional Database Only in the
<p>preceding step, you will probably be taken directly to step 6. However, you may see
<p>a dialog box inviting you to select a drive for the InnoDB data file. Unless you chose
<p>Multifunctional Database, just click Next and move on to step 6.
<p>If you plan to use InnoDB, you need to tell MySQL where to store the data.
<p>The InnoDB engine uses a single <b>tablespace </b>that acts as a sort of virtual file system.
<p>InnoDB files, once created, cannot be made smaller. The default location for the
<p>tablespace is C:\Program Files\MySQL\MySQL Server 5.0\data. If you want to
<p>locate the tablespace elsewhere, the drop-down menu offers some suggested
<p>alternatives. When you have made your choice, click Next.
<p><b>6. </b>Leave the next dialog box at the default Decision Support (DSS)/OLAP, and click
<p>Next.
<p><b>7. </b>The next dialog box sets the networking options and SQL mode. The important settings
<p>are in the top half. Make sure Enable TCP/IP Networking is checked, and leave
<p>Port Number on the default setting of 3306. The lower half of the dialog box lets
<p>you choose whether to run MySQL in strict mode. In an ideal world, you should
<p>accept this default setting, but it may cause problems with some PHP applications
<p>written before strict mode was introduced. Deselect the Strict mode checkbox, and
<p>click Next.
<p><i>If you choose </i>Multifunctional Database<i>, you need to edit the MySQL configuration file</i>
<p><i>later, as described in “Changing the default table type on Windows Essentials.”</i>
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>407</b>
<p><b>13</b>
<p><b>8. </b>MySQL has impressive support for most of the world’s languages. The next dialog
<p>box invites you to choose a default character set. In spite of what you might think,
<p>this has no bearing on the range of languages supported—all are supported by
<p>default. The character set mainly determines the order in which data is sorted.
<p>Since Dreamweaver CS3 now uses Unicode (UTF-8) as the default encoding for web
<p>pages, choosing the second option, Best Support for Multilingualism, seems the obvious
<p>choice. However, support for Unicode was not introduced to MySQL until
<p>version 4.1. If your hosting company is still running an earlier version of MySQL,
<p>you should stick with the default Standard Character Set. This is also a suitable
<p>choice if you work exclusively in English or use a completely different encoding,
<p>such as Shift_JIS for Japanese. Click Next after you have made your choice.
<p><b>9. </b>The recommended way of running MySQL is as a Windows service. If you accept
<p>the defaults as shown in the top half of the next dialog box, MySQL will always start
<p>automatically when you boot your computer and run silently in the background. (If
<p>MySQL has already been installed as a Windows service, this section will be grayed
<p>out.) If for any reason you don’t want MySQL to start automatically, uncheck the
<p>Launch the MySQL Server automatically option. You can easily change this option
<p>later (see the section “Starting and stopping MySQL manually on Windows” later in
<p>this chapter).
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>408</b>
<p>The lower half of the dialog box gives you the option to include the bin directory
<p>in your Windows PATH. This option enables you to interact directly with MySQL and
<p>its related utilities at the command line without the need to change directory every
<p>time. You won’t need to do this very often—if at all—but selecting this option
<p>makes life a little more convenient if the occasion ever arises. Click Next.
<p><b>10. </b>A fresh installation of MySQL has no security settings, so anyone can tamper with
<p>your data. MySQL uses the name <b>root </b>to signify the main database administrator
<p>with unrestricted control over all aspects of the database. Choose a password that
<p>you can remember, and enter it in both boxes.
<p>Unless you access your development server from a different computer over a network,
<p>leave the Enable root access from remote machines checkbox unchecked.
<p>Do <i>not </i>check Create An Anonymous Account. It will make your database insecure.
<p>If you are upgrading an existing version of Windows Essentials and want to keep
<p>your current root password, deselect the Modify Security Settings checkbox. If this is
<p>a first-time installation, you might not have this checkbox.
<p>Click Next when you have finished.
<p><i>If you get a warning message that a Windows service with the name MySQL already</i>
<p><i>exists, you will be asked if you want to use this name. You must click </i>No <i>and choose a</i>
<p><i>different name from the drop-down menu in the </i>Service Name <i>field.</i>
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>409</b>
<p><b>13</b>
<p><b>11. </b>At long last, everything is ready. Click Execute. If you have installed a software firewall,
<p>it will probably warn you that MySQL is trying to connect to a DNS server. You
<p>must allow the connection; otherwise, MySQL will never work. If your firewall
<p>doesn’t list MySQL specifically, make sure that it permits local connections on port
<p>3306, the MySQL default.
<p><b>12. </b>Assuming that all was okay, you should see a screen confirming that the configuration
<p>process is complete. MySQL should now be running—even if you selected the
<p>option not to start automatically (the option applies only to automatic start on
<p>bootup).
<p><b>13. </b>If you want to change the configuration at a later date—say, to add or remove support
<p>for InnoDB—launch the Configuration Wizard from the Windows Start menu
<p>by choosing Programs <b>ä </b>MySQL <b>ä </b>MySQL Server 5.0 <b>ä </b>MySQL Server Instance
<p>Config Wizard. The dialog box that opens offers the following two options:
<p>Reconfigure Instance: This takes you through all the dialog boxes again. If you
<p>add support for InnoDB, change the default table type, as described in the next
<p>section. If you remove support for InnoDB, stop the MySQL server after the
<p>wizard has finished, and delete any files with names that begin ibdata and
<p>ib_logfile from C:\Program Files\MySQL\MySQL Server 5.0\data. Then
<p>restart MySQL.
<p>Remove Instance: This does not remove MySQL from your system but removes
<p>the Windows service that automatically starts MySQL when you boot your computer.
<p>Unfortunately, it also removes the MySQL configuration file. See “Starting
<p>and stopping MySQL manually on Windows” for a less radical solution.
<p><b>Changing the default table type on Windows Essentials</b>
<p>The instructions in this section are required only if you selected Multifunctional Database in
<p>step 4 of “Configuring MySQL Windows Essentials.”
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>410</b>
<p>The Windows Configuration Wizard sets InnoDB as the default table storage engine for a
<p>multifunctional database. This is the opposite of the standard MySQL setup, so it makes
<p>sense to switch the default to match the way your remote server works. All it requires is a
<p>simple change to the MySQL configuration file: my.ini.
<p><b>1. </b>Use Windows Explorer to navigate to the folder in which MySQL was installed. The
<p>default is C:\Program Files\MySQL\MySQL Server 5.0.
<p><b>2. </b>Locate the file called my.ini, and double-click it. The file will open in Notepad.
<p><b>3. </b>Approximately 80 lines from the top, you should find a line that reads as follows:
<p>default-storage-engine=INNODB
<p>Change it to the following (the spelling of MyISAM is case insensitive):
<p>default-storage-engine=<b>MyISAM</b>
<p><b>4. </b>Save the file, and close it. To make the change effective, restart MySQL. MySQL will
<p>now create all new tables in the default MyISAM format. To use the InnoDB format
<p>for a database or an individual table, you can change the table type in phpMyAdmin,
<p>the graphical interface for MySQL that you will install later in the chapter.
<p><b>Starting and stopping MySQL manually on Windows</b>
<p>Most of the time, MySQL will be configured to start up automatically, and you can forget
<p>about it entirely. There are times, however, when you need to know how to start or stop
<p>MySQL manually—usually for maintenance or to conserve resources.
<p><b>1. </b>Select Control Panel from the Windows Start menu. Double-click the Administrative
<p>Tools icon, and then double-click the Services icon in the window that opens.
<p><b>2. </b>In the Services panel, scroll down to find MySQL, and highlight it by clicking once.
<p>You can now use the video recorder–type icons at the top of the panel (or rightclick
<p>to bring up the context menu) to stop or start the server.
<p><b>3. </b>To change the automatic startup option, highlight MySQL in the Services panel,
<p>right-click to reveal a context menu, and choose Properties.
<p><b>4. </b>In the dialog box that opens, activate the Startup type drop-down menu, and
<p>choose Automatic, Manual, or Disabled. Click OK. That’s all there is to it.
<p><b>Using the MySQL monitor on Windows</b>
<p>Although most of your interaction with MySQL will be through phpMyAdmin or your own
<p>PHP scripts, it’s useful to know how to access MySQL through the MySQL monitor (or the
<p>Command Line Client, as it’s called in Windows Essentials). It’s also a good way to test that
<p>your installation went without problems.
<p><b>To start a session </b>From the Windows Start menu, select Programs <b>ä </b>MySQL <b>ä </b>MySQL
<p>Server 5.0 <b>ä </b>MySQL Command Line Client. This will open the Command Line Client, which
<p>will ask you for your password. Type the root password that you chose in step 10 of the
<p>section “Configuring MySQL Windows Essentials,” and press Enter. As long as the server is
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>411</b>
<p><b>13</b>
<p>running—and you typed your password correctly—you will see a welcome message similar
<p>to the one shown here (on Windows XP, the title bar says MySQL Command Line Client).
<p>If you get your password wrong, your computer will beep and close the window. If you
<p>find this happening repeatedly, even though you’re sure you typed in your password correctly,
<p>there are two likely explanations. The first is that your Caps Lock key is on—MySQL
<p>passwords are case sensitive. The other is that the MySQL server isn’t running. Refer to the
<p>previous section on how to control MySQL manually before doing too much damage by
<p>banging your forehead on the keyboard.
<p><b>Ending your session </b>After you finish working with the MySQL monitor, type exit or quit at
<p>the mysql&gt; prompt, followed by Enter. The MySQL Command Line Client window closes
<p>automatically.
<p><b>Setting up MySQL on Mac OS X</b>
<p>MySQL is available as a Mac PKG file, so everything is taken care of for you, apart from
<p>some minor configuration.
<p><i>When upgrading an existing installation of MySQL, the Mac installer will not move</i>
<p><i>your data files. You must first create a backup, as described at the end of this chapter,</i>
<p><i>and reload them after upgrading. You must also shut down the MySQL server. If you</i>
<p><i>have never installed MySQL before, you don’t need any special preparations; just follow</i>
<p><i>these instructions.</i>
<p><i>Being unable to connect to MySQL because the server isn’t running is probably the</i>
<p><i>most common beginner’s mistake. The MySQL server runs in the background, waiting</i>
<p><i>for requests. Opening the Command Line Client does not start MySQL; it opens the</i>
<p><i>MySQL monitor, which is a channel for you to send instructions to the server. Equally,</i>
<p><i>closing the Command Line Client does not stop MySQL. The server continues running</i>
<p><i>in the background until the computer is closed down or until you stop it manually.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>412</b>
<p><b>1. </b>Go to www.mysql.com/downloads, and select the link for MySQL Community Server.
<p><b>2. </b>Select the Mac OS X (package format) downloads section, and choose the Standard
<p>version for your processor and version of OS X—there are separate packages for
<p>PowerPC, 64-bit PowerPC, and Intel Macs. The Intel Mac version is labeled x86. As
<p>you can see from the screenshot in the next step, the PKG file name includes not
<p>only the MySQL version number but also the version of OS X and processor for
<p>which it has been compiled (osx10.4-powerpc).
<p><b>3. </b>Double-click the DMG icon to mount the disk image on your desktop.
<p><b>4. </b>Double-click the mysql-standard-x.x.x.pkg icon to start the installation process. The
<p>Mac OS X installer opens. Follow the instructions onscreen.
<p><b>5. </b>Double-click the MySQLStartupItem.pkg icon, and follow the instructions onscreen.
<p><b>6. </b>Open a Finder window, and drag the MySQL.prefPane icon onto Applications <b>ä</b>
<p>System Preferences. This installs a MySQL control panel. A dialog box asks whether
<p>you want it to be available to yourself or all users. Make your choice, and click
<p>Install.
<p>The MySQL preference pane should open. Click Start MySQL Server, and enter your
<p>Mac administrator password when prompted. It may take a few seconds before the
<p>preference pane reports that the server is running, as shown here:
<p><i>The Mac files are available in two formats. Make sure you don’t select a TAR package</i>
<p><i>by mistake. These instructions are for the package format, which uses a Mac installer.</i>
<p><b>Downloading and installing MySQL</b>
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>413</b>
<p><b>13</b>
<p>To start or stop the MySQL server in future, open the preference pane by clicking
<p>the MySQL icon in the Other section of System Preferences.
<p><b>Adding MySQL to your PATH</b>
<p>You normally access MySQL through phpMyAdmin (introduced later in this chapter) or
<p>your own PHP scripts, but sometimes you need to access it directly in Terminal. To avoid
<p>having to type out the full path every time, add it to the PATH in your environmental variables.
<p>By default, Terminal uses what is known as the “bash shell.” Open Terminal (in
<p>Applications <b>ä </b>Utilities), and check the title bar. If it says Terminal—bash, as shown in the
<p>following screenshot, use the following instructions. In the unlikely event that it says
<p>Terminal—tcsh, follow the instructions in the section titled “Amending PATH in the tcsh
<p>shell.”
<p>Use this set of instructions if the Terminal title bar says Terminal—bash:
<p><b>1. </b>Open BBEdit or TextWrangler.
<p><b>2. </b>From the File menu, choose Open Hidden, and browse to your home folder. If there
<p>is a file called .profile (with a period as the first character), as shown in the
<p>screenshot, highlight it, and click Open.
<p><b>Amending PATH in the bash shell</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>414</b>
<p><b>3. </b>The file exists only if you have already made changes to the way Terminal operates.
<p>If .profile doesn’t exist, click Cancel, and open a blank file.
<p><b>4. </b>If you have opened an existing version of .profile, add the following code on a
<p>separate line at the end. Otherwise, enter it in the blank page.
<p>export PATH=&#8221;$PATH:/usr/local/mysql/bin&#8221;
<p><b>5. </b>Select File <b>ä </b>Save, and save the file as .profile in your own home folder. The
<p>period at the beginning of the file name should provoke the following warning:
<p><b>6. </b>Select Use “.” and close your text editor.
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>415</b>
<p><b>13</b>
<p>Use the following, alternative instructions <i>only </i>if the title bar says Terminal—tcsh:
<p><b>1. </b>Open Terminal, and enter the following command at the shell prompt:
<p>echo &#8217;setenv PATH /usr/local/mysql/bin:$PATH&#8217; &gt;&gt; ~/.tcshrc
<p>Make sure you copy everything exactly, including the quotes and spacing as shown.
<p><b>2. </b>Press Return, and close Terminal. The next time you open Terminal, the MySQL program
<p>directory will have been added to your PATH.
<p><b>Securing MySQL on Mac OS X</b>
<p>Although you have a fully functioning installation of MySQL, by default it has no security.
<p>Even if you’re the only person working on your computer, you need to set up a similar system
<p>of passwords and user accounts as on your hosting company’s server. There’s one
<p>important account that exists by default on all MySQL servers. It’s called root, and it is the
<p>main database administrator with unlimited powers over database files. When you first
<p>install MySQL, access to the root account isn’t password protected, so you need to block
<p>this security gap. The MySQL root user, by the way, is totally unrelated to the Mac OS X
<p>root user, which is disabled by default. Enabling root for MySQL has <i>no </i>effect on the
<p>OS X root user.
<p><b>1. </b>Open Terminal, and type the following command:
<p>mysql -u root
<p>The command contains three elements:
<p>mysql: The name of the program
<p>-u: Tells the program that you want to log in as a specified user
<p>root: The name of the user
<p><b>Setting the MySQL root password</b>
<p><i>If you have just added MySQL to your </i>PATH<i>, you must close and reopen Terminal</i>
<p><i>before embarking on this section. Otherwise, Terminal won’t be able to find MySQL.</i>
<p><b>Amending PATH in the tcsh shell</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>416</b>
<p><b>2. </b>You should see a welcome message like this:
<p><b>3. </b>The most common problem is getting an error message like this instead:
<p>It means that mysqld, the MySQL server, is not running. Use the MySQL control
<p>panel in System Preferences to start the server.
<p>Another common problem is for Terminal to report command not found. That
<p>means you have either mistyped the command or that you haven’t added the
<p>MySQL program files directory to your PATH, as described in the previous section.
<p><b>4. </b>Assuming that you have logged in successfully, as described in step 2, type the following
<p>command at the mysql&gt; prompt:
<p>use mysql
<p>This command tells MySQL that you want to use the database called mysql, which
<p>contains all the details of authorized users and the privileges they have to work on
<p>database files. You should see the message Database changed, which means MySQL
<p>is ready for you to work on the files controlling administrative privileges.
<p><b>5. </b>Now enter the command to set a password for the root user. Substitute
<p><i>myPassword </i>with the actual password you want to use. Also make sure you use
<p>quotes where indicated and finish the command with a semicolon.
<p>UPDATE user SET password = PASSWORD(&#8216;<i>myPassword</i>&#8216;) WHERE user = &#8216;root&#8217;;
<p><b>6. </b>Next, remove anonymous access to MySQL:
<p>DELETE FROM user WHERE user = &#8221;;
<p>The quotes before the semicolon are two single quotes with no space in between.
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>417</b>
<p><b>13</b>
<p><b>7. </b>Tell MySQL to update the privileges table:
<p>FLUSH PRIVILEGES;
<p>The sequence of commands should produce a series of results like this:
<p><b>8. </b>To exit the MySQL monitor, type exit, followed by Return. This simply ends your session
<p>with the MySQL monitor. <i>It does not shut down the MySQL server.</i>
<p><b>9. </b>Now try to log back in by using the same command as in step 2. MySQL won’t let
<p>you in. Anonymous access and password-free access have been removed. To get in
<p>this time, you need to tell MySQL that you want to use a password:
<p>mysql -u root <b>-p</b>
<p><b>10. </b>When you press Return, you will be prompted for your password. Nothing will
<p>appear onscreen as you type, but as long as you enter the correct password, MySQL
<p>will let you back in. Congratulations, you now have a secure installation of MySQL.
<p><b>Using the MySQL monitor on Windows and Mac</b>
<p>From this point on, 99.9 percent of everything you do is identical on both Windows and
<p>Mac OS X. If you are used to working exclusively with a GUI like Windows or Mac OS, it can
<p>be unsettling to work at the command line with MySQL. You won’t need to do it very
<p>often, if at all. However, it’s not difficult, and here are a few pointers to make you feel
<p>more at home:
<p>When you work inside the MySQL monitor, most commands need to end with a
<p>semicolon (;). The only exceptions are use <i>databaseName </i>and exit. The MySQL
<p>monitor is quite happy if you use a semicolon after these two commands, so the
<p>simple rule is this: <i>if in doubt, put a semicolon on the end of each command</i>.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>418</b>
<p>If you forget to put a semicolon at the end of a command that needs one, the
<p>MySQL monitor will assume that you want to break your command over more than
<p>one line, and that you haven’t finished typing. It will patiently wait for you to do so,
<p>like this:
<p>This enables you to spread long queries over a number of lines. Not only is this easier
<p>to read onscreen, it’s also useful if you make an error. The MySQL monitor
<p>remembers previous commands line by line, and you can retrieve them by pressing
<p>the up and down arrow keys on your keyboard. Once a previous command has
<p>been redisplayed, you can use your left and right arrow keys to move along the line
<p>and edit it in the normal way. Once you have completed the command, just type a
<p>semicolon and press Enter/Return. The MySQL monitor will then process it.
<p>If you spot a mistake before pressing Enter/Return, use your left and right arrow
<p>keys to edit the current line. If the mistake is on a previous line, there is no way to
<p>go back. Abandon the command by typing \c. The MySQL monitor will ignore
<p>everything you have entered and present you with the mysql&gt; prompt.
<p><b>Using MySQL with phpMyAdmin</b>
<p>Although you can do everything using MySQL monitor, it’s a lot easier to use a graphic
<p>interface. There are several to choose from, both commercial and free. Among the free
<p>offerings are two from MySQL itself: MySQL Administrator and MySQL Query Browser
<p>(www.mysql.com/products/tools). Two other popular graphical front ends for MySQL are
<p>the commercial product Navicat (www.navicat.com) and SQLyog (www.webyog.com), which
<p>is available in both commercial and free versions.
<p>However, the most popular graphical interface for MySQL is phpMyAdmin (www.phpmyadmin.
<p>net). It’s a PHP-based administrative system for MySQL that has been around since 1998,
<p>and it constantly evolves to keep pace with MySQL developments. It works on Windows,
<p>Mac OS X, and Linux and currently supports all versions of MySQL from 3.23.32 to 5.0.
<p>What’s more, many hosting companies provide it as the standard interface to MySQL.
<p>Because phpMyAdmin has a very intuitive interface, I suggest that you try it first. If you
<p>work with databases on a regular basis, you may want to explore the other graphical interfaces
<p>later. However, since phpMyAdmin is free, you have nothing to lose—and you may
<p>find it does everything you want.
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>419</b>
<p><b>13</b>
<p><b>Setting up phpMyAdmin on Windows and Mac</b>
<p>These instructions are based on phpMyAdmin 2.10.1. Like a lot of open source applications,
<p>phpMyAdmin is constantly evolving. Any changes of a substantial nature will be
<p>listed on my website at http://foundationphp.com/egdwcs3/updates.php.
<p>Since phpMyAdmin is PHP-based, all that’s needed to install it is to download the files,
<p>unzip them to a website in your local testing environment, and create a simple configuration
<p>file.
<p><b>1. </b>Go to www.phpmyadmin.net, and download the latest stable version. The files can
<p>be downloaded in three types of compressed file: BZIP2, GZIP, and ZIP. Choose
<p>whichever format you have the decompression software for.
<p><b>2. </b>Unzip the downloaded file. It will extract the contents to a folder called
<p>phpMyAdmin-<i>x.x.x</i>, where <i>x </i>represents the version number.
<p><b>3. </b>Highlight the folder icon, and cut it to your clipboard. On Windows, paste it inside
<p>the folder designated as your web server root (C:\htdocs, if you followed my
<p>example). If you’re on a Mac and want phpMyAdmin to be available to all users,
<p>put the folder in Macintosh HD:Library:WebServer:Documents rather than in your
<p>own Sites folder.
<p><b>4. </b>Rename the folder you have just moved to this: phpMyAdmin.
<p><b>5. </b>Like Apache and PHP, phpMyAdmin uses a text file to store all the configuration
<p>details. Since version 2.7.0, you no longer edit the phpMyAdmin configuration file
<p>but store your personal details in a new file, which should be named
<p>config.inc.php. There are two ways of doing this: using a built-in script called
<p>setup.php or manually. I prefer the manual method, but instructions for both
<p>methods follow.
<p>Use these instructions if you want to use the built-in configuration script.
<p><b>1. </b>Create a new subfolder called config within the phpMyAdmin folder. Windows users
<p>skip to step 3. Mac users continue with step 2.
<p><b>2. </b>On Mac OS X, use Finder to locate the config folder that you have just created.
<p>Ctrl-click and select Get Info. In Ownership &amp; Permissions, expand Details, and click
<p>the lock icon so that you can make changes to the settings. Change the setting for
<p>Others to Read &amp; Write. Close the config Info panel.
<p><b>3. </b>Open a browser, and type the following into the address bar:
<p>http://localhost/phpmyadmin/scripts/setup.php
<p>If you created the phpMyAdmin folder inside your Sites folder on a Mac, use the
<p>following address, substituting <i>username </i>with your Mac username:
<p>http://localhost/~<i>username</i>/phpmyadmin/scripts/setup.php
<p><b>Configuring phpMyAdmin with setup.php</b>
<p><b>Downloading and installing phpMyAdmin</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>420</b>
<p><b>4. </b>You should see the page shown in Figure 13-3.
<p><b>Figure 13-3. </b>A built-in script automates the configuration of phpMyAdmin.
<p>Ignore any warning about the connection not being secure. This is intended for
<p>server administrators installing phpMyAdmin on a live Internet server. If, on the
<p>other hand, you see the following warning, it means that you have not set up
<p>the config folder correctly and should go back to step 1.
<p><b>5. </b>Click the Add button in the Servers section. This loads a form with most of the necessary
<p>information already filled in. Check the following settings:
<p>Server hostname: localhost
<p>Server port: Leave blank unless your web server is running on a nonstandard
<p>port, such as 8080
<p>Server socket: Leave blank
<p>Connection type: tcp
<p>PHP extension to use: mysqli
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>421</b>
<p><b>13</b>
<p><b>6. </b>The default setting for Authentication type is config. If you don’t need to password
<p>protect access to phpMyAdmin, check that User for config auth is set to root, and
<p>enter your MySQL root password in the next field, Password for config auth.
<p>If you want to restrict access to phpMyAdmin by prompting users for a password,
<p>change Authentication type to http, and delete root from the User for config auth field.
<p><b>7. </b>Scroll down to the Actions field, and click Add. As shown here, there are two Add
<p>buttons close to each other; click the one circled in the screenshot:
<p><b>8. </b>The next screen will probably warn you that you didn’t set up a phpMyAdmin database,
<p>so you won’t be able to use all the phpMyAdmin features. This is not important.
<p>You can set up one later if you decide to use the advanced features of
<p>phpMyAdmin.
<p><b>9. </b>Scroll down to the Configuration section near the bottom of the page, and click
<p>Save.
<p><b>10. </b>Open the config folder in Explorer or Finder. You should see a new file called
<p>config.inc.php. Move it to the main phpMyAdmin folder. The official instructions
<p>tell you to delete the config folder, but this isn’t necessary in a local testing environment.
<p>Although setup.php automates the creation of config.inc.php, it duplicates some
<p>default settings. If you strip out the unnecessary commands, you may find it quicker to
<p>create the file manually.
<p><b>1. </b>If you don’t need to password protect access to phpMyAdmin, type the following
<p>code into a blank document:
<p>&lt;?php
<p>$i = 1;
<p>$cfg['Servers'][$i]['extension'] = &#8216;mysqli&#8217;;
<p>$cfg['Servers'][$i]['password'] = &#8216;<i>mysqlRootPassword</i>&#8216;;
<p>?&gt;
<p>Use your own MySQL root password in place of <i>mysqlRootPassword</i>.
<p><b>Configuring phpMyAdmin manually</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>422</b>
<p>If you need password protection for phpMyAdmin, use the following code instead:
<p>&lt;?php
<p>$i = 1;
<p>$cfg['Servers'][$i]['extension'] = &#8216;mysqli&#8217;;
<p>$cfg['Servers'][$i]['auth_type'] = &#8216;http&#8217;;
<p>?&gt;
<p><b>2. </b>Save the file as config.inc.php in the main phpMyAdmin folder. Erm . . . that’s it.
<p><b>Launching phpMyAdmin</b>
<p>To use phpMyAdmin, launch a browser, and enter http://localhost/phpMyAdmin/index.php in
<p>the address bar (on a Mac, use http://localhost/~username/phpMyAdmin/index.php if
<p>you put phpMyAdmin in your Sites folder). If you stored your root password in
<p>config.inc.php, phpMyAdmin should load right away, as shown in Figure 13-4. If you
<p>chose to password protect phpMyAdmin, enter root as the username and whatever you
<p>specified as the MySQL root password when prompted.
<p><b>Figure 13-4. </b>phpMyAdmin is a very user-friendly and stable graphical interface to MySQL.
<p>If you’re used to glossy software design, your initial impression of phpMyAdmin may not
<p>be all that favorable, particularly if you don’t have a large monitor. The interface is sorely
<p>in need of a facelift, but don’t let that fool you; phpMyAdmin is both powerful and easy
<p>to use.
<p><i>If you get a message saying that the server is not responding or that the socket is not</i>
<p><i>correctly configured, make sure that the MySQL server is running.</i>
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>423</b>
<p><b>13</b>
<p><b>Logging out of phpMyAdmin</b>
<p>If you opted to password protect phpMyAdmin, the Log out link is at
<p>the bottom left of the front page, just beneath Import (as shown in the
<p>screenshot alongside). When you click the link, you are immediately
<p>prompted for your username and password. Click Cancel, and you will
<p>be presented with a screen informing you that you supplied the wrong
<p>username/password—in other words, you have been logged out. Odd, but that’s the way
<p>it works.
<p><b>Backup and data transfer</b>
<p>MySQL doesn’t store your database in a single file that you can simply upload to your website.
<p>Even if you find the right files (on Windows, they’re located in C:\Program Files\
<p>MySQL\MySQL Server 5.0\data), you’re likely to damage them unless the MySQL server is
<p>turned off. Anyway, most hosting companies won’t permit you to upload the raw files,
<p>because it would also involve shutting down their server, causing a great deal of inconvenience
<p>for everyone.
<p>Nevertheless, moving a database from one server to another is very easy. All it involves is
<p>creating a backup <b>dump </b>of the data and loading it into the other database with
<p>phpMyAdmin. The dump is a text file that contains all the necessary Structured Query
<p>Language (SQL) commands to populate an individual table or even an entire database
<p>elsewhere. phpMyAdmin can create backups of your entire MySQL server, individual databases,
<p>selected tables, or individual tables. To make things simple, the following instructions
<p>show you how to back up only a single database.
<p>These instructions show you how to back up an entire database. You can also back up individual
<p>tables in the same way by selecting the tables in step 4.
<p><b>Creating a backup</b>
<p><i>If you have just installed MySQL for the first time, bookmark this section for</i>
<p><i>when you need to upload files to your remote server or upgrade MySQL. If</i>
<p><i>you’re on a Mac, you must always back up your data before upgrading MySQL.</i>
<p><i>Once the new version has been installed, you can transfer your data to the new</i>
<p><i>server. Windows users need to follow this procedure only when upgrading from</i>
<p><i>one series to another, such as 5.0 to 5.1.</i>
<p><i>You cannot log back in to phpMyAdmin from the wrong username/password screen.</i>
<p><i>You must enter the original URL into the browser address bar first.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>424</b>
<p><b>1. </b>Launch phpMyAdmin, and select the database that you want to back up from the
<p>drop-down menu in the navigation frame.
<p><b>2. </b>When the database details have loaded into the main frame, select Export from the
<p>tabs along the top of the screen, as shown here.
<p><b>3. </b>The rather fearsome-looking screen shown in Figure 13-5 opens. In spite of all the
<p>options, you need to concern yourself with only a few.
<p><b>Figure 13-5. </b>phpMyAdmin offers a wide range of choices when exporting data from MySQL.
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>425</b>
<p><b>13</b>
<p><b>4. </b>The Export section on the left of the screen lists all the tables in your database.
<p>Click Select All, and leave the radio buttons on the default SQL.
<p><b>5. </b>If the database has <i>never </i>been transferred to the other server before, the only
<p>option that you need to set on the right side of the screen is the drop-down menu
<p>labeled SQL compatibility mode. The setting depends on the version of MySQL on
<p>the other server (only the first two numbers, such as 3.23, 4.0, 4.1, or 5.0, are
<p>important):
<p>If the other server is running the same version of MySQL, choose NONE.
<p>If you are transferring between MySQL 4.1 and MySQL 5.0 (in either direction),
<p>choose NONE.
<p>If the other server is running MySQL 3.23, choose MYSQL323.
<p>If the other server is running MySQL 4.0, choose MYSQL40.
<p><b>6. </b>If the database has <i>already </i>been transferred on a previous occasion, select Add
<p>DROP TABLE in the Structure section. The existing contents of each table are
<p>dropped and are replaced with the data in the backup file.
<p><b>7. </b>Put a check mark in the box alongside Save as file at the bottom of the screen. The
<p>default setting in File name template is __DB__, which automatically gives the
<p>backup file the same name as your database. So, in this case, it will become
<p>egdwcs3.sql. If you add anything after the final double underscore, phpMyAdmin
<p>will add this to the name. For instance, you might want to indicate the date of the
<p>backup, so you could add 20070704 for a backup made on July 4, 2007. The file
<p>would then be named egdwcs320070704.sql.
<p><b>1. </b>If a database of the same name doesn’t already exist on the target server, create
<p>the database, but don’t create any tables.
<p><b>2. </b>Launch the version of phpMyAdmin that is used by the target server, and select the
<p>database that you plan to transfer the data to. Click the Import tab in the main
<p>frame (on versions of phpMyAdmin earlier than 2.7.0, click the SQL tab instead).
<p><b>3. </b>Use the Browse button to locate the SQL file on your local computer, and click Go.
<p>That’s it!
<p><i>Because phpMyAdmin uses PHP to upload the file, the maximum size of any backup is</i>
<p><i>normally limited to 2MB, which is the default maximum size for any file upload. If you</i>
<p><i>are transferring a very large database, use the phpMyAdmin export and import tabs to</i>
<p><i>backup and transfer individual tables. Alternatively, contact your hosting company for</i>
<p><i>advice on transferring your database.</i>
<p><b>Loading data from a backup file</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>426</b>
<p><b>Looking ahead . . .</b>
<p>Now that you have MySQL and phpMyAdmin installed, we can finally begin to explore
<p>Dreamweaver’s server behaviors. In the next chapter, I’ll show you how to create a database
<p>table in MySQL and insert into it user input from the feedback form in Chapter 9.
<p>You’ll also learn how to combine it with the mail processing script from Chapters 11 and
<p>12 and how to retrieve and display information stored in a database.
<p>SETTING UP MYSQL AND PHPMYADMIN
<p><b>427</b>
<p><b>13</b>
<p>14 <b>STORING RECORDS</b>
<p><b>IN A DATABASE</b>
<p>Unlike Access or FileMaker Pro, MySQL doesn’t come with predesigned forms. Instead, you
<p>build and design everything yourself. While this presents a challenge to the first-time user,
<p>MySQL isn’t difficult to use, and Dreamweaver takes a lot of the hard work out of integrating
<p>MySQL with your website.
<p>Let’s say that you decide to start accepting orders for goods and services through your
<p>website. As well as getting the orders by email, you need to store that information in a
<p>database. Rather than input all the data again manually, it makes much more sense to
<p>combine the two operations. So by the end of this chapter, you will be able to input data
<p>directly from the feedback form from Chapters 9, 11, and 12, and then send the details to
<p>your mail inbox. In the process, you’ll learn the basics of database construction, and how
<p>to handle different types of data. Specifically, you’ll learn how to
<p>Create MySQL user accounts
<p>Define a database table
<p>Create a database connection in Dreamweaver
<p>Insert form input into a database
<p>Use a recordset to retrieve data and display database results
<p>Apply a repeat region to display multiple records
<p>Merge the mail processing script with database input
<p><b>Setting up a database in MySQL</b>
<p>If you set up MySQL and phpMyAdmin in a local testing environment, as described in the
<p>last chapter, launch phpMyAdmin, and open the Database drop-down menu in the left
<p>frame (see Figure 14-1).
<p>MySQL isn’t a single database, but a relational database management system (RDBMS). The
<p>first database listed, information_schema, is a virtual database that contains details of
<p>other databases within the RDBMS. The second one, mysql, contains all the user account
<p>and security information and should never be edited directly unless you’re really sure what
<p>you’re doing. The final database, test, contains nothing. The numbers in parentheses indicate
<p>how many tables each database contains.
<p><b>Figure 14-1.</b>
<p>A new installation of MySQL contains
<p>three default databases.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>430</b>
<p>If you’re using a remote server, and your hosting company provides phpMyAdmin, the list
<p>of databases will be limited to those on your account, or you may be limited to only one
<p>database.
<p><b>Creating a local database for testing</b>
<p>Assuming that you have set up a local testing environment, you need to create a test database
<p>to work with the remaining chapters. I’m going to call the database egdwcs3. To make
<p>life easier for yourself when it comes to testing pages on the Internet, use the name of a
<p>database on your remote server.
<p>Type the name of the database in the field labeled Create new database in the
<p>phpMyAdmin welcome screen, and click Create, as shown in Figure 14-2. Leave Collation in
<p>its default position. However, if you’re working in a language other than English, Swedish,
<p>or Finnish, <i>and </i>your remote server runs MySQL 4.1 or later, skip ahead to the section
<p>“Understanding collation” before going any further.
<p><b>Figure 14-2. </b>To create a new database, just type its name into
<p>the phpMyAdmin welcome screen, and click Create.
<p>The database should be created instantly, and phpMyAdmin will invite you to create a new
<p>table. Before doing that, you need to create at least one user account for the database.
<p>Leave phpMyAdmin open.
<p><i>Because phpMyAdmin is a browser-based application, the precise layout of what you</i>
<p><i>see onscreen depends on the size of your monitor and browser viewport.</i>
<p>STORING RECORDS IN A DATABASE
<p><b>431</b>
<p><b>14</b>
<p><b>Creating user accounts for MySQL</b>
<p>At the moment, your installation of MySQL has only one registered user—the superuser
<p>account called “root,” which has complete control over everything. A lot of beginners
<p>think that once they have set up a password for the root user, they can start building databases.
<p>This is a big mistake. The root user should <i>never </i>be used for anything other than
<p>administration.
<p>MySQL stores all databases in a common directory. So, on shared hosting, your database—
<p>with all its precious information—rubs shoulders with everyone else’s. Clearly, you need a
<p>way to prevent unauthorized people from seeing or altering your data. The answer is to
<p>create user accounts that have the fewest number of privileges necessary to perform
<p>essential tasks, preferably on a single database.
<p><b>Granting the necessary user privileges</b>
<p>You normally want visitors to your site to be able to see the information it contains but not
<p>to change it. However, as administrator, you need to be able to insert new records, and
<p>update or delete existing ones. This involves four types of privileges, all named after the
<p>equivalent SQL commands:
<p>SELECT: Retrieves records from database tables
<p>INSERT: Inserts records into a database
<p>UPDATE: Changes existing records
<p>DELETE: Deletes records but not tables or databases (the command for that is DROP)
<p>In an ideal setup, you create two separate user accounts: one for administrators, who
<p>require all four privileges, and another one for visitors, limited to SELECT. If your hosting
<p>company lets you set up user accounts with different privileges, I suggest that you create
<p>two accounts like this. However, if you have no choice, set up one account and use the
<p>same username and password as on your remote server.
<p>These instructions show you how to set up user accounts in a local testing environment.
<p>You can skip this section if you are using your remote server as your testing server.
<p><b>1. </b>Click the home icon at the top of the left frame in phpMyAdmin to return to the
<p>welcome screen, and then click Privileges, as shown in the following screenshot:
<p><b>Setting up MySQL user accounts</b>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>432</b>
<p><b>2. </b>The User overview screen opens. Click Add a new User halfway down the page.
<p><b>3. </b>In the page that opens, enter the name of the user account that you want to create
<p>in the User name field. Select Local from the Host drop-down menu. This automatically
<p>enters localhost in the field alongside. This option restricts the user to connecting
<p>to MySQL only from the same computer. Enter a password in the Password
<p>field, and confirm it in the Re-type field. The Login Information table should look
<p>like this:
<p><i>The </i>Privileges <i>tab at the top of the previous screen displays a list of current user</i>
<p><i>accounts. To create a new user account, you must use the link in the welcome screen.</i>
<p>STORING RECORDS IN A DATABASE
<p><b>433</b>
<p><b>14</b>
<p><b>4. </b>Beneath the Login Information table is one labeled Global privileges. Granting such
<p>extensive privileges is insecure, so scroll past the Global privileges table, and click
<p>the Go button right at the bottom of the page.
<p><b>5. </b>The next page confirms that the user has been created and displays many options,
<p>beginning with the Global privileges again. Scroll down to the section labeled
<p>Database-specific privileges. Activate the drop-down menu, as shown here, to display
<p>a list of all databases. Select the name for the database you plan to use for
<p>testing.
<p><b>6. </b>The next screen allows you to set the user’s privileges for just this database. You
<p>want the admin user to have all four privileges listed earlier, so click the checkboxes
<p>next to SELECT, INSERT, UPDATE, and DELETE (if you hover your mouse
<p>pointer over each option, phpMyAdmin displays a tooltip describing what it’s for).
<p>After selecting the four privileges, as shown here, click the top Go button.
<p><i>Dreamweaver needs these details later to make a connection to the database.</i>
<p><i>If you want to use the download files exactly as they are, use </i>humpty <i>as</i>
<p><i>the password for </i>egadmin<i>.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>434</b>
<p><b>7. </b>phpMyAdmin presents you with the following confirmation that the privileges have
<p>been updated for the user account:
<p><b>8. </b>The page displays the Database-specific privileges table again, in case you need to
<p>change anything. Assuming you got it right, click the Privileges tab at the top right
<p>of the page. You should now see the new user listed in the User overview.
<p>If you ever need to make any changes to a user’s privileges, click the Edit Privileges
<p>icon to the right of the listing, as shown. You can also delete users by selecting the
<p>checkbox to the left of the User column, then clicking Go.
<p><b>9. </b>If your hosting company permits you to create multiple user accounts, click Add a
<p>new User, and repeat steps 3–8 to create a second user account. If you want to use
<p>the same username and password as in the download files, call the account eguser,
<p>and give it the password dumpty. This user will have restricted privileges, so in
<p>step 6, check only the SELECT option.
<p>Now that you have a database and at least one user account, you can build the table to
<p>store the feedback information. However, first, you need to understand the principles
<p>behind table construction.
<p><i>phpMyAdmin frequently offers you a variety of options on the same page, each of</i>
<p><i>which normally has its own </i>Go <i>button. Always click the one at the foot of or alongside</i>
<p><i>the section that relates to the options you want to set.</i>
<p>STORING RECORDS IN A DATABASE
<p><b>435</b>
<p><b>14</b>
<p><b>How a database stores information</b>
<p>All data in MySQL is stored in tables, with information organized into rows and columns
<p>very much like a spreadsheet. Figure 14-3 shows a simple database table as seen in
<p>phpMyAdmin.
<p><b>Figure 14-3. </b>Information in a database table is stored in rows and columns, just like in a
<p>spreadsheet.
<p>Each <b>column </b>has a name (image_id, filename, and caption) indicating what it stores.
<p>The rows aren’t labeled, but the first column (image_id) contains a unique identifier
<p>known as a <b>primary key</b>, which can be used to identify the data associated with a particular
<p>row. Each row contains an individual <b>record </b>of related data. The significance of primary
<p>keys is explained in the next section.
<p>The intersection of a row and a column, where the data is stored, is called a <b>field</b>. So, for
<p>instance, the caption field for the third record in Figure 14-3 contains the value “The
<p>Golden Pavilion in Kyoto” and the primary key for that record is 3.
<p><b>How primary keys work</b>
<p>Although Figure 14-3 shows image_id as a consecutive sequence from 1 to 8, they’re not
<p>row numbers. Figure 14-4 shows the same table with the captions sorted in alphabetical
<p>order. The field highlighted in Figure 14-3 has moved to the seventh row, but it still has the
<p>same image_id and filename.
<p><i>The terms “field” and “column” are often used interchangeably. A field holds</i>
<p><i>one piece of information for a single record, whereas a column contains the</i>
<p><i>same field for all records.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>436</b>
<p><b>Figure 14-4. </b>Even when the table is sorted in a different order, each record can be identified
<p>by its primary key.
<p>Although the primary key is rarely displayed, it identifies the record and all the data stored
<p>in it. If you know the primary key, you can update a record, delete it, or use it to display
<p>data. Don’t worry about how you find the primary key; it’s easy using Structured Query
<p>Language (SQL), the standard means of communicating with all major databases. The
<p>important thing is to assign a primary key to every record.
<p>A primary key doesn’t need to be a number, but <i>it must be unique</i>.
<p>Social Security, staff ID, or product numbers make good primary keys. They may
<p>consist of a mixture of numbers, letters, and other characters but are always
<p>different.
<p>MySQL will generate a primary key for you automatically.
<p>Once a primary key has been assigned, it should never—repeat, never—be changed.
<p>Because a primary key must be unique, MySQL doesn’t normally reuse the number when a
<p>record is deleted, leaving holes in the sequence. <i>Don’t even think about renumbering. </i>By
<p>changing the numbers to close the gaps, you put the integrity of your database at serious
<p>risk. Some people want to remove gaps to keep track of the number of records, but you
<p>can easily get the same information with SQL.
<p>Although Figures 14-3 and 14-4 show the similarity between a database table and a
<p>spreadsheet, there’s an important difference. With a spreadsheet, you can enter data without
<p>the need to specify beforehand what type of data it is or how it’s to be structured. You
<p>can’t do that with a database.
<p><b>Designing a database table</b>
<p>Before entering data, you need to define the table structure. This involves the following
<p>decisions:
<p>The name of the table
<p>How many columns it will have
<p>The name of each column
<p>What type of data will be stored in each column
<p>Whether the column must always have data in each field
<p>Which column contains the table’s primary key
<p>STORING RECORDS IN A DATABASE
<p><b>437</b>
<p><b>14</b>
<p>Don’t be tempted to choose the first thing that comes into your head. Experienced database
<p>developers often say at least half the total development time is spent deciding the
<p>structure of a database. Although the structure of a database can be altered, some decisions
<p>tie your hands so badly you need to redesign everything from scratch. That’s not
<p>much fun when the database contains several thousand records. The time spent on these
<p>early decisions can save a lot of agony and frustration later on.
<p>Because each database is different, it’s impossible to prescribe one simple formula, but the
<p>next few pages should help guide you in the right direction. Don’t attempt to commit
<p>everything to memory at the first read-through. Come back later when you need to
<p>refresh your memory or check a particular point.
<p><b>Choosing the table name</b>
<p>The basic MySQL naming rules for databases, tables, and columns are as follows:
<p>Names can be up to 64 characters long.
<p>Legal characters are numbers, letters, the underscore, and $.
<p>Names can begin with a number but cannot consist exclusively of numbers.
<p>Some hosting companies seem blissfully ignorant of these rules and assign clients databases
<p>that contain one or more hyphens (an illegal character) in their name. If a name contains
<p>spaces or illegal characters, you must surround it by backticks (`) in SQL queries.
<p>Note that this is not a single quote (&#8216;) but a separate character. Dreamweaver and
<p>phpMyAdmin normally do this for you automatically.
<p>Choose names that are meaningful. Tables hold groups of records, so it’s a good strategy
<p>to use plural nouns. For example, use products rather than product. Don’t try to save on
<p>typing by using abbreviations, particularly when naming columns. Explicit names make it
<p>much easier to build SQL queries to extract the information you want from a database.
<p>SQL is designed to be as human-readable as possible, so don’t make life difficult for yourself
<p>by using cryptic naming conventions.
<p>When choosing column names, there is a danger that you might accidentally choose
<p>one of MySQL’s many reserved words (http://dev.mysql.com/doc/refman/5.0/en/
<p>reserved-words.html), such as date or time. A good technique is to use compound
<p>words, such as arrival_date, arrival_time, and so on. These names also tell you much
<p>more about the data held in the column.
<p><b>Case sensitivity of names </b>Windows and Mac OS X treat MySQL names as case insensitive.
<p>However, Linux and Unix servers respect case sensitivity. To avoid problems when transferring
<p>databases and PHP code from your local computer to a remote server, I recommend
<p>that you use only lowercase in database, table, and column names. Using camel case (e.g.,
<p>arrivalDate) is likely to cause your code to fail when transferring a database from your
<p>local computer to a Linux server.
<p><b>Deciding how many columns to create</b>
<p>How should you store each person’s name? One column? Or one each for the family and
<p>personal names? A commercial contacts management program like Microsoft Outlook
<p>goes even further, splitting the name into five parts. In addition to first and last name, it
<p>stores title (Mr., Mrs., etc.), a middle name, and suffix (I, II, III, Jr., and Sr.). Addresses are
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>438</b>
<p>best broken down into street, town, county, state, ZIP code, etc. Think of all the possible
<p>alternatives, and add a column for each one. Things like company name, apartment number,
<p>and extra lines in an address can be made optional, but you need to make provision
<p>for them. This is an important principle of a relational database: <i>break down complex</i>
<p><i>information into its component parts, and store each part separately</i>.
<p>This makes searching, sorting, and filtering much easier. Breaking information into small
<p>chunks may seem a nuisance, but you can always join them together again. It’s much easier
<p>than trying to separate complex information stored in a single field.
<p><b>Choosing the right column type in MySQL</b>
<p>MySQL 5.0 has 28 different column types. Rather than confuse you by listing all of them,
<p>I’ll explain just the most commonly used. You can find full details of all column types in the
<p>MySQL documentation at http://dev.mysql.com/doc/refman/5.0/en/data-types.html.
<p><b>Storing text </b>The difference between the main text column types boils down to the maximum
<p>number of characters that can be stored in an individual field, and whether you can
<p>set a default value.
<p>CHAR: A fixed-length width text column up to a maximum of 255 characters. You
<p>must specify the size when building the table, although this can be altered later.
<p>Shorter strings are OK. MySQL adds trailing space to store them, and automatically
<p>removes it on retrieval. If you attempt to store a string that exceeds the specified
<p>size, excess characters are truncated. You can define a default value.
<p>VARCHAR: A variable-length character string. The maximum number must be specified
<p>when designing the table, but this can be altered later. Prior to MySQL 5.0, the
<p>limit is 255; this has been increased to 65,535 in MySQL 5.0. Another change in
<p>MySQL 5.0 affects the way trailing space is treated. Prior to MySQL 5.0, trailing
<p>space is stripped at the time of storing a record. Since MySQL 5.0, trailing space is
<p>retained for both storage and retrieval. You can define a default value.
<p>TEXT: Stores a maximum of 65,535 characters (slightly shorter than this chapter).
<p>You cannot define a default value.
<p>TEXT is convenient, because you don’t need to specify a maximum size (in fact, you can’t).
<p>Although the maximum length of VARCHAR is the same as TEXT in MySQL 5.0, other factors
<p>such as the number of columns in a table reduce this.
<p>Prior to MySQL 5.0, you cannot use CHAR in a table that also contains VARCHAR, TEXT, or
<p>BLOB. When creating the table, MySQL silently converts any CHAR columns to VARCHAR.
<p><b>Storing numbers </b>The most frequently used numeric column types are as follows:
<p>TINYINT: Any whole number (integer) between –128 and 127. If the column is
<p>declared as UNSIGNED, the range is from 0 to 255. This is particularly suitable for
<p>storing people’s ages, number of children, and so on.
<p>INT: Any integer between –2,147,483,648 and 2,147,483,647. If the column is
<p>declared as UNSIGNED, the range is from 0 to 4,294,967,295.
<p><i>Keep it simple: use </i>VARCHAR <i>for short text items and </i>TEXT <i>for longer ones.</i>
<p>STORING RECORDS IN A DATABASE
<p><b>439</b>
<p><b>14</b>
<p>FLOAT: A floating-point number.
<p>DECIMAL: A floating-point number <i>stored as a string</i>. <i>This column type is best</i>
<p><i>avoided</i>.
<p>DECIMAL is intended for currencies, but you can’t perform calculations with strings inside a
<p>database, so it’s more practical to use INT. For dollars or euros, store currencies as cents;
<p>for pounds, use pence. Then use PHP to divide the result by 100, and format the currency
<p>as desired.
<p><b>Storing dates and times </b>MySQL stores dates in the format YYYY-MM-DD. This may come as a
<p>shock, but it’s the ISO (International Organization for Standardization) standard, and
<p>avoids the ambiguity inherent in national conventions. The most important column types
<p>for dates and times are as follows:
<p>DATE: A date stored as YYYY-MM-DD. The supported range is 1000-01-01 to 9999-12-31.
<p>DATETIME: A combined date and time displayed in the format YYYY-MM-DD
<p>HH:MM:SS.
<p>TIMESTAMP: A timestamp (normally generated automatically by the computer).
<p>Legal values range from the beginning of 1970 to partway through 2037.
<p><b>Storing predefined lists </b>MySQL lets you store two types of predefined list that could be
<p>regarded as the database equivalents of radio button and checkbox states:
<p>ENUM: This column type stores a single choice from a predefined list, such as “yes,
<p>no, don’t know” or “male, female.” The maximum number of items that can be
<p>stored in the predefined list is a mind-boggling 65,535—some radio-button group!
<p>SET: This stores zero or more choices from a predefined list, up to a maximum of
<p>64. Although this violates the principle of storing only one piece of information in
<p>a field, it’s useful when the items form a coherent unit (e.g., optional extras on a car).
<p>The values stored in the ENUM and SET columns are stored as a comma-separated string.
<p>Individual values can include spaces and other characters but not commas.
<p><i>MySQL timestamps are based on a human-readable date and, since MySQL 4.1,</i>
<p><i>use the same format as </i>DATETIME<i>. As a result, they are incompatible with Unix</i>
<p><i>and PHP timestamps, which are based on the number of seconds elapsed since</i>
<p><i>January 1, 1970. Don’t mix them.</i>
<p><i>Don’t use commas or spaces as the thousands-separator. Apart from numerals,</i>
<p><i>the only characters permitted in numbers are the negative operator (</i>-<i>) and the</i>
<p><i>decimal point (</i>.<i>). Although some countries use a comma as the decimal point,</i>
<p><i>MySQL accepts only a period.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>440</b>
<p><b>Storing binary data </b>Binary data, such as images, bloat your tables and cannot be displayed
<p>directly from a database. However, the following column types are designed for binary
<p>data:
<p>TINYBLOB: Up to 255 bytes
<p>BLOB: Up to 64KB
<p>MEDIUMBLOB: Up to 16MB
<p>LONGBLOB: Up to 4GB
<p>With such whimsical names, it’s a bit of a letdown to discover that BLOB stands for <b>binary</b>
<p><b>large object</b>.
<p><b>Deciding whether a field can be empty</b>
<p>When defining a database table, specifying a column as NOT NULL is the equivalent of designating
<p>a required field. Since the phpMyAdmin default is NOT NULL, you need to manually
<p>override this to make a field optional. You can change a column definition from NOT
<p>NULL to NULL and vice versa at any time.
<p><b>Storing input from the feedback form</b>
<p>It’s time to put the knowledge from the preceding section to practical use by building a
<p>table to store the information from the feedback form from Chapters 9, 11, and 12. The
<p>form is available in the download files, so you can dive straight in. Don’t be put off by the
<p>fact that it’s a feedback form; working with it shows you all the basic techniques you need
<p>for inserting records into a database.
<p>The name for the database table needs to give a clear indication of what it contains, so I’ll
<p>call the table feedback. The next step is to analyze the form and decide how the feedback
<p>table should be structured.
<p><b>Analyzing the form</b>
<p>There are seven fields in the form (see Figure 14-5), so you need at least seven columns.
<p>You need another column for the primary key. Anything else?
<p><i>If you set a default value for a </i>NOT NULL <i>column, MySQL automatically uses that</i>
<p><i>value if nothing is entered in the field. Unfortunately, Dreamweaver doesn’t</i>
<p><i>support this useful feature.</i>
<p>STORING RECORDS IN A DATABASE
<p><b>441</b>
<p><b>14</b>
<p><b>Figure 14-5. </b>The names of the form fields often make good names for database columns.
<p>In a real-world situation the family and given names should be stored separately, but I’m
<p>going to skip that here, because both are text fields, so they are handled in the same way.
<p>The one extra field that I’m going to add will store the date and time that the form was
<p>submitted. So that makes a total of nine columns. As for column names, the name attributes
<p>of the form fields make a good choice, and as you’ll see shortly, using them makes it
<p>a lot easier to use the Dreamweaver server behaviors. For the two extra fields, let’s use
<p>message_id for the primary key, and submitted for the date.
<p>The next step is to decide the column types (refer to “Choosing the right column type in
<p>MySQL”). By convention, the primary key column is normally the first one in a table.
<p>MySQL has a feature called auto_increment, which automatically assigns the next available
<p>number. This is ideal for a primary key, so we’ll make the column an INT type. We don’t
<p>want negative numbers, so we’ll also make it UNSIGNED. This gives a range of nearly 4.3 billion,
<p>which is probably excessive for most tables. However, the danger of choosing a
<p>smaller number type is that you run out of numbers, particularly if records are added and
<p>deleted frequently. It’s much better to err on the side of caution with the primary key
<p>column.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>442</b>
<p>The first two form fields, name and email, contain short, variable amounts of text, so
<p>VARCHAR is appropriate. With VARCHAR you need to specify the maximum number of characters.
<p>For name, 50 is sufficient, but you don’t want to risk truncating an email address, so
<p>100 is a safer choice for email.
<p>The comments field is also text. If your remote server is running MySQL 5.0 or higher, you
<p>can use VARCHAR and set a limit of 500 or 1000, but TEXT is appropriate for all versions, so
<p>we’ll use that. To limit the length of comments, use the Spry Textarea Validation Widget as
<p>described in Chapter 9.
<p>The checkbox group interests presents a dilemma. Unless you make this a required field,
<p>users can pick anything from none to five. Storing more than one piece of information in
<p>a field goes against the principles of good database design, but creating five separate
<p>columns isn’t very satisfactory either. What happens if you want to add another category
<p>to the list, or remove one? Since interests are grouped together, and represent a series
<p>of closely related options, this is where SET comes in handy.
<p>The drop-down menu visited allows only one choice. Although this sounds like a good
<p>candidate for ENUM, you may want to change the range of options later, so this is better as
<p>VARCHAR. That way, you can change the value attributes of the &lt;option&gt; tags without
<p>needing to change the table definition.
<p>The views multiple-choice list is similar to the checkbox group, so that will be another SET.
<p>The subscribe radio group is a straight yes/no choice, so it should be an ENUM column
<p>type.
<p>Finally, submitted needs to store the date and time, so we’ll make it a TIMESTAMP column.
<p>Whenever a record is inserted or updated, the current date and time are automatically
<p>inserted into the first TIMESTAMP column in a table. With a DATETIME column, you have to
<p>insert the value explicitly.
<p>Table 14-1 summarizes this analysis. You’ll use this summary to define the feedback table
<p>in phpMyAdmin, so the table headings use the same terminology as phpMyAdmin. The
<p>setting for Length/Values for the two SET columns is described in the instructions in
<p>“Defining the feedback table.” Note that interests and views are specified as the only
<p>fields not required by setting them to null. I’ve done this because the Dreamweaver Insert
<p>Record server behavior can’t handle SET columns automatically. So we’ll come back to
<p>these two later.
<p>STORING RECORDS IN A DATABASE
<p><b>443</b>
<p><b>14</b>
<p><b>Table 14-1. </b>Column settings for the feedback table
<p><b>Field Type Length/Values Attributes Null Extra Primary key</b>
<p>message_id INT UNSIGNED not null auto_increment Selected
<p>name VARCHAR 50 not null
<p>email VARCHAR 100 not null
<p>comments TEXT not null
<p>interests SET See text null
<p><i>Continued</i>
<p><b>Defining a table in phpMyAdmin</b>
<p>Defining a database table normally requires writing a lengthy SQL query, but phpMyAdmin
<p>makes the process a lot simpler through a form-based interface. The form is quite wide
<p>and, unless you have a large monitor, you might need to scroll horizontally to see all the
<p>fields. You might find the text in some screenshots hard to read, but all important information
<p>is repeated in the instructions and Table 14-1.
<p><b>1. </b>Launch phpMyAdmin, and select the egdwcs3 database. In the main frame, type
<p>feedback in the Name field, enter 9 as the Number of fields, and click Go.
<p><b>2. </b>This opens the form shown in Figure 14-6 with nine blank rows where you enter
<p>the column definitions. Copy the values from Table 14-1. Designate message_id as
<p>the table’s primary key by selecting the radio button as indicated in Figure 14-6.
<p><b>Figure 14-6. </b>Defining the columns for the feedback table in phpMyAdmin
<p>For the SET and ENUM columns, you need to enter in Length/Values the value attributes
<p>from the related form fields as a series of comma-separated strings. Each
<p>string needs to be enclosed in single quotes. So, for interests, it looks like this:
<p>&#8216;Classical concerts&#8217;, &#8216;Rock/pop&#8217;, &#8216;Drama&#8217;, &#8216;Guided walks&#8217;, &#8216;Art&#8217;</p>
Posted in Uncategorized  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/swebsolution.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/swebsolution.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/swebsolution.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/swebsolution.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/swebsolution.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/swebsolution.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/swebsolution.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/swebsolution.wordpress.com/35/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/swebsolution.wordpress.com/35/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/swebsolution.wordpress.com/35/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=35&subd=swebsolution&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://swebsolution.wordpress.com/2009/02/28/dreamweaver-cs3-with-css-ajax-and-php-part-03/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4fc1b8adaf945b9ecf45239af6e622af?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Prakash Sherawat</media:title>
		</media:content>
	</item>
		<item>
		<title>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP 02</title>
		<link>http://swebsolution.wordpress.com/2009/01/22/dreamweaver-cs3-with-css-ajax-and-php-02/</link>
		<comments>http://swebsolution.wordpress.com/2009/01/22/dreamweaver-cs3-with-css-ajax-and-php-02/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 10:38:30 +0000</pubDate>
		<dc:creator>Prakash Sherawat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://swebsolution.wordpress.com/2009/01/22/dreamweaver-cs3-with-css-ajax-and-php-02/</guid>
		<description><![CDATA[The full range of options is as follows:
None: Don’t use—all pages should have a DOCTYPE declaration.
HTML 4.01 Transitional: Choose this if you don’t want to use XHTML.
HTML 4.01 Strict: This excludes deprecated elements (those destined for eventual
elimination)—use this only if you have a good knowledge of HTML and have made
a conscious decision not to use [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=34&subd=swebsolution&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The full range of options is as follows:
<p>None: Don’t use—all pages should have a DOCTYPE declaration.
<p>HTML 4.01 Transitional: Choose this if you don’t want to use XHTML.
<p>HTML 4.01 Strict: This excludes deprecated elements (those destined for eventual
<p>elimination)—use this only if you have a good knowledge of HTML and have made
<p>a conscious decision not to use XHTML.
<p>XHTML 1.0 Transitional: This offers the same flexibility as HTML 4.01 Transitional by
<p>permitting the use of deprecated elements but applies the stricter rules of XML.
<p>XHTML 1.0 Strict: This excludes all deprecated elements—use this only if you are
<p>competent with XHTML.
<p>XHTML 1.1: Don’t use—this DTD should not be used on pages delivered using the
<p>text/html MIME type, the current standard for web servers.
<p>XHTML Mobile 1.0: This is a subset of XHTML Basic for mobile devices—you can find
<p>the full specification at www.openmobilealliance.org/tech/affiliates/wap/
<p>wap-277-xhtmlmp-20011029-a.pdf.
<p>If you choose an HTML document type, Dreamweaver automatically creates code according
<p>to the HTML specification. Similarly, if you choose XHTML, your code automatically
<p>follows the stricter rules, using lowercase for tag names and event handlers and inserting
<p>a closing slash in empty tags such as &lt;img&gt;. You need to be careful when copying and pasting
<p>code from other sources. If you’re not sure about the quality of the code, run
<p>Commands <b>ä </b>Clean Up XHTML, which should correct most, if not all, problems.
<p>If you select a Strict DTD, it’s important to realize that Dreamweaver does <i>not </i>prevent you
<p>from using deprecated elements or attributes. Dreamweaver expects you to understand
<p>the difference yourself.
<p><b>Choosing the default encoding </b>The decision to switch the default encoding in
<p>Dreamweaver CS3 to Unicode (UTF-8) makes a lot of sense. Unicode supports nearly every
<p>known writing system, so—as long as you have the right fonts on your computer—you can
<p>combine Spanish, Russian, Chinese, and English all on the same web page. All modern
<p>browsers support UTF-8, so there is no reason you shouldn’t use it. But—and it’s a big
<p>but—this book concentrates heavily on using PHP and the MySQL database. Versions of
<p>MySQL prior to the 4.1 series do not support UTF-8. If your hosting company uses MySQL
<p>3.23 or 4.0, you might need to change the default encoding for your web pages. See
<p>“Understanding collation” in Chapter 13.
<p><b>Exploring the workspace</b>
<p>1-4 shows the default Windows workspace with a web page under construction and
<p>all the main areas labeled. The main part of the workspace is occupied by the Document
<p>window, which includes everything from the Document toolbar to the Tag selector.
<p>DREAMWEAVER CS3—
<p><b>7</b>
<p><b>1</b>
<p><b>1-4. </b>The Dreamweaver workspace remains basically unchanged.
<p>As you can see from 1-5, the Mac workspace is virtually the same. In harmony with
<p>other Mac programs, the Close, Minimize, and Zoom buttons are at the top left of the
<p>Document window. The Document window’s tabbed interface is displayed only when more
<p>than one document is open. If you want the Mac version to display tabs all the time, open
<p>Preferences from the Dreamweaver menu, select the General category, and check the
<p>option labeled Always show tabs. Alternatively, if you don’t want the tabbed interface, deselect
<p>the Open documents in tabs option.
<p>Two other points to note about the Mac workspace: you can close a tab by clicking the <b>5</b>
<p>in a circle to the left of the file name; and the Property inspector overlaps the Files panel
<p>on a 1024<b>5</b>768 resolution monitor (the minimum display required for Dreamweaver CS3).
<p>As a result, on a small monitor the Property inspector flops in front of or behind the Files
<p>panel, depending on whether it has focus. This results in some icons being hidden, but you
<p>can bring them back into view by clicking in any blank space in the Property inspector.
<p>Alternatively, resize the Files panel to make room.
<p>The main menus run across the top just below the title bar. The menus provide access to
<p>all features, but I prefer to work directly in the workspace with Dreamweaver’s visual tools,
<p>each of which I’ll describe briefly.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>8</b>
<p><b>1-5. </b>Apart from a few minor differences, the Mac workspace is identical to Windows.
<p><b>Insert bar</b>
<p>The Insert bar is really a collection of toolbars used to perform the most frequently used
<p>operations in building web pages. It’s organized as a tabbed interface. 1-6 shows the
<p>Common tab. When you first launch Dreamweaver, there are six other tabs (or categories).
<p>Additional, context-sensitive tabs are displayed only when the features can be used in a
<p>particular page, such as when using PHP or the XSL Transformation server behavior. The
<p>tabs organize program features in logical groups, so some commonly used features, such
<p>as tables and &lt;div&gt; tags, are duplicated on more than one tab to save time switching back
<p>and forth.
<p><b>1-6. </b>The Common tab of the Insert bar houses some of the most frequently used operations.
<p>If space is at a premium, you can save a few pixels of vertical space by switching to the
<p>menu style shown in 1-7. Click the name at the left end to reveal a menu of available
<p>categories. However, it takes two clicks to change categories, so you’ll probably find
<p>the tabbed interface more convenient. Alternatively, you can put frequently used items in
<p>the Favorites category as described shortly.
<p><b>1-7. </b>The Insert bar has an alternative menu style that saves a little space.
<p>DREAMWEAVER CS3—
<p><b>9</b>
<p><b>1</b>
<p>To use the menu style, click the panel Options menu button (shown alongside) at the top
<p>right of the Insert bar, and select Show as Menu. To restore the tabbed interface, click the
<p>category name at the left end of the Insert bar, and select Show as Tabs from the bottom
<p>of the menu.
<p>Table 1-1 describes briefly what each category contains. Although the Insert bar will look
<p>familiar to users of previous versions of Dreamweaver, it has been revamped with many
<p>new items and the removal of some old ones. For the benefit of readers upgrading from
<p>Dreamweaver 8, I have indicated the main changes.
<p><b>Table 1-1. </b>The main features of Insert bar tabs (categories)
<p><b>Tab/category Description Changes from Dreamweaver 8</b>
<p>Common Inserts the most commonly used Now contains all tags related
<p>objects, such as tables, images, with &lt;head&gt; and &lt;script&gt;
<p>and &lt;div&gt; tags. from the old HTML category.
<p>Layout Offers various tools for layout, Layout Mode was removed
<p>including table modification, but remains accessible
<p>frames, and Spry widgets, such through View <b>ä </b>Table Mode <b>ä</b>
<p>as menu bar (see Chapter 7), Layout Mode.
<p>and tabbed and collapsible
<p>panels (see Chapter 8).
<p>Forms Creates forms and inserts all form No change, apart from the
<p>elements, including Spry validation addition of Spry validation
<p>widgets (forms and Spry validation widgets.
<p>are covered in Chapter 9).
<p>Data Offers access to most dynamic Previously the Application
<p>features, including Spry data sets category. Import Tabular Data
<p>(see Chapter 19) and PHP server (for CSV files) has been
<p>behaviors (see Chapter 14 onward). relocated here from the
<p>Also imports data from comma- Layout category. Addition of
<p>separated value (CSV) files into Spry data features.
<p>a static web page.
<p>Spry All Spry features gathered in a New.
<p>single category.
<p>Text Provides an alternative to the Font Tag Editor was removed.
<p>Property inspector for common
<p>formatting options. Also, home
<p>to definition list and HTML entities.
<p>Favorites Left blank for you to customize. For backward compatibility,
<p>gives access to the HTML and
<p>Flash elements categories,
<p>which have been removed
<p>from the main Insert bar.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>10</b>
<p><b>Selecting options from the Insert bar </b>To see what each button is
<p>for, hold your mouse pointer over it, and a tooltip appears. Some
<p>buttons have a little down arrow alongside them to the right. The
<p>first time you click one of these buttons, Dreamweaver displays a
<p>menu showing all options, as shown in the screenshot alongside.
<p>Dreamweaver remembers your selection and always displays the
<p>most recently used option. If you want to use the same option
<p>again, click the button itself. To select a different option, click the
<p>arrow to the right to reveal the menu again.
<p><b>Customizing the Favorites category </b>If switching among categories becomes too timeconsuming,
<p>you can populate the Favorites category with your most frequently used items.
<p>Select the Favorites tab, right-click, and select Customize Favorites from the context menu.
<p>The drop-down menu at the top left of the Customize Favorite Objects dialog box (shown
<p>in 1-8) lets you choose either from a master list or from individual categories. In the
<p>left panel, select one item at a time, and click the button with the double chevron to add
<p>it to the Favorite objects panel on the right. To remove an item, select it in the right panel,
<p>and click the trash can button at the top right. The up and down arrows can be used to
<p>change the position of the selected item, and the Add separator button inserts a separator
<p>after the current item.
<p><b>1-8. </b>You can customize the Favorites category of the Insert bar for quick
<p>access to frequently used options.
<p>The Customize Favorite Objects dialog box gives access to all Insert bar categories, including
<p>context-sensitive ones, such as PHP, as well as to items that have been removed since
<p>Dreamweaver 8.
<p>To copy your Favorites to a different computer, follow the instructions at the end of the
<p>next section.
<p><b>Document window</b>
<p>By default, Dreamweaver displays each web page in a tabbed interface. Tabs are created
<p>left to right in the same order as the pages are opened, but you can drag and drop them
<p>DREAMWEAVER CS3—
<p><b>11</b>
<p><b>1</b>
<p>into any order. You can also tidy up the workspace by right-clicking any tab to reveal a
<p>context menu that, among other things, lets you close the individual tab, close all tabs, or
<p>close them all except the current one.
<p><b>Document toolbar </b>Running across the top of the Document window is the Document toolbar,
<p>shown in 1-9. The three buttons on the left are the most important, as they let
<p>you switch quickly between Code view, Design view, and a combination of both called Split
<p>view, as shown in Figures 1-4 and 1-5. The Live Data view button is displayed only in
<p>dynamic pages, such as a PHP page. It processes server-side code to show you a good
<p>approximation of what the page will look like when parsed by a web server. Before you can
<p>use Live Data view, you need to define a testing server as described in Chapter 4.
<p><b>1-9. </b>The Document toolbar mainly controls how your main work environment looks.
<p>The following list briefly describes the other options on the Document toolbar:
<p>Title: This is where you enter the document title that is displayed in the browser
<p>title bar.
<p>File management: This offers a quick way of uploading and downloading the current
<p>file to and from your remote server. Setting the connection details is covered in
<p>Chapter 4.
<p>Preview in browser: This displays the current page in a browser or Device Central
<p>(see “Checking what your page will look like in other media” later in this chapter).
<p>Refresh: This refreshes Design view. It’s used only when you’re working in the
<p>underlying code in Split view. Otherwise, Design view refreshes automatically.
<p>View options: This turns rulers and guides on and off.
<p>Visual aids: This controls the CSS visual aids described in “Using visual aids to understand
<p>your CSS structure” later in this chapter.
<p>Validate: This option checks your document, selected files, or the entire site against
<p>World Wide Web Consortium (W3C) standards. Dreamweaver’s validator misses
<p>some errors, particularly when checking pages against a Strict Document Type
<p>Definition (DTD). Double-check against the official W3C Markup Validation Service
<p>at http://validator.w3.org.
<p>Check page: This runs checks for browser compatibility (see “Checking for browser
<p>bugs” later in the chapter) and accessibility.
<p><b>Code view </b>This is where you work directly with all the XHTML, PHP, and other code that
<p>controls your web page. Even if you rarely touch the code yourself, it’s important to
<p>understand what’s happening in Code view. PHP code inserted in the wrong place will
<p>bring your page down like a house of cards.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>12</b>
<p><b>Design view </b>This renders your page as it should look in a standards-compliant browser.
<p>The CSS rendering in Dreamweaver CS3 is generally very accurate, but don’t fall into the
<p>trap of regarding Dreamweaver as a WYSIWYG (what you see is what you get) web page
<p>builder. It’s an excellent visual design tool, but you need a solid understanding of XHTML
<p>and CSS to use it to its best advantage.
<p><b>Tag selector </b>The status bar at the bottom of the Document window displays a hierarchical
<p>view of the document indicating where the insertion point is at any given moment. As
<p>1-10 shows, clicking one of the tags in the Tag selector highlights the element in
<p>both Design view and Code view. This is extremely useful for editing an element or applying
<p>a dynamic behavior to it. Right-clicking a tag in the Tag selector brings up a context
<p>menu with a useful selection of editing options, including the ability to add an ID or a class
<p>to the element. The Tag selector fulfils a similar role to the GoLive Markup Tree bar.
<p><b>1-10. </b>Clicking a tag in the Tag selector highlights the
<p>element in Design view, as well as the underlying code.
<p><b>Property inspector </b>This context-sensitive panel gives direct access to all the main attributes
<p>of the currently selected element. It’s equivalent to the Inspector palette in GoLive.
<p><b>Panel groups </b>The panel groups, which are displayed by default on the right of the screen,
<p>give you access to more detailed or specialized features. Clicking a panel group’s title bar
<p>toggles it open and closed. The most important one is the Files panel, which not only displays
<p>the file hierarchy of your site but also ensures that all internal links are updated and
<p>controls uploading and downloading to and from your remote server.
<p>DREAMWEAVER CS3—
<p><b>13</b>
<p><b>1</b>
<p><b>Organizing your workspace</b>
<p>The Windows version of Dreamweaver CS3 comes with three workspace layouts: Designer,
<p>Coder, and Dual Screen. Designer is the default layout shown in 1-4. Coder puts the
<p>panel groups on the left of the screen with the Property inspector collapsed. Dual Screen
<p>detaches the panel groups and Property inspector and opens a separate Code Inspector,
<p>ready for you to arrange as you like. The Mac version has two preset options: the Default
<p>layout shown in 1-5 and the Dual Screen option.
<p>To select a layout, go to Window <b>ä </b>Workspace Layout, and choose the layout you want
<p>to use.
<p><b>Rearranging panels</b>
<p>The preset layouts are just a start. You can undock any
<p>panel group by hovering your mouse pointer over the
<p>left side of a panel’s title bar until it turns into a fourheaded
<p>arrow, as shown alongside (or a hand on the
<p>Mac version). Hold down your mouse button, and drag
<p>the panel to wherever you want.
<p><b>Saving and sharing customized workspace layouts</b>
<p>In addition to undocking panel groups, you can reorganize the panels into different groups
<p>to suit your own preferences or to reflect different priorities for various projects. To move
<p>a panel, open its parent panel group, and select the panel you want to move. Then rightclick
<p>the icon on the right of the panel group’s title bar to display the Options menu, as
<p>shown in the following screenshot. You can choose to move the panel to an existing group
<p>or to create a new panel group. The menu also offers other options, including renaming
<p>the panel group. (The same options are available from a much larger menu if you use your
<p>main mouse button.)
<p>Once everything is the way you want it, save the new layout by choosing Window <b>ä</b>
<p>Workspace Layout <b>ä </b>Save Current. The name of your customized workspace appears at the
<p>top of the Workspace Layout submenu. There is no limit to the number of preset layouts
<p>that you can create, and you can switch freely between layouts without restarting the program.
<p>To rename or remove customized layouts, use the Manage option at the bottom of
<p>the Workspace Layout submenu.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>14</b>
<p>You can transfer customized layouts to another computer by copying the XML files that
<p>store the details. In Windows XP, the files are in C:\Documents and Settings\&lt;username&gt;\
<p>Application Data\Adobe\Dreamweaver 9\Configuration\Workspace, where &lt;username&gt;
<p>is the Windows account to which you are currently logged in. In Vista, they’re in C:\Users\
<p>&lt;username&gt;\AppData\Roaming\Adobe\Dreamweaver 9\Configuration\Workspace. If you
<p>can’t see the Application Data or AppData folder, see the next section, “Accessing hidden
<p>files and folders in Windows.”
<p>On a Mac, they are in Macintosh HD:Users:&lt;username&gt;:Library:Application Support:
<p>Adobe:Dreamweaver 9:Configuration:Workspace.
<p>The files have the same name that you used to save the layout. Simply copy them to the
<p>other computer, and restart Dreamweaver. Since they’re XML, you can share them among
<p>Windows and Mac users.
<p><b>Accessing hidden files and folders in Windows</b>
<p>Most Dreamweaver configuration files are hidden by default in Windows XP and Vista. To
<p>edit or copy them, you need to enable the option to view hidden files and folders. Once
<p>you turn on this option, hidden folders are displayed as dimmed icons to remind you to
<p>treat them with care.
<p>In Windows XP, go to Start <b>ä </b>My Computer <b>ä </b>Tools <b>ä </b>Folder Options <b>ä </b>View. In Advanced
<p>settings, select Show hidden files and folders. In Vista, go to Start <b>ä </b>Computer <b>ä </b>Organize <b>ä</b>
<p>Folder and Search Options <b>ä </b>View. In Advanced settings, select Show hidden files and folders.
<p><b>Displaying optional toolbars</b>
<p>Bizarre though it may seem, the Standard toolbar (see following screenshot) is not displayed
<p>by default. To display it, go to View <b>ä </b>Toolbars, and select Standard. Alternatively,
<p>right-click any toolbar, and select Standard from the context menu.
<p>Dreamweaver automatically locates the Standard toolbar—which contains common file
<p>functions such as New Document, Open, Save, Print, Cut, Copy, and Paste—immediately
<p>below the Document toolbar. This isn’t really very helpful, because it means the toolbar
<p>disappears as soon as all documents are closed.
<p>However, on Windows you can move the Standard toolbar by positioning your mouse
<p>pointer over the double row of dots at the left edge, holding down the main mouse button,
<p>and dragging and dropping the toolbar to a new location. If you have a wide monitor,
<p>you can place it alongside the Insert bar. Alternatively, dock it directly underneath the
<p>Insert bar. It then remains available at all times.
<p>On a Mac, there appears to be no way of undocking the Standard toolbar from the
<p>Document toolbar.
<p><b>Temporarily hiding all panels</b>
<p>When you want to clear the onscreen clutter to see your design in all its glory, just press
<p>F4, and all the panels disappear, leaving the Document window on its own. In Windows,
<p>DREAMWEAVER CS3—
<p><b>15</b>
<p><b>1</b>
<p>the Document window expands to fill the entire workspace. On a Mac, panels disappear,
<p>but the Document window doesn’t change size. Press F4 again: the panels return, and on
<p>Windows, the Document window shrinks back to fit inside the workspace.
<p><b>Organizing visual assets with Bridge</b>
<p>If you have used Adobe Creative Suite 2, you’ll already be familiar with Bridge, although it
<p>has undergone a considerable transformation in CS3. It’s a powerful file organizer with
<p>features designed to appeal to photographers and designers, and it now comes bundled
<p>with Dreamweaver CS3. To do Bridge justice would require several chapters, so I’ll concentrate
<p>on the main points that apply to Dreamweaver.
<p>You can launch Bridge CS3 either from the Start menu in Windows and Applications in Mac
<p>OS X or from inside Dreamweaver or any other CS3 program. To launch Bridge from inside
<p>Dreamweaver, go to File <b>ä </b>Browse in Bridge, or click the Browse in Bridge button on the
<p>Standard toolbar (shown alongside).
<p>Bridge is a large program, so it doesn’t appear instantly. The advantage of launching Bridge
<p>from inside Dreamweaver is that it automatically displays the root folder of the current
<p>site in the Content tab. 1-11 shows the default layout of Bridge after navigating to a
<p>site’s main images folder.
<p><b>1-11. </b>Bridge CS3 makes it easy to view and organize a website’s visual assets.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>16</b>
<p>The Content tab in the center displays the contents of the selected folder. At first glance, it
<p>may not look very different from Windows Explorer or Mac Finder, but the first thing you’ll
<p>notice is that if you have Flash movies (SWF files) or video (FLV), Fireworks PNG files,
<p>Photoshop PSD files, or Adobe Illustrator AI files, you can see a thumbnail of the contents,
<p>rather than an icon. You can also play Flash video and see the contents of most PDF files.
<p>You can even flip through the pages of a PDF in the Preview panel at the top right.
<p>Two features that will appeal to digital photographers are the abilities to use Bridge to
<p>import photos directly from your camera (File <b>ä </b>Get Photos from Camera) and to preview
<p>photos stored in Camera Raw, the generic name given to the native format of most
<p>middle-range and professional-level digital cameras.
<p><b>Controlling thumbnails</b>
<p>The thumbnails in the Content tab are scalable. Just drag the pointer at the right end of the
<p>Bridge status bar to make them bigger or smaller. If the thumbnails look blurred, switch
<p>the default to High Quality Thumbnails by opening the Preferences panel (Edit <b>ä </b>Preferences
<p>or Bridge <b>ä </b>Preferences on a Mac) and selecting the Thumbnails category. The Thumbnails
<p>category in Preferences also lets you choose other information to be displayed under the
<p>thumbnail in addition to the file name.
<p>Once a thumbnail has been generated, Bridge caches it in a central folder to speed up the
<p>program’s performance. By default, the cache is created in your own user folders, but you
<p>can change the location through the Advanced category of Preferences. It’s a good idea to
<p>purge the cache from time to time to avoid clogging up your hard disk with thumbnails of
<p>files no longer in use. You can clear the entire cache by clicking the Purge Cache button in
<p>the Advanced category of Preferences. To clear the cached thumbnails for a single folder,
<p>go to Tools <b>ä </b>Cache, and select Purge Cache for Folder “<i>foldername</i>”.
<p>As well as the default view shown in 1-11, there are two other layouts: Filmstrip
<p>Focus and Metadata Focus (which displays metadata alongside the thumbnail). You can
<p>quickly switch between views by clicking one of the numbers at the bottom right of the
<p>Bridge status bar.
<p>If you want to display your images in their full glory, Bridge can create a full-screen
<p>slideshow (View <b>ä </b>Slideshow or Slideshow Options). Press Esc to exit the slideshow.
<p><b>Adding metadata</b>
<p>To get the most out of Bridge’s powerful search capabilities, you need to input information
<p>about your images, such as keywords, designer/photographer, ranking (you can give
<p>images star ratings), and so on. You fill in these details in the Metadata and Keywords tabs
<p>at the bottom right of the default view.
<p><b>Renaming files</b>
<p>One of the most useful features of Bridge is its ability to rename large numbers of files.
<p>Let’s say you have just received a batch of photos from a client and they have meaningless
<p>names such as DSC_0417.jpg. You can rename them all in seconds by selecting them in
<p>DREAMWEAVER CS3—
<p><b>17</b>
<p><b>1</b>
<p>Bridge and going to Tools <b>ä </b>Batch Rename. The options allow you to build up complex yet
<p>meaningful names. You can rename the existing files in the same folder or make renamed
<p>copies in a different folder.
<p>Although you can use the batch rename feature to change the file name extension of all
<p>files in a website from .html to .php, the integration with Dreamweaver is not smart
<p>enough to update all internal links inside the files. This would be a useful addition to a
<p>future version.
<p><b>Dragging and dropping files</b>
<p>You can drag and drop any file directly from Bridge into Dreamweaver or another CS3 program.
<p>If you drag an image into Dreamweaver, it’s inserted into the page wherever you
<p>drop it, automatically creating the necessary XHTML. If you drag an image into Fireworks,
<p>it’s immediately ready for editing.
<p><b>Creating standards-compliant web pages</b>
<p>No sooner was Dreamweaver 8 out of the door than a team of Dreamweaver engineers
<p>were recruited for a secret mission known as Project Hoover, a reference to the wellknown
<p>brand of vacuum cleaners. The team’s task has been to sweep up relics of the past,
<p>removing obsolete tags and markup from the code that Dreamweaver creates when laying
<p>out a web page. Web standardistas will be quick to point out that the job isn’t complete,
<p>but the team has trodden a delicate path between striving for full standards compliance
<p>and maintaining backward compatibility with existing sites. I understand that the team
<p>members haven’t packed away their coveralls; they plan to keep on vacuuming as they
<p>work on the next release. They’re not ready to flip the Hoover off switch just yet.
<p><b>Enhanced CSS support</b>
<p>In spite of some failings, particularly in regard to ensuring full compliance with a Strict
<p>DTD—which is still left up to the user—I think it’s fair to say that Dreamweaver CS3 is the
<p>most standards-compliant version of the program yet. It comes with an impressive array of
<p>standard layouts, styled with fully-commented CSS. The handling of CSS style rules and the
<p>visual rendering of pages in Design view are much improved. Dreamweaver CS3 is
<p>browser-neutral: unlike the previous version, it doesn’t attempt to emulate Internet
<p>Explorer 6. Instead, it attempts to render styles according to the CSS 2.1 recommendation
<p>laid down by W3C—and mostly succeeds.
<p>As part of Project Hoover, Dreamweaver dropped proprietary terminology in favor of
<p>more descriptive terms.
<p><b>Layers are dead . . . Welcome, AP elements</b>
<p>One important change for existing Dreamweaver users and those migrating from GoLive is
<p>that layers are dead. Since a layer is really a &lt;div&gt; that has been absolutely positioned with
<p>CSS, Dreamweaver CS3 now calls them AP elements. While this may seem a cosmetic
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>18</b>
<p>change, the idea is to clarify how they fit into a web page. What’s more, any tag can be
<p>used to create an AP element, not just a &lt;div&gt;.
<p>1-12 shows how Dreamweaver CS3 renders the following code (it’s in examples/
<p>ch01/classof58.html in the download files):
<p>&lt;div id=&#8221;wrapper&#8221;&gt;
<p>&lt;img id=&#8221;header&#8221; src=&#8221;images/header.jpg&#8221; alt=&#8221;Class of 58&#8243; <b>å</b>
<p><b>width=&#8221;720&#8243; height=&#8221;175&#8243; /&gt;</b>
<p><b>&lt;ul id=&#8221;nav&#8221;&gt;</b>
<p><b>&lt;li&gt;&lt;a href=&#8221;#&#8221;&gt;Home&lt;/a&gt;&lt;/li&gt;</b>
<p><b>&lt;li&gt;&lt;a href=&#8221;#&#8221;&gt;2006 Reunion&lt;/a&gt;&lt;/li&gt;</b>
<p><b>&lt;li&gt;&lt;a href=&#8221;#&#8221;&gt;Memory Lane &lt;/a&gt; &lt;/li&gt;</b>
<p><b>&lt;li&gt;&lt;a href=&#8221;#&#8221;&gt;Roll call&lt;/a&gt;&lt;/li&gt;</b>
<p><b>&lt;li&gt;&lt;a href=&#8221;#&#8221;&lt;/a&gt;&lt;/li&gt;</b>
<p><b>&lt;li&gt;&lt;a href=&#8221;#&#8221;&gt;Contact&lt;/a&gt;&lt;/li&gt;</b>
<p><b>&lt;/ul&gt;</b>
<p>&lt;/div&gt;
<p>The wrapper &lt;div&gt; is relatively positioned to center the whole page in the browser and
<p>contains two absolutely positioned elements: an image with the ID header and an
<p>unordered list with the ID nav. As you can see, the AP Elements panel on the right of the
<p>lists both absolutely positioned elements but not the relatively positioned one. In
<p>previous versions of Dreamweaver, the Layers panel ignored absolutely positioned elements
<p>unless they used a &lt;div&gt; tag.
<p><b>1-12. </b>Dreamweaver CS3 lists all absolutely positioned elements in the new AP Elements panel.
<p><i>For backward compatibility, “layers” still live on in the name of the JavaScript function</i>
<p><i>associated with one of the Dreamweaver behaviors. Although the </i>Show/Hide Layers
<p><i>behavior has been renamed </i>Show/Hide Elements<i>, the function is still called</i>
<p>MM_showHideLayers<i>. However, the behavior now handles any element that has an ID.</i>
<p><i>Behaviors are covered in the next chapter.</i>
<p>DREAMWEAVER CS3—
<p><b>19</b>
<p><b>1</b>
<p>This new arrangement gives you much greater flexibility and control over your CSS.
<p>There’s no longer any need to litter your code with unnecessary &lt;div&gt; tags, and the AP
<p>Elements panel provides an instant snapshot of the absolutely positioned elements on your
<p>page. You can drag and drop elements within the panel to change their z-index property,
<p>and the eye icon on the left of the panel changes the visibility property. AP elements
<p>nested inside another AP element are indented, and if you realize that the nesting is causing
<p>an element to be displayed in the wrong place, you can separate them by dragging the
<p>nested element to the left of the panel. Changes made in the AP Elements panel automatically
<p>update the element’s style rules, even if they are in a separate style sheet.
<p><b>Seeing the impact of CSS changes in real time</b>
<p>Grouped together with the AP Elements panel is the CSS Styles panel, which lets you
<p>inspect and edit style rules without leaving Design view. As a result, you can see immediately
<p>how your changes affect the layout of the page and tweak them until you get the
<p>desired result. Like many features in Dreamweaver, the CSS Styles panel is context sensitive.
<p>1-13 shows the styles for the nav unordered list in classof58.html. The properties
<p>for the #nav ID selector are shown in the lower section of the panel, while the upper
<p>sections show all the rules that affect the element currently selected in Design view. This
<p>helps you understand how the rules are cascaded down to a particular element, making it
<p>easier to troubleshoot styles that don’t work the way you expect. Chapters 5 and 6 show
<p>you how to make effective use of the CSS Styles panel.
<p><b>1-13.</b>
<p>The CSS Styles panel shows which styles in the
<p>cascade affect the selected element.
<p><i>The style rules for </i>classof58.html <i>are in </i>classof58.css <i>in the </i>styles <i>folder.</i>
<p><i>This example has been deliberately designed to demonstrate a new feature of</i>
<p><i>Dreamweaver CS3. I don’t necessarily recommend the use of AP elements to</i>
<p><i>achieve this particular layout.</i>
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>20</b>
<p><b>Improved style sheet management</b>
<p>A major innovation in Dreamweaver CS3 is the ability to drag and drop selectors in the
<p>CSS Styles panel to reorder style blocks in your style sheet. You can also move styles out
<p>of the &lt;head&gt; of a document into a new or an existing style sheet with just a couple of
<p>mouse clicks. The target style sheet doesn’t even need to exist or to be open; everything
<p>happens automatically.
<p>If you have old-style layers with inline styles, you can clean up your pages easily by using
<p>the Convert Inline CSS to Rule feature to move the rules into the &lt;head&gt; of the document
<p>or an external style sheet. It doesn’t matter whether you’re in Code view or Design view; as
<p>long as your cursor is anywhere inside a layer, just right-click and select CSS Styles <b>ä</b>
<p>Convert Inline CSS to Rule from the context menu. Dreamweaver presents you with the dialog
<p>box shown in 1-14.
<p><b>1-14. </b>As long as your cursor is inside a layer, Dreamweaver can move the
<p>inline styles to an external style sheet or the head of the document.
<p>Dreamweaver automatically chooses the ID as the name of the selector for the new rule.
<p>Although you can change the name in the dialog box, this affects only the new style rule.
<p>It doesn’t change the ID of the &lt;div&gt;. You can convert only one layer at a time, but it’s a
<p>much quicker and more accurate way of tidying up legacy pages than attempting to cut
<p>and paste everything manually. The Convert to drop-down menu at the top left of the
<p>Convert Inline CSS dialog box has two other options: to create a class based on the inline
<p>styles or to apply the styles to all &lt;div&gt; elements. They are there for completeness and
<p>should be used rarely, if ever. You can test this feature using layers.html in
<p>examples/ch01.
<p>Another small improvement to CSS management in Dreamweaver CS3 is the option to
<p>clean up the formatting of style rules by selecting Apply Source Formatting from the
<p>Commands menu. The available formatting options are shown in 1-15. They’re very
<p>basic in comparison with a dedicated CSS editor like TopStyle Pro but are nevertheless a
<p>welcome addition. To access the CSS Source Format Options dialog box, go to Preferences
<p>on the Edit menu (Dreamweaver menu on a Mac), select the Code Format category, and
<p>click the Advanced Formatting CSS button.
<p>DREAMWEAVER CS3—
<p><b>21</b>
<p><b>1</b>
<p><b>1-15. </b>You can tell Dreamweaver CS3 how you prefer
<p>style sheets to be laid out.
<p><b>Using visual aids to understand your CSS structure</b>
<p>Dreamweaver’s visual aids are a powerful feature that helps you visualize the underlying
<p>structure of your page by highlighting individual block elements and their associated
<p>padding and margins in Design view. Most visual aids are turned on by default but remain
<p>in the background until you select a particular block element, such as a &lt;div&gt; or &lt;table&gt;.
<p>1-16 shows one of the preset layouts with the container &lt;div&gt; selected in the Tag
<p>selector (the file is also in examples/ch01/visualaids.html).
<p><b>1-16. </b>Dreamweaver lets you see the underlying structure of your page with powerful
<p>visual aids.</p>
Posted in Uncategorized  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/swebsolution.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/swebsolution.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/swebsolution.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/swebsolution.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/swebsolution.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/swebsolution.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/swebsolution.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/swebsolution.wordpress.com/34/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/swebsolution.wordpress.com/34/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/swebsolution.wordpress.com/34/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=34&subd=swebsolution&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://swebsolution.wordpress.com/2009/01/22/dreamweaver-cs3-with-css-ajax-and-php-02/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4fc1b8adaf945b9ecf45239af6e622af?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Prakash Sherawat</media:title>
		</media:content>
	</item>
		<item>
		<title>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP 01</title>
		<link>http://swebsolution.wordpress.com/2009/01/22/dreamweaver-cs3-with-css-ajax-and-php-01/</link>
		<comments>http://swebsolution.wordpress.com/2009/01/22/dreamweaver-cs3-with-css-ajax-and-php-01/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 10:26:33 +0000</pubDate>
		<dc:creator>Prakash Sherawat</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://swebsolution.wordpress.com/2009/01/22/dreamweaver-cs3-with-css-ajax-and-php-01/</guid>
		<description><![CDATA[In one respect, the change symbolizes the fact that Dreamweaver is under new ownership.
Macromedia, the company that turned Dreamweaver, Flash, and Fireworks into must-have
tools for web developers, was acquired by Adobe at the end of 2005. And Dreamweaver
(together with former Macromedia stable mates Fireworks and Flash) is now part of
Creative Suite, Adobe’s family of web [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=32&subd=swebsolution&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In one respect, the change symbolizes the fact that Dreamweaver is under new ownership.
<p>Macromedia, the company that turned Dreamweaver, Flash, and Fireworks into must-have
<p>tools for web developers, was acquired by Adobe at the end of 2005. And Dreamweaver
<p>(together with former Macromedia stable mates Fireworks and Flash) is now part of
<p>Creative Suite, Adobe’s family of web and print design tools that includes Photoshop,
<p>Illustrator, and InDesign. Creative Suite is now in its third iteration; hence CS3. Although
<p>each program has a long history, the idea of Creative Suite is to promote greater integration
<p>to make it easier to switch to the best tool for a particular job, such as Photoshop for
<p>photo manipulation and retouching, and import the results into another program. And
<p>that’s what’s happened to Dreamweaver: although it’s available as a stand-alone program,
<p>it’s now closely integrated with its new Adobe brothers and sisters as part of Adobe Web
<p>Suite CS3 and Design Suite CS3.
<p>Even the stand-alone version of Dreamweaver CS3 comes bundled with three other
<p>programs:
<p><b>Extension Manager CS3</b>: An updated version of the program that lets you install
<p>third-party add-ons to extend the functionality of Dreamweaver, Flash, and Fireworks.
<p><b>Adobe Bridge CS3</b>: As the name suggests, this is intended to facilitate communication
<p>between the various parts of Creative Suite, but it also works with the standalone
<p>version of Dreamweaver. At one level, it’s like a super-charged version of
<p>Windows Explorer or Finder on the Mac, but it shines in the handling of visual
<p>assets. It allows you to see inside a wide variety of formats, making it easy to find
<p>an image by what it looks like.
<p><b>Adobe Device Central CS3</b>: This is a brand new program that allows you to visualize
<p>what your websites will look like in a wide range of mobile devices, not only
<p>from the layout point of view but also simulating mobile backlight and sunlight
<p>reflections.
<p>The integration goes further through the ability to copy and paste directly from a
<p>Photoshop PSD file into Dreamweaver. When you do so, Dreamweaver optimizes the file
<p>for the Web. So, yes, the “CS3” does make sense. It’s not just change for the sake of
<p>change.
<p>Once installed, Extension Manager, Bridge, and Device Central are separate programs and
<p>can be launched independently, but you have no choice whether to install them. The
<p>installer simply lists them as “Shared Components.” As a result, this version of Dreamweaver
<p>occupies roughly four times more disk space than previous versions. Personally, I like
<p>Bridge and think that Device Central is likely to become increasingly useful as mobile Web
<p>access grows in popularity. Others may disagree.
<p>If you’re a long-term Dreamweaver user, though, the program that you know and love
<p>hasn’t changed beyond recognition. As Figures 1-4 and 1-5 show, the workspace layout is
<p>identical to Dreamweaver 8. The development team moved with Dreamweaver to Adobe,
<p>and the improvements to the program are a logical progression. Adobe accompanied
<p>its decision to include Dreamweaver in Creative Suite 3 with the bold step of dropping its
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>2</b>
<p>own web design program, GoLive. Although GoLive has been updated, it’s not in any of the
<p>CS3 packages. What’s more, Adobe has created an online tutorial to help GoLive users
<p>migrate to Dreamweaver (www.adobe.com/go/learn_dw_golive). This sends a clear message
<p>that Adobe now regards Dreamweaver as its prime tool for developing standardscompliant
<p>websites.
<p>In this chapter, we’ll take a look at the most important features and changes in
<p>Dreamweaver CS3, with particular emphasis on cascading style sheets (CSS) and creating
<p>standards-compliant Extensible HyperText Markup Language (XHTML), both of which are
<p>essential for building any modern website. Then, in the following chapter, we’ll take a look
<p>at the tools Dreamweaver offers for building dynamic websites: Spry—Adobe’s implementation
<p>of Asynchronous JavaScript + XML (Ajax)—and PHP.
<p>What this chapter covers
<p>Finding out what’s new in Dreamweaver CS3
<p>Exploring and organizing the Dreamweaver workspace
<p>Using Bridge to manage visual assets
<p>Taking a first look at Dreamweaver’s support for cascading style sheets
<p>Getting the best out of Code view
<p><b>Getting your bearings in Dreamweaver</b>
<p>As the title of this book says, this is an <i>essential </i>guide to Dreamweaver CS3. So I don’t
<p>intend to bore you to death with descriptions of every menu and submenu. However, all
<p>readers may not be familiar with Dreamweaver, so I’ll start with a few signposts to guide
<p>you around the Dreamweaver interface and help set basic program preferences. Most of
<p>this will be familiar to experienced users of Dreamweaver, but there are some important
<p>changes. To identify these changes, look for the New and Changed graphics in the margin.
<p><b>Starting up</b>
<p>When you launch Dreamweaver CS3, the first thing you see after the program has finished
<p>loading is the welcome screen shown in 1-1. The three columns in the top section
<p>provide quick access to a recently opened document (this list is empty the first time you
<p>launch Dreamweaver), create a new document or Dreamweaver site (site definition is
<p>covered in Chapter 4), or select from a predefined layout. The Dreamweaver Exchange
<p>option at the foot of the right column takes you directly to the Adobe Dreamweaver
<p>Exchange (www.adobe.com/cfusion/exchange/index.cfm?view=sn120), where you can
<p>obtain extensions to add extra functionality to Dreamweaver (many are free; others are
<p>sold on a commercial basis). The bottom section of the welcome screen takes you to various
<p>parts of the Adobe website and displays what Adobe considers useful information, for
<p>example, available updates to the program.
<p>DREAMWEAVER CS3—
<p><b>3</b>
<p><b>1</b>
<p><b>1-1. </b>The welcome screen offers access to recent documents and a quick way to
<p>create new ones.
<p>The Dreamweaver welcome screen reappears whenever you close all documents in the
<p>workspace and connects to Adobe to see if there are any new announcements. In previous
<p>versions, leaving the welcome screen enabled was a resource hog, so many developers
<p>chose the Don’t show again option at the bottom left. This means what it says: once you
<p>select it, the welcome screen disappears forever. If you want it back, go to Edit <b>ä</b>
<p>Preferences (Dreamweaver <b>ä </b>Preferences on a Mac), choose the General category, and
<p>select Show welcome screen.
<p>Although the welcome screen no longer appears to be a resource hog, you may prefer to
<p>switch it off because you get a much better range of options from the New Document dialog
<p>box. You can also con Dreamweaver to reopen on startup any documents that
<p>are still open when you close the program. Just select Reopen documents on startup in the
<p>General category of the Preferences panel.
<p><b>Creating a new document</b>
<p>To create a new document, select File <b>ä </b>New or press Ctrl+N/Cmd+N. This opens the New
<p>Document dialog box, which has been considerably revamped, as shown in 1-2.
<p>The biggest change is that, in addition to a completely blank page, you can now select one
<p>of 32 CSS layouts. There are also options to change the page’s document type definition
<p>(DTD)—by default, Dreamweaver CS3 uses XHTML 1.0 Transitional—and to attach an
<p>external style sheet to the page at the time of creation. We’ll look at the CSS layouts and
<p>style sheet options in Chapters 5 and 6.
<p>DREAMWEAVER CS3 WITH CSS, AJAX, AND PHP
<p><b>4</b>
<p><b>1-2. </b>The New Document dialog box offers a massive range of options and preset layouts.
<p>By selecting the appropriate option from the menu on the left side of the New Document
<p>dialog box, you can also create new templates from scratch or a page from an existing
<p>template (templates are covered in Chapter 12). The Page from Sample option offers a
<p>wide range of preset layouts, but I don’t recommend using them, as many of them use oldstyle
<p>presentational elements and deprecated attributes. The final option, labeled Other,
<p>contains a variety of pages for programming languages such as ActionScript, C#, and
<p>VBScript, none of which are used in this book.
<p><b>Setting new document preferences</b>
<p>Click the Preferences button at the bottom left of the New Document dialog box.
<p>Alternatively, choose Preferences from the Edit menu (Dreamweaver menu on a Mac), and
<p>select the New Document category. Either presents you with the New Document Preferences
<p>dialog box shown in 1-3.
<p>The dialog box lets you set the following global preferences:
<p>Default document lets you choose the type of document that will be created when
<p>you use the keyboard shortcut for a new document (Ctrl+N/Cmd+N). For this to
<p>work, you must deselect the option at the bottom labeled Show New Document dialog
<p>box on Control+N/Cmd+N. Otherwise, the dialog box shown in 1-2 will
<p>appear.
<p>Default extension affects only (X)HTML files. Change the value only if you want to
<p>use .htm to maintain unity with the naming convention of older sites.
<p>Default Document Type (DTD) sets the default DOCTYPE declaration for all new web
<p>pages. You cannot set one value for, say, .html and another for .php pages.
<p>DREAMWEAVER CS3—
<p><b>5</b>
<p><b>1</b>
<p><b>1-3. </b>The New Document category of the Preferences panel
<p>Default encoding lets you choose the character set to be used in all web pages. The
<p>Dreamweaver CS3 default is Unicode (UTF-8). (In the Mac version, this is listed as
<p>Unicode 4.0 UTF-8.) This is different from previous versions. The checkbox below
<p>this option tells Dreamweaver to use the same character set to display existing
<p>pages that don’t specify a particular encoding. It doesn’t insert any extra coding in
<p>such pages.
<p>Unicode Normalization Form is required only when using UTF-8 for encoding. It
<p>should normally be set to C (Canonical Decomposition, followed by Canonical
<p>Composition), and the Include Unicode Signature (BOM) checkbox should be deselected.
<p>If you use any other encoding, set Unicode Normalization Form to None.
<p><b>Choosing the default document type </b>Many people misunderstand the purpose of the DTD
<p>(the DOCTYPE declaration before the opening &lt;html&gt; tag). It simply tells the browser how
<p>you have coded your page and is intended to speed up the correct rendering of your
<p>design. It’s not a badge of honor or magic spell that somehow renders your web pages
<p>future-proof. The default setting in Dreamweaver CS3 is XHTML 1.0 Transitional, and this is
<p>the appropriate choice for most people when creating a new web page <i>as long as you</i>
<p><i>understand the stricter rules imposed by XHTML</i>.
<p><i>Visit </i>www.w3.org/TR/xhtml1/#diffs <i>to learn about the differences</i>
<p><i>between HTML and XHTML. Also read the frequently asked questions</i>
<p><i>at </i><a href="http://www.w3.org/MarkUp/2004/xhtml-faq">www.w3.org/MarkUp/2004/xhtml-faq</a><i>.</i>
<p><em></em>&nbsp;</p>
<div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:86e8b58d-8810-49e7-b1de-3958bafb1ca2" style="display:inline;margin:0;padding:0;">Technorati Tags: <a href="http://technorati.com/tags/DREAMWEAVER%20CS3%20WITH%20CSS" rel="tag">DREAMWEAVER CS3 WITH CSS</a>,<a href="http://technorati.com/tags/AJAX" rel="tag">AJAX</a>,<a href="http://technorati.com/tags/AND%20PHP%2001" rel="tag">AND PHP 01</a></div>
Posted in Uncategorized  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/swebsolution.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/swebsolution.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/swebsolution.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/swebsolution.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/swebsolution.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/swebsolution.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/swebsolution.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/swebsolution.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/swebsolution.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/swebsolution.wordpress.com/32/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=32&subd=swebsolution&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://swebsolution.wordpress.com/2009/01/22/dreamweaver-cs3-with-css-ajax-and-php-01/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4fc1b8adaf945b9ecf45239af6e622af?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Prakash Sherawat</media:title>
		</media:content>
	</item>
		<item>
		<title>Valentine Gifts &amp; Valentine Jewelry</title>
		<link>http://swebsolution.wordpress.com/2008/02/08/valentine-gifts-valentine-jewelry/</link>
		<comments>http://swebsolution.wordpress.com/2008/02/08/valentine-gifts-valentine-jewelry/#comments</comments>
		<pubDate>Fri, 08 Feb 2008 15:12:42 +0000</pubDate>
		<dc:creator>Prakash Sherawat</dc:creator>
				<category><![CDATA[Valentine Gift]]></category>

		<guid isPermaLink="false">http://swebsolution.wordpress.com/2008/02/08/valentine-gifts-valentine-jewelry/</guid>
		<description><![CDATA[Heartfelt Gifts for your Valentine
Love, commitment and more&#8230; Specially handcrafted jewelry
symbolizing your journey of growing love.
Celebrate life, celebrate love. Special gifts to cherish the special moments of
togetherness.
More for less&#8230;. Enchanting sets of exquisitely matched jewelry with great
value for your money.
Choose a gemstone of her preference and complement it with a setting from our exquisite collection.








18k [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=26&subd=swebsolution&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h5 align="center"><a href="http://www.angara.com/"><strong>Heartfelt Gifts for your Valentine</strong></a><br />
Love, commitment and more&#8230; Specially handcrafted jewelry<br />
symbolizing your journey of growing love.<br />
Celebrate life, celebrate love. Special gifts to cherish the special moments of<br />
togetherness.<br />
More for less&#8230;. Enchanting sets of exquisitely matched jewelry with great<br />
value for your money.<br />
Choose a gemstone of her preference and complement it with a setting from our exquisite collection.</h5>
<div align="center">
<table border="1" align="center" width="494" style="width:494px;height:409px;">
<tr>
<td width="246"><a href="http://www.angara.com/shop.do?pID=216270" title="Valentine Gift"><img border="0" width="150" src="http://www.angara.com/store/assets/images/products/Gemstone/APW0449_Small.jpg" height="150" /></a></td>
<td width="192"><a href="http://www.angara.com/shop.do?cID=1896&amp;pID=217851" title="Valentin Gigts"><img border="0" width="150" src="http://www.angara.com/store/assets/images/products/Gemstone/APW0451_Small.jpg" alt="Valentine Jewelry" height="150" /></a></td>
<td><a href="http://www.angara.com/shop.do?cID=1896&amp;pID=216271" title="Valentien Gift"><img border="0" width="150" src="http://www.angara.com/store/assets/images/products/Gemstone/APW0450_Small.jpg" height="150" /></a></td>
</tr>
<tr>
<td height="48" width="246"><font color="#ff9900">18k White Gold Diamond Heart Pendant (3/4 ct. tw.) <b>$589.99</b></font></td>
<td height="48" width="192"><font color="#ff9900">18k White Gold Ruby Heart Pendants<br />
<b></b><b>$339.99</b></font></td>
<td height="48"><font color="#ff9900">18k White Gold Diamond and Ruby Designer Heart Pendant <u><b>$399.99</b></u></font></td>
</tr>
<tr>
<td width="246"><font color="#ff9900">A lovely accessory to compliment your outfit. This 18k white<br />
gold pendant features round brilliant diamonds (0.70 ct. tw.) in<br />
a pretty heart shape.</font></td>
<td width="192"><font color="#ff9900">Dramatic and Colorful, this 18k white gold pendant features a heart<br />
studded with ruby gemstones (1.63 ct. tw.). This gorgeous heart pendant<br />
will add color to any attire</font></td>
<td><font color="#ff9900">A graceful, stylized heart motif featuring round brilliant<br />
diamonds (0.11 ct. tw.) and red ruby gemstones (0.34 ct. tw.) in<br />
a contemporary design. This 18k white gold pendant is a treat<br />
for the jewelry lover.</font></td>
</tr>
<tr>
<td width="246">
<h5><a href="http://www.angara.com/shop.do?cID=1706&amp;landing=valentine"><font color="#ff9900">Valentine Gifts</font></a></h5>
</td>
<td width="192">
<h5><a href="http://www.angara.com/shop.do?cID=1706"><font color="#ff9900">Valentines Day Gifts</font></a></h5>
</td>
<td>
<h5><a href="http://www.angara.com/gembuilder_load.do"><font color="#ff9900">Valentine Jewelry Gift</font></a></h5>
</td>
</tr>
</table>
</div>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/swebsolution.wordpress.com/26/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/swebsolution.wordpress.com/26/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/swebsolution.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/swebsolution.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/swebsolution.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/swebsolution.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/swebsolution.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/swebsolution.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/swebsolution.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/swebsolution.wordpress.com/26/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/swebsolution.wordpress.com/26/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/swebsolution.wordpress.com/26/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=26&subd=swebsolution&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://swebsolution.wordpress.com/2008/02/08/valentine-gifts-valentine-jewelry/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4fc1b8adaf945b9ecf45239af6e622af?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Prakash Sherawat</media:title>
		</media:content>

		<media:content url="http://www.angara.com/store/assets/images/products/Gemstone/APW0449_Small.jpg" medium="image" />

		<media:content url="http://www.angara.com/store/assets/images/products/Gemstone/APW0451_Small.jpg" medium="image">
			<media:title type="html">Valentine Jewelry</media:title>
		</media:content>

		<media:content url="http://www.angara.com/store/assets/images/products/Gemstone/APW0450_Small.jpg" medium="image" />
	</item>
		<item>
		<title>Java Help, Java Tutorials, Java Programming, Java Tricks</title>
		<link>http://swebsolution.wordpress.com/2008/01/08/java-help-java-tutorials-java-programming-java-tricks-4/</link>
		<comments>http://swebsolution.wordpress.com/2008/01/08/java-help-java-tutorials-java-programming-java-tricks-4/#comments</comments>
		<pubDate>Tue, 08 Jan 2008 08:54:00 +0000</pubDate>
		<dc:creator>Prakash Sherawat</dc:creator>
				<category><![CDATA[Java Help]]></category>

		<guid isPermaLink="false">http://swebsolution.wordpress.com/2008/01/08/java-help-java-tutorials-java-programming-java-tricks-4/</guid>
		<description><![CDATA[
Java Help, Java Tutorials, Java Programming, Java Trickslesson four
Working with Objects
CONTENTS
Creating New Objects
Using new
What new Does
A Note on Memory Management
Accessing and Setting Class and Instance Variables
Getting Values
Changing Values
Class Variables
Calling Methods
Class Methods
References to Objects
Casting and Converting Objects and Primitive Types
Casting Primitive Types
Casting Objects
Converting Primitive Types to Objects and Vice Versa
Odds and Ends
Comparing Objects
Determining the Class of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=25&subd=swebsolution&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><b><br />
Java Help, Java Tutorials, Java Programming, Java Tricks</b><b>lesson four</p>
<p>Working with Objects</p>
<p>CONTENTS</p>
<p>Creating New Objects</p>
<p>Using new</p>
<p>What new Does</p>
<p>A Note on Memory Management</p>
<p>Accessing and Setting Class and Instance Variables</p>
<p>Getting Values</p>
<p>Changing Values</p>
<p>Class Variables</p>
<p>Calling Methods</p>
<p>Class Methods</p>
<p>References to Objects</p>
<p>Casting and Converting Objects and Primitive Types</p>
<p>Casting Primitive Types</p>
<p>Casting Objects</p>
<p>Converting Primitive Types to Objects and Vice Versa</p>
<p>Odds and Ends</p>
<p>Comparing Objects</p>
<p>Determining the Class of an Object</p>
<p>Class and Object Reflection (Java 1.1)</p>
<p>The Java Class Library</p>
<p>Summary</p>
<p>Q&amp;A</p>
<p></b>Let&#8217;s start today&#8217;s lesson with an obvious statement: Because Java is an<br />
object-oriented language, you&#8217;re</p>
<p>going to be dealing with a lot of objects. You&#8217;ll create them, modify them, move<br />
them around, change</p>
<p>their variables, call their methods, combine them with other objects-and, of<br />
course, develop classes and</p>
<p>use your own objects in the mix.</p>
<p>Today, therefore, you&#8217;ll learn all about the Java object in its natural habitat.<br />
Today&#8217;s topics include</p>
<p>Creating instances of classes</p>
<p>Testing and modifying class and instance variables in your new instance</p>
<p>Calling methods in that object</p>
<p>Casting (converting) objects and other data types from one class to another</p>
<p>Other odds and ends about working with objects</p>
<p>An overview of the Java class libraries</p>
<p>Creating New Objects</p>
<p>When you write a Java program, you define a set of classes. As you learned on<br />
Day 2, &#8220;Object-Oriented</p>
<p>Programming and Java,&#8221; classes are templates for objects; for the most part, you<br />
merely use the class to</p>
<p>create instances and then work with those instances. In this section, therefore,<br />
you&#8217;ll learn how to create a</p>
<p>new object from any given class.</p>
<p>Remember strings from yesterday? You learned that using a string literal-a<br />
series of characters enclosed in</p>
<p>double-quotes-creates a new instance of the class String with the value of that<br />
string.</p>
<p>The String class is unusual in that respect-although it&#8217;s a class, there&#8217;s an<br />
easy way to create instances of</p>
<p>that class using a literal. The other classes don&#8217;t have that shortcut; to<br />
create instances of those classes you</p>
<p>have to do so explicitly by using the new operator.</p>
<p>Note</p>
<p>What about the literals for numbers and characters? Don&#8217;t they create</p>
<p>objects, too? Actually, they don&#8217;t. The primitive data types for</p>
<p>numbers and characters create numbers and characters, but for</p>
<p>efficiency, they aren&#8217;t actually objects. You can put object wrappers</p>
<p>around them if you need to treat them like objects (you&#8217;ll learn how to</p>
<p>do this in &#8220;Casting and `Converting Objects and Primitive Types&#8221;).</p>
<p>Using new</p>
<p>To create a new object, you use the new operator with the name of the class you<br />
want to create an instance</p>
<p>of, then parentheses after that. The following examples create new instances of<br />
the classes String,</p>
<p>Random, and Motorcycle, and store those new instances in variables of the<br />
appropriate types:</p>
<p>String str = new String();</p>
<p>Random r = new Random();</p>
<p>Motorcycle m2 = new Motorcycle();</p>
<p>The parentheses are important; don&#8217;t leave them off. The parentheses can be<br />
empty (as in these examples),</p>
<p>in which case the most simple, basic object is created; or the parentheses can<br />
contain arguments that</p>
<p>determine the initial values of instance variables or other initial qualities of<br />
that object:</p>
<p>Date dt = new Date(90, 4, 1, 4, 30);</p>
<p>Point pt = new Point(0,0);</p>
<p>The number and type of arguments you can use inside the parentheses with new are<br />
defined by the class</p>
<p>itself using a special method called a constructor (you&#8217;ll learn more about<br />
constructors later today). If you</p>
<p>try and create a new instance of a class with the wrong number or type of<br />
arguments (or if you give it no</p>
<p>arguments and it needs some), then you&#8217;ll get an error when you try to compile<br />
your Java program.</p>
<p>Here&#8217;s an example of creating several different types of objects using different<br />
numbers and types of</p>
<p>arguments. The Date class, part of the java.util package, creates objects that<br />
represent the current</p>
<p>date. Listing 4.1 is a Java program that shows three different ways of creating<br />
a Date object using new.</p>
<p>Listing 4.1. Laura&#8217;s Date program.</p>
<p>1: import java.util.Date;</p>
<p>2:</p>
<p>3: class CreateDates {</p>
<p>4:</p>
<p>5: public static void main(String args[]) {</p>
<p>6: Date d1, d2, d3;</p>
<p>7:</p>
<p>8: d1 = new Date();</p>
<p>9: System.out.println(&#8220;Date 1: &#8221; + d1);</p>
<p>10:</p>
<p>11: d2 = new Date(71, 7, 1, 7, 30);</p>
<p>12: System.out.println(&#8220;Date 2: &#8221; + d2);</p>
<p>13:</p>
<p>14: d3 = new Date(&#8220;April 3 1993 3:24 PM&#8221;);</p>
<p>15: System.out.println(&#8220;Date 3: &#8221; + d3);</p>
<p>16: }</p>
<p>17: }</p>
<p>Date 1: Tue Feb 13 09:36:56 PST 1996</p>
<p>Date 2: Sun Aug 01 07:30:00 PDT 1971</p>
<p>Date 3: Sat Apr 03 15:24:00 PST 1993</p>
<p>Analysis</p>
<p>In this example, three different date objects are created using different</p>
<p>arguments to the class listed after new. The first instance (line <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> uses</p>
<p>new Date() with no arguments, which creates a Date object for</p>
<p>today&#8217;s date (the first line of the output shows a sample; your output</p>
<p>will, of course, read the current date and time for you).</p>
<p>The second Date object you create in this example has five integer arguments.<br />
The arguments represent a</p>
<p>date: year, month, day, hours, and minutes. And, as the output shows, this<br />
creates a Date object for that</p>
<p>particular date: Sunday, August 1, 1971, at 7:30 a.m.</p>
<p>Note</p>
<p>Java numbers months starting from 0. So although you might expect</p>
<p>the seventh month to be July, month 7 in Java is indeed August.</p>
<p>The third version of Date takes one argument, a string, representing the date as<br />
a text string. When the</p>
<p>Date object is created, that string is parsed, and a Date object with that date<br />
and time is created (see the</p>
<p>third line of output). The date string can take many different formats; see the<br />
API documentation for the</p>
<p>Date class (part of the java.util package) for information about what strings<br />
you can use.</p>
<p>What new Does</p>
<p>When you use the new operator, the new instance of the given class is created,<br />
and memory is allocated</p>
<p>for it. In addition (and most importantly), a special method defined in the<br />
given class is called to initialize</p>
<p>the object and set up any initial values it needs. This special method is called<br />
a constructor. Constructors</p>
<p>are special methods, defined in classes, that create and initialize new<br />
instances of classes.</p>
<p>New Term</p>
<p>Constructors are special methods that initialize a new object, set its</p>
<p>variables, create any other objects that object needs, and generally</p>
<p>perform any other operations the object needs to initialize itself.</p>
<p>Multiple constructor definitions in a class can each have a different number or<br />
type of arguments-then,</p>
<p>when you use new, you can specify different arguments in the argument list, and<br />
the right constructor for</p>
<p>those arguments will be called. That&#8217;s how each of those different versions of<br />
new that you used in the</p>
<p>CreateDates class can create different Date objects.</p>
<p>When you create your own classes, you can define as many constructors as you<br />
need to implement that</p>
<p>class&#8217;s behavior. You&#8217;ll learn how to create constructors on Day 7, &#8220;More About<br />
Methods.&#8221;</p>
<p>A Note on Memory Management</p>
<p>Memory management in Java is dynamic and automatic. When you create a new object<br />
in Java, Java</p>
<p>automatically allocates the right amount of memory for that object in the heap.<br />
You don&#8217;t have to allocate</p>
<p>any memory for any objects explicitly; Java does it for you.</p>
<p>What happens when you&#8217;re finished with that object? How do you de-allocate the<br />
memory that object</p>
<p>uses? The answer, again, is that memory management is automatic. Once you&#8217;re<br />
done with an object, you</p>
<p>reassign all the variables that might hold that object and remove it from any<br />
arrays, thereby making the</p>
<p>object unusable. Java has a &#8220;garbage collector&#8221; that looks for unused objects<br />
and reclaims the memory that</p>
<p>those objects are using. You don&#8217;t have to do any explicit freeing of memory;<br />
you just have to make sure</p>
<p>you&#8217;re not still holding onto an object you want to get rid of. You&#8217;ll learn<br />
more specific details about the</p>
<p>Java garbage collector and how it works on Day 21, &#8220;Under the Hood.&#8221;</p>
<p>New Term</p>
<p>A garbage collector is a special thing built into the Java environment</p>
<p>that looks for unused objects. If it finds any, it automatically removes</p>
<p>those objects and frees the memory those objects were using.</p>
<p>Accessing and Setting Class and Instance Variables</p>
<p>Now you have your very own object, and that object may have class or instance<br />
variables defined in it.</p>
<p>How do you work with those variables? Easy! Class and instance variables behave<br />
in exactly the same</p>
<p>ways as the local variables you learned about yesterday; you just refer to them<br />
slightly differently than you</p>
<p>do regular variables in your code.</p>
<p>Getting Values</p>
<p>To get to the value of an instance variable, you use an expression in what&#8217;s<br />
called dot notation. With dot</p>
<p>notation, the reference to an instance or class variable has two parts: the<br />
object on the left side of the dot</p>
<p>and the variable on the right side of the dot.</p>
<p>New Term</p>
<p>Dot notation is an expression used to get at instance variables and</p>
<p>methods inside a given object.</p>
<p>For example, if you have an object assigned to the variable myObject, and that<br />
object has a variable</p>
<p>called var, you refer to that variable&#8217;s value like this:</p>
<p>myObject.var;</p>
<p>This form for accessing variables is an expression (it returns a value), and<br />
both sides of the dot can also be</p>
<p>expressions. This means that you can nest instance variable access. If that var<br />
instance variable itself</p>
<p>holds an object and that object has its own instance variable called state, you<br />
could refer to it like this:</p>
<p>myObject.var.state;</p>
<p>Dot expressions are evaluated left to right, so you start with myObject&#8217;s<br />
variable var, which points to</p>
<p>another object with the variable state. You end up with the value of that state<br />
variable after the entire</p>
<p>expression is done evaluating.</p>
<p>Changing Values</p>
<p>Assigning a value to that variable is equally easy-just tack an assignment<br />
operator on the right side of the</p>
<p>expression:</p>
<p>myObject.var.state = true;</p>
<p>Listing 4.2 is an example of a program that tests and modifies the instance<br />
variables in a Point object.</p>
<p>Point is part of the java.awt package and refers to a coordinate point with an x<br />
and a y value.</p>
<p>Listing 4.2. The TestPoint Class.</p>
<p>1: import java.awt.Point;</p>
<p>2:</p>
<p>3: class TestPoint {</p>
<p>4: public static void main(String args[]) {</p>
<p>5: Point thePoint = new Point(10,10);</p>
<p>6:</p>
<p>7: System.out.println(&#8220;X is &#8221; + thePoint.x);</p>
<p>8: System.out.println(&#8220;Y is &#8221; + thePoint.y);</p>
<p>9:</p>
<p>10: System.out.println(&#8220;Setting X to 5.&#8221;);</p>
<p>11: thePoint.x = 5;</p>
<p>12: System.out.println(&#8220;Setting Y to 15.&#8221;);</p>
<p>13: thePoint.y = 15;</p>
<p>14:</p>
<p>15: System.out.println(&#8220;X is &#8221; + thePoint.x);</p>
<p>16: System.out.println(&#8220;Y is &#8221; + thePoint.y);</p>
<p>17:</p>
<p>18: }</p>
<p>19:}</p>
<p>X is 10</p>
<p>Y is 10</p>
<p>Setting X to 5.</p>
<p>Setting Y to 15.</p>
<p>X is 5</p>
<p>Y is 15</p>
<p>Analysis</p>
<p>In this example, you first create an instance of Point where X and Y</p>
<p>are both 10 (line 6). Lines 8 and 9 print out those individual values,</p>
<p>and you can see dot notation at work there. Lines 11 through 14</p>
<p>change the values of those variables to 5 and 15, respectively.</p>
<p>Finally, lines 16 and 17 print out the values of X and Y again to show</p>
<p>how they&#8217;ve changed.</p>
<p>Class Variables</p>
<p>Class variables, as you&#8217;ve already learned, are variables that are defined and<br />
stored in the class itself. Their</p>
<p>values, therefore, apply to the class and to all its instances.</p>
<p>With instance variables, each new instance of the class gets a new copy of the<br />
instance variables that class</p>
<p>defines. Each instance can then change the values of those instance variables<br />
without affecting any other</p>
<p>instances. With class variables, there is only one copy of that variable. Every<br />
instance of the class has</p>
<p>access to that variable, but there is only one value. Changing the value of that<br />
variable changes it for all</p>
<p>the instances of that class.</p>
<p>You define class variables by including the static keyword before the variable<br />
itself. You&#8217;ll learn more</p>
<p>about this on Day 6, &#8220;Creating Classes and Applications in Java.&#8221; For example,<br />
take the following partial</p>
<p>class definition:</p>
<p>class FamilyMember {</p>
<p>static String surname = &#8220;Johnson&#8221;;</p>
<p>String name;</p>
<p>int age;</p>
<p>&#8230;</p>
<p>}</p>
<p>Instances of the class FamilyMember each have their own values for name and age.<br />
But the class</p>
<p>variable surname has only one value for all family members. Change surname, and<br />
all the instances of</p>
<p>FamilyMember are affected.</p>
<p>To access class variables, you use the same dot notation as you do with instance<br />
variables. To get or</p>
<p>change the value of the class variable, you can use either the instance or the<br />
name of the class on the left</p>
<p>side of the dot. Both of the lines of output in this example print the same<br />
value:</p>
<p>FamilyMember dad = new FamilyMember();</p>
<p>System.out.println(&#8220;Family&#8217;s surname is: &#8221; + dad.surname);</p>
<p>System.out.println(&#8220;Family&#8217;s surname is: &#8221; + FamilyMember.surname);</p>
<p>Because you can use an instance to change the value of a class variable, it&#8217;s<br />
easy to become confused</p>
<p>about class variables and where their values are coming from (remember that the<br />
value of a class variable</p>
<p>affects all the instances). For this reason, it&#8217;s a good idea to use the name of<br />
the class when you refer to a</p>
<p>class variable-it makes your code easier to read and strange results easier to<br />
debug.</p>
<p>Calling Methods</p>
<p>Calling a method is similar to referring to an object&#8217;s instance variables:<br />
Method calls to objects also use</p>
<p>dot notation. The object itself whose method you&#8217;re calling is on the left side<br />
of the dot; the name of the</p>
<p>method and its arguments are on the right side of the dot:</p>
<p>myObject.methodOne(arg1, arg2, arg3);</p>
<p>Note that all calls to methods must have parentheses after them, even if that<br />
method takes no arguments:</p>
<p>myObject.methodNoArgs();</p>
<p>If the method you&#8217;ve called returns an object that itself has methods, you can<br />
nest methods as you would</p>
<p>variables. This next example calls the getName() method, which is defined in the<br />
object returned by the</p>
<p>getClass() method, which was defined in myObject. Got it?</p>
<p>myObject.getClass().getName();</p>
<p>You can combine nested method calls and instance variable references as well (in<br />
this case you&#8217;re calling</p>
<p>the methodTwo() method, which is defined in the object stored by the var<br />
instance variable, which in</p>
<p>turn is part of the myObject object):</p>
<p>myObject.var.methodTwo(arg1, arg2);</p>
<p>System.out.println(), the method you&#8217;ve been using through the book this far to<br />
print out bits of</p>
<p>text, is a great example of nesting variables and methods. The System class<br />
(part of the java.lang</p>
<p>package) describes system-specific behavior. System.out is a class variable that<br />
contains an instance of</p>
<p>the class PrintStream that points to the standard output of the system.<br />
PrintStream instances have</p>
<p>a println() method that prints a string to that output stream.</p>
<p>Listing 4.3 shows an example of calling some methods defined in the String<br />
class. Strings include</p>
<p>methods for string tests and modification, similar to what you would expect in a<br />
string library in other</p>
<p>languages.</p>
<p>Listing 4.3. Several uses of String methods.</p>
<p>1: class TestString {</p>
<p>2:</p>
<p>3: public static void main(String args[]) {</p>
<p>4: String str = &#8220;Now is the winter of our discontent&#8221;;</p>
<p>5:</p>
<p>6: System.out.println(&#8220;The string is: &#8221; + str);</p>
<p>7: System.out.println(&#8220;Length of this string: &#8220;</p>
<p>8: + str.length());</p>
<p>9: System.out.println(&#8220;The character at position 5: &#8220;</p>
<p>10: + str.charAt(5));</p>
<p>11: System.out.println(&#8220;The substring from 11 to 17: &#8220;</p>
<p>12: + str.substring(11, 17));</p>
<p>13: System.out.println(&#8220;The index of the character d: &#8220;</p>
<p>14: + str.indexOf(&#8216;d&#8217;));</p>
<p>15: System.out.print(&#8220;The index of the beginning of the &#8220;);</p>
<p>16: System.out.println(&#8220;substring \&#8221;winter\&#8221;: &#8220;</p>
<p>17: + str.indexOf(&#8220;winter&#8221;));</p>
<p>18: System.out.println(&#8220;The string in upper case: &#8220;</p>
<p>19: + str.toUpperCase());</p>
<p>20: }</p>
<p>21: }</p>
<p>The string is: Now is the winter of our discontent</p>
<p>Length of this string: 35</p>
<p>The character at position 5: s</p>
<p>The substring from positions 11 to 17: winter</p>
<p>The index of the character d: 25</p>
<p>The index of the beginning of the substring &#8220;winter&#8221;: 11</p>
<p>The string in upper case: NOW IS THE WINTER OF OUR DISCONTENT</p>
<p>Analysis</p>
<p>In line 4, you create a new instance of String by using a string</p>
<p>literal (it&#8217;s easier that way than using new and then putting the</p>
<p>characters in individually). The remainder of the program simply calls</p>
<p>different string methods to do different operations on that string:</p>
<p>Line 6 prints the value of the string we created in line 4: &#8220;Now is the winter<br />
of our</p>
<p>discontent&#8221;.</p>
<p>l</p>
<p>Line 7 calls the length() l method in the new String object. This string has 35<br />
characters.</p>
<p>Line 9 calls the charAt() method, which returns the character at the given<br />
position in the string.</p>
<p>Note that string positions start at 0, so the character at position 5 is s.</p>
<p>l</p>
<p>Line 11 calls the substring() method, which takes two integers indicating a<br />
range and returns</p>
<p>the substring at those starting and ending points. The substring() method can<br />
also be called</p>
<p>with only one argument, which returns the substring from that position to the<br />
end of the string.</p>
<p>l</p>
<p>Line 13 calls the indexOf() method, which returns the position of the first<br />
instance of the given</p>
<p>character (here, &#8216;d&#8217;).</p>
<p>l</p>
<p>Line 15 shows a different use of the indexOf() method, which takes a string<br />
argument and</p>
<p>returns the index of the beginning of that string.</p>
<p>l</p>
<p>l Finally, line 19 uses the toUpperCase() method to return a copy of the string<br />
in all uppercase.</p>
<p>Class Methods</p>
<p>Class methods, like class variables, apply to the class as a whole and not to<br />
its instances. Class methods</p>
<p>are commonly used for general utility methods that may not operate directly on<br />
an instance of that class,</p>
<p>but fit with that class conceptually. For example, the String class contains a<br />
class method called</p>
<p>valueOf(), which can take one of many different types of arguments (integers,<br />
booleans, other objects,</p>
<p>and so on). The valueOf() method then returns a new instance of String<br />
containing the string value</p>
<p>of the argument it was given. This method doesn&#8217;t operate directly on an<br />
existing instance of String, but</p>
<p>getting a string from another object or data type is definitely a String-like<br />
operation, and it makes sense</p>
<p>to define it in the String class.</p>
<p>Class methods can also be useful for gathering general methods together in one<br />
place (the class). For</p>
<p>example, the Math class, defined in the java.lang package, contains a large set<br />
of mathematical</p>
<p>operations as class methods-there are no instances of the class Math, but you<br />
can still use its methods</p>
<p>with numeric or boolean arguments. For example, the class method Math.max()<br />
takes two arguments</p>
<p>and returns the larger of the two. You don&#8217;t need to create a new instance of<br />
Math; just call the method</p>
<p>anywhere you need it, like this:</p>
<p>in biggerOne = Math.max(x, y);</p>
<p>To call a class method, you use dot notation as you do with instance methods. As<br />
with class variables, you</p>
<p>can use either an instance of the class or the class itself on the left site of<br />
the dot. However, for the same</p>
<p>reasons noted in the discussion on class variables, using the name of the class<br />
for class methods makes</p>
<p>your code easier to read. The last two lines in this example produce the same<br />
result (the string &#8220;5&#8243;):</p>
<p>String s, s2;</p>
<p>s = &#8220;foo&#8221;;</p>
<p>s2 = s.valueOf(5);</p>
<p>s2 = String.valueOf(5);</p>
<p>References to Objects</p>
<p>As you work with objects, one important thing going on behind the scenes is the<br />
use of references to those</p>
<p>objects. When you assign objects to variables, or pass objects as arguments to<br />
methods, you are passing</p>
<p>references to those objects, not the objects themselves or copies of those<br />
objects.</p>
<p>An example should make this clearer. Examine Listing 4.4, which shows a simple<br />
example of how</p>
<p>references work.</p>
<p>Listing 4.4. A references example.</p>
<p>1: import java.awt.Point;</p>
<p>2:</p>
<p>3: class ReferencesTest {</p>
<p>4: public static void main (String args[]) {</p>
<p>5: Point pt1, pt2;</p>
<p>6: pt1 = new Point(100, 100);</p>
<p>7: pt2 = pt1;</p>
<p>8:</p>
<p>9: pt1.x = 200;</p>
<p>10: pt1.y = 200;</p>
<p>11: System.out.println(&#8220;Point1: &#8221; + pt1.x + &#8220;, &#8221; + pt1.y);</p>
<p>12: System.out.println(&#8220;Point2: &#8221; + pt2.x + &#8220;, &#8221; + pt2.y);</p>
<p>13: }</p>
<p>14: }</p>
<p>Point1: 200, 200</p>
<p>Point2: 200, 200</p>
<p>Analysis</p>
<p>In the first part of this program, you declare two variables of type</p>
<p>Point (line 5), create a new Point object to pt1 (line 6), and</p>
<p>finally, assign the value of pt1 to pt2 (line 7).</p>
<p>Now, here&#8217;s the challenge. After changing pt1&#8217;s x and y instance variables in<br />
lines 9 and 10, what will</p>
<p>pt2 look like?</p>
<p>As you can see, pt2&#8217;s x and y instance variables were also changed, even though<br />
you never explicitly</p>
<p>changed them. When you assign the value of pt1 to pt2, you actually create a<br />
reference from pt2 to the</p>
<p>same object to which pt1 refers (see Figure 4.1). Change the object that pt2<br />
refers to, and you also</p>
<p>change the object that pt1 points to, because both are references to the same<br />
object.</p>
<p>Figure 4.1 : References to objects.</p>
<p>Note</p>
<p>If you actually do want pt1 and pt2 to point to separate objects, you</p>
<p>should use new Point() for both lines to create separate objects.</p>
<p>The fact that Java uses references becomes particularly important when you pass<br />
arguments to methods.</p>
<p>You&#8217;ll learn more about this later today, but keep these references in mind.</p>
<p>Technical Note</p>
<p>There are no explicit pointers or pointer arithmetic in Java as there are</p>
<p>in C-like languages-just references. However, with these references,</p>
<p>and with Java arrays, you have most of the capabilities that you have</p>
<p>with pointers without the confusion and lurking bugs that explicit</p>
<p>pointers can create.</p>
<p>Casting and Converting Objects and Primitive</p>
<p>Types</p>
<p>Sometimes in your Java programs you may have a value stored somewhere that is<br />
the wrong type for what</p>
<p>you want to do with it. Maybe it&#8217;s an instance of the wrong class, or perhaps<br />
it&#8217;s a float and you want it</p>
<p>to be an int. To convert the value of one type to another, you use casting.<br />
Casting is a programming term</p>
<p>that means, effectively, converting a value or an object from one type to<br />
another. The result of a cast is a</p>
<p>new value or object; casting does not change the original object or value.</p>
<p>New Time</p>
<p>Casting converts the value of an object or primitive type into another</p>
<p>type.</p>
<p>Although the concept of casting is a simple one, the rules for what types in<br />
Java can be converted to what</p>
<p>other types are complicated by the fact that Java has both primitive types (int,<br />
float, boolean), and</p>
<p>object types (String, Point, Window, and so on). There are three forms of casts<br />
and conversions to</p>
<p>talk about in this section:</p>
<p>Casting between primitive types: int to float or float l to double</p>
<p>l Casting between object types: an instance of a class to an instance of another<br />
class</p>
<p>l Converting primitive types to objects and then extracting primitive values<br />
back out of those objects</p>
<p>Casting Primitive Types</p>
<p>Casting between primitive types allows you to &#8220;convert&#8221; the value of one type to<br />
another primitive</p>
<p>type-for example, to assign a number of one type to a variable of another type.<br />
Casting between primitive</p>
<p>types most commonly occurs with the numeric types; boolean values cannot be cast<br />
to any other primitive</p>
<p>type.</p>
<p>Often, if the type you are casting to is &#8220;larger&#8221; than the type of the value<br />
you&#8217;re converting, you may not</p>
<p>have to use an explicit cast. You can often automatically treat a byte or a<br />
character as an int, for</p>
<p>example, or an int as a long, an int as a float, or anything as a double<br />
automatically. In most</p>
<p>cases, because the larger type provides more precision than the smaller, no loss<br />
of information occurs</p>
<p>when the value is cast. The exception is casting integers to floating-point<br />
values; casting an int or a</p>
<p>long to a float or a long to a double may cause some loss of precision.</p>
<p>To convert a large value to smaller type, you must use an explicit cast, because<br />
converting that value may</p>
<p>result in a loss of precision. Explicit casts look like this:</p>
<p>(typename)value</p>
<p>In this form, typename is the name of the type you&#8217;re converting to (for<br />
example: short, int, float,</p>
<p>boolean), and value is an expression that results in the value you want to<br />
convert. So, for example, in</p>
<p>this expression the value of x is divided by the value of y and the result is<br />
cast to an int:</p>
<p>(int) (x / y);</p>
<p>Note that because the precedence of casting is higher than that of arithmetic,<br />
you have to use parentheses</p>
<p>here; otherwise, the value of x would be cast first and then divided by y (which<br />
might very well be a very</p>
<p>different result).</p>
<p>Casting Objects</p>
<p>Instances of classes can also be cast to instances of other classes, with one<br />
restriction: The class of the</p>
<p>object you&#8217;re casting and the class you&#8217;re casting it to must be related by<br />
inheritance; that is, you can cast</p>
<p>an object only to an instance of its class&#8217;s sub- or superclass-not to any<br />
random class.</p>
<p>Analogous to converting a primitive value to a larger type, some objects may not<br />
need to be cast</p>
<p>explicitly. In particular, because subclasses contain all the same information<br />
as their superclass, you can</p>
<p>use an instance of a subclass anywhere a superclass is expected. (Did you just<br />
have to read that sentence</p>
<p>four times before you understood it? I had to rewrite it a whole lot of times<br />
before it became even that</p>
<p>simple. Bear with me, its not that bad. Let&#8217;s try an example.) Suppose you have<br />
a method that takes two</p>
<p>arguments: one of type Object, and one of type Number. You don&#8217;t have to pass<br />
instances of those</p>
<p>particular classes to that method. For the Object argument, you can pass any<br />
subclass of Object (any</p>
<p>object, in other words), and for the Number argument you can pass in any<br />
instance of any subclass of</p>
<p>Number (Integer, Boolean, Float, and so on); you don&#8217;t have to explicitly<br />
convert them first.</p>
<p>Casting downward in the class hierarchy is automatic, but casting upward is not.<br />
Converting an instance of</p>
<p>a subclass to an instance of a superclass loses the information the original<br />
subclass provided and requires</p>
<p>an explicit cast. To cast an object to another class, you use the same casting<br />
operation that you used for</p>
<p>base types:</p>
<p>(classname)object</p>
<p>In this case, classname is the name of the class you want to cast the object to,<br />
and object is a</p>
<p>reference to the object you&#8217;re casting. Note that casting creates a reference to<br />
the old object of the type</p>
<p>classname; the old object still continues to exist as it did before.</p>
<p>Here&#8217;s a (fictitious) example of a cast of an instance of the class GreenApple<br />
to an instance of the class</p>
<p>Apple (where GreenApple is theoretically a subclass of Apple with more<br />
information to define the</p>
<p>apple as green):</p>
<p>GreenApple a;</p>
<p>Apple a2;</p>
<p>a = new GreenApple();</p>
<p>a2 = (Apple) a;</p>
<p>In addition to casting objects to classes, you can also cast objects to<br />
interfaces-but only if that object&#8217;s</p>
<p>class or one of its superclasses actually implements that interface. Casting an<br />
object to an interface means</p>
<p>that you can call one of that interface&#8217;s methods even if that object&#8217;s class<br />
does not actually implement that</p>
<p>interface. You&#8217;ll learn more about interfaces in Week 3.</p>
<p>Converting Primitive Types to Objects and Vice Versa</p>
<p>Now you know how to cast a primitive type to another primitive type and how to<br />
cast between classes.</p>
<p>How can you cast one to the other?</p>
<p>You can&#8217;t! Primitive types and objects are very different things in Java and you<br />
can&#8217;t automatically cast or</p>
<p>convert between the two. However, the java.lang package includes several special<br />
classes that</p>
<p>correspond to each primitive data type: Integer for ints, Float for floats,<br />
Boolean for</p>
<p>booleans, and so on. Note that the class names have an initial capital letter,<br />
and the primitive types are</p>
<p>lowercase. Java treats these names very differently, so don&#8217;t confuse them, or<br />
your methods and variables</p>
<p>won&#8217;t behave the way you expect.</p>
<p>Using class methods defined in these classes, you can create an<br />
object-equivalent for all the primitive</p>
<p>types using new. The following line of code creates an instance of the Integer<br />
class with the value 35:</p>
<p>Integer intObject = new Integer(35);</p>
<p>Once you have actual objects, you can treat those values as objects. Then, when<br />
you want the primitive</p>
<p>values back again, there are methods for that as well-for example, the intValue()<br />
method extracts an</p>
<p>int primitive value from an Integer object:</p>
<p>int theInt = intObject.intValue(); // returns 35</p>
<p>See the Java API documentation for these special classes for specifics on the<br />
methods for converting</p>
<p>primitives to and from objects.</p>
<p>Note</p>
<p>In Java 1.0 there are special type classes for Boolean,</p>
<p>Character, Double, Float, Integer, and Long. Java 1.1</p>
<p>adds classes for Byte and Short, as well as a special wrapper class</p>
<p>for Void. The latter classes are used primarily for object reflection.</p>
<p>Odds and Ends</p>
<p>This section is a catchall for other information about working with objects,<br />
particularly the following:</p>
<p>l Comparing objects</p>
<p>l Finding out the class of any given object</p>
<p>l Testing to see whether an object is an instance of a given class</p>
<p>Comparing Objects</p>
<p>Yesterday you learned about operators for comparing values: equals, not equals,<br />
less than, and so on. Most</p>
<p>of these operators work only on primitive types, not on objects. If you try to<br />
use other values as operands,</p>
<p>the Java compiler produces errors.</p>
<p>The exception to this rule is with the operators for equality: == (equal) and !=<br />
(not equal). These</p>
<p>operators, when used with objects, test whether the two operands refer to<br />
exactly the same object in</p>
<p>memory.</p>
<p>What should you do if you want to be able to compare instances of your class and<br />
have meaningful</p>
<p>results? You have to implement special methods in your class, and you have to<br />
call those methods using</p>
<p>those method names.</p>
<p>Technical Note</p>
<p>Java does not have the concept of operator overloading-that is, the</p>
<p>ability to redefine the behavior of the built-in operators using methods</p>
<p>in your own classes. The built-in operators remain defined only for</p>
<p>numbers.</p>
<p>A good example of this is the String class. It is possible to have two strings,<br />
two independent objects in</p>
<p>memory with the same values-that is, the same characters in the same order.<br />
According to the == operator,</p>
<p>however, those two String objects will not be equal, because, although their<br />
contents are the same, they</p>
<p>are not the same object.</p>
<p>The String class, therefore, defines a method called equals() that tests each<br />
character in the string</p>
<p>and returns true if the two strings have the same values. Listing 4.5<br />
illustrates this.</p>
<p>Listing 4.5. A test of string equality.</p>
<p>1: class EqualsTest {</p>
<p>2: public static void main(String args[]) {</p>
<p>3: String str1, str2;</p>
<p>4: str1 = &#8220;she sells sea shells by the sea shore.&#8221;;</p>
<p>5: str2 = str1;</p>
<p>6:</p>
<p>7: System.out.println(&#8220;String1: &#8221; + str1);</p>
<p>8: System.out.println(&#8220;String2: &#8221; + str2);</p>
<p>9: System.out.println(&#8220;Same object? &#8221; + (str1 == str2));</p>
<p>10:</p>
<p>11: str2 = new String(str1);</p>
<p>12:</p>
<p>13: System.out.println(&#8220;String1: &#8221; + str1);</p>
<p>14: System.out.println(&#8220;String2: &#8221; + str2);</p>
<p>15: System.out.println(&#8220;Same object? &#8221; + (str1 == str2));</p>
<p>16: System.out.println(&#8220;Same value? &#8221; + str1.equals(str2));</p>
<p>17: }</p>
<p>18: }</p>
<p>String1: she sells sea shells by the sea shore.</p>
<p>String2: she sells sea shells by the sea shore.</p>
<p>Same object? true</p>
<p>String1: she sells sea shells by the sea shore.</p>
<p>String2: she sells sea shells by the sea shore.</p>
<p>Same object? false</p>
<p>Same value? true</p>
<p>Analysis</p>
<p>The first part of this program (lines 4 through 6) declares two</p>
<p>variables (str1 and str2) assigns the literal she sells sea</p>
<p>shells by the sea shore. to str1, and then assigns that</p>
<p>value to str2. As you learned earlier when we talked about object</p>
<p>references, now str1 and str2 point to the same object, and the</p>
<p>equality test at line 10 proves that.</p>
<p>In the second part, you create a new string object with the same value as str1<br />
and assign str2 to that</p>
<p>new string object. Now you have two different string objects in str1 and str2,<br />
both with the same</p>
<p>value. Testing them to see whether they&#8217;re the same object by using the ==<br />
operator (line 16) returns the</p>
<p>expected answer (false-they are not the same object in memory), as does testing<br />
them using the</p>
<p>equals() method (line 17) (true-they have the same values).</p>
<p>Technical Note</p>
<p>Why can&#8217;t you just use another literal when you change str2, rather</p>
<p>than using new? String literals are optimized in Java-if you create a</p>
<p>string using a literal, and then use another literal with the same</p>
<p>characters, Java knows enough to give you the first String object</p>
<p>back. Both strings are the same objects-to create two separate objects</p>
<p>you have to go out of your way.</p>
<p>Determining the Class of an Object</p>
<p>Want to find out the class of an object? Here&#8217;s the way to do it for an object<br />
assigned to the variable obj:</p>
<p>String name = obj.getClass().getName();</p>
<p>What does this do? The getClass() method is defined in the Object class, and as<br />
such is available</p>
<p>for all objects. The result of that method is a Class object (where Class is<br />
itself a class), which has a</p>
<p>method called getName(). getName() returns a string representing the name of the<br />
class.</p>
<p>Another test that might be useful to you is the instanceof operator. instanceof<br />
has two operands:</p>
<p>an object on the left and the name of a class on the right. The expression<br />
returns true or false based on</p>
<p>whether the object is an instance of the named class or any of that class&#8217;s<br />
subclasses:</p>
<p>&#8220;foo&#8221; instanceof String // true</p>
<p>Point pt = new Point(10, 10);</p>
<p>pt instanceof String // false</p>
<p>The instanceof operator can also be used for interfaces; if an object implements<br />
an interface, the</p>
<p>instanceof operator with that interface name on the right side returns true.<br />
You&#8217;ll learn all about</p>
<p>interfaces in Week 3.</p>
<p>Class and Object Reflection (Java 1.1)</p>
<p>Reflection, also known as introspection, is a somewhat lofty term to describe<br />
the ability to &#8220;look inside&#8221; a</p>
<p>class or an object and get information about that object&#8217;s variables and methods<br />
as well as actually set and</p>
<p>get the values of those variables and to call methods. Object reflection is<br />
useful for tools such as class</p>
<p>browsers or debuggers, where getting at the information of an object on-the-fly<br />
allows you to explore what</p>
<p>that object can do, or for component-based programs such as Java Beans, where<br />
the ability for one object</p>
<p>to query another object about what it can do (and then ask it to do something)<br />
is useful to building larger</p>
<p>applications.</p>
<p>The classes that support reflection of Java classes and objects will be part of<br />
the core Java 1.1 API (they</p>
<p>are not available in the 1.0.2 version of the JDK). A new package,<br />
java.lang.reflect, will contain</p>
<p>new classes to support reflection, which include the following:</p>
<p>l Field, for managing and finding out information about class and instance<br />
variables</p>
<p>l Method, for managing class and instance methods</p>
<p>Constructor, for managing the special methods for creating new instances of<br />
classes (you&#8217;ll</p>
<p>learn more about constructors on Day 7)</p>
<p>l</p>
<p>l Array, for managing arrays</p>
<p>Modifier, for decoding modifier information about classes, variables and methods<br />
(more about</p>
<p>modifiers on Day 15, &#8220;Modifiers, Access Control, and Class Design&#8221;)</p>
<p>l</p>
<p>In addition, there will be a number of new methods available in the Class class<br />
to help tie together the</p>
<p>various reflection classes.</p>
<p>You can find out more about the new reflection classes and methods from</p>
<p>http://java.sun.com/products/JDK/1.1/designspecs/reflection/.</p>
<p>The Java Class Library</p>
<p>To finish up today, let&#8217;s look at the Java class library. Actually, you&#8217;ve had<br />
some experience with some of</p>
<p>the Java classes already, so they shouldn&#8217;t seem that strange.</p>
<p>The Java class library provides the set of classes that are guaranteed to be<br />
available in any commercial</p>
<p>Java environment (for example, in any Java development environment or in<br />
browsers such as Netscape).</p>
<p>Those classes are in the java package and include all the classes you&#8217;ve seen so<br />
far in this book, plus a</p>
<p>whole lot more classes you&#8217;ll learn about later on in this book (and more you<br />
may not learn about at all).</p>
<p>The Java Developer&#8217;s Kit comes with documentation for all of the Java class<br />
library, which includes</p>
<p>descriptions of each class&#8217;s instance variables, methods, constructors,<br />
interfaces, and so on. You can get to</p>
<p>this documentation (called the Java Application Programmer&#8217;s Interface, or API)<br />
via the Web at</p>
<p>http://java.sun.com:80/products/JDK/CurrentRelease/api/packages.html. A</p>
<p>shorter summary of the Java API is in appendix C as well. Exploring the Java<br />
class library and its methods</p>
<p>and instance variables is a great way to figure out what Java can and cannot do,<br />
as well as how it can</p>
<p>become a starting point for your own development.</p>
<p>Here are the class packages that are part of the Java class library:</p>
<p>java.lang-Classes that apply to the language itself, including the Object class,<br />
the String</p>
<p>class, and the System class. It also contains the special classes for the<br />
primitive types (Integer,</p>
<p>Character, Float, and so on). You&#8217;ll get at least a glance at most of the<br />
classes in this package</p>
<p>in this first week.</p>
<p>l</p>
<p>java.util-Utility classes, such as Date, as well as simple collection classes,<br />
such as Vector</p>
<p>and Hashtable. You&#8217;ll learn more about these classes in the Bonus Week.</p>
<p>l</p>
<p>java.io-Input and output classes for writing to and reading from streams (such<br />
as standard input</p>
<p>and output) and for handling files. Day 19, &#8220;Streams and I/O,&#8221; describes the<br />
classes in this package.</p>
<p>l</p>
<p>java.net-Classes for networking support, including Socket and URL (a class to<br />
represent</p>
<p>references to documents on the World Wide Web). You&#8217;ll learn a little about<br />
networking on Day 14,</p>
<p>&#8220;Windows, Networking, and Other Tidbits,&#8221; and then on Day 26, &#8220;Client/Server<br />
Networking in</p>
<p>Java.&#8221;</p>
<p>l</p>
<p>java.awt-This is the Abstract Windowing Toolkit. It contains classes to<br />
implement graphical</p>
<p>user interface features, including classes for Window, Menu, Button, Font,<br />
CheckBox, and so</p>
<p>on. It also includes mechanisms for managing system events and for processing<br />
images (in the</p>
<p>java.awt.Image package). You&#8217;ll learn all about the awt in Week 2.</p>
<p>l</p>
<p>l java.applet-Classes to implement Java applets.</p>
<p>In addition to the Java classes, your development environment may also include<br />
additional classes that</p>
<p>provide other utilities or functionality. Although these classes may be useful,<br />
because they are not part of</p>
<p>the standard Java library, they may not be available to other people trying to<br />
run your Java program unless</p>
<p>you explicitly include those classes with your program. This is particularly<br />
important for applets, because</p>
<p>applets are expected to be able to run on any platform, using any Java-enabled<br />
browser. Only classes</p>
<p>inside the java package are guaranteed to be available on all browsers and Java<br />
environments.</p>
<p>Summary</p>
<p>Objects, objects everywhere. Today, you&#8217;ve learned all about how to deal with<br />
objects: how to create</p>
<p>them, how to find out and change the values of their variables, and how to call<br />
their methods. You have</p>
<p>also learned how to copy and compare them and how to convert them into other<br />
objects. Finally, you have</p>
<p>learned a bit about the Java class libraries-which give you a whole slew of<br />
classes to play with in your</p>
<p>own programs.</p>
<p>You now have the fundamentals of how to deal with most simple things in the Java<br />
language. All you</p>
<p>have left are arrays, conditionals, and loops, which you&#8217;ll learn about<br />
tomorrow. Then you&#8217;ll learn how to</p>
<p>define and use classes in Java applications on Day 6, and launch directly into<br />
applets next week. With just</p>
<p>about everything you do in your Java programs, you&#8217;ll always come back to<br />
objects.</p>
<p>Q&amp;A</p>
<p>Q: I&#8217;m confused about the differences between objects and the primitive data<br />
types, such as</p>
<p>int and boolean.</p>
<p>A: The primitive types in the language (byte, short, int, long, float, double,<br />
boolean,</p>
<p>and char) represent the smallest things in the language. They are not objects,<br />
although in many</p>
<p>ways they can be handled like objects-they can be assigned to variables and<br />
passed in and out of</p>
<p>methods. Most of the operations that work exclusively on objects, however, will<br />
not work with</p>
<p>primitive types.</p>
<p>Objects are instances of classes and, as such, are usually much more complex<br />
data types than</p>
<p>simple numbers and characters, often containing numbers and characters as<br />
instance or class</p>
<p>variables.</p>
<p>Q: No pointers in Java? If you don&#8217;t have pointers, how are you supposed to do<br />
something like</p>
<p>linked lists, where you have a pointer from one nose to another so you can<br />
traverse them?</p>
<p>A: Java doesn&#8217;t have no pointers at all; it has no explicit pointers. Object<br />
references are, effectively,</p>
<p>pointers. So to create something like a linked list, you would create a class<br />
called Node, which</p>
<p>would have an instance variable also of type Node. Then to link together node<br />
objects all you</p>
<p>need to do is assign a node object to the instance variable of the object just<br />
before it in the list.</p>
<p>Because object references are pointers, linked lists set up this way will behave<br />
as you would</p>
<p>expect them to.</p>
<p>Q: In the section on calling methods, you had examples of calling a method with<br />
a different</p>
<p>number of arguments each time-and it gave a different kind of result. How is<br />
that possible?</p>
<p>A: That&#8217;s called method overloading. Overloading means that the same method can<br />
have different</p>
<p>behavior based on the arguments it&#8217;s called with-and the number and type of<br />
arguments can vary.</p>
<p>When you define methods in your own classes, you define separate method<br />
signatures with</p>
<p>different sets of arguments and different definitions. When a method is called,<br />
Java figures out</p>
<p>which definition to execute based on the number and type of arguments with which<br />
you called it.</p>
<p>You&#8217;ll learn all about this on Day 6.</p>
<p>Q: No operator overloading in Java? Why not? I thought Java was based on C++,<br />
and C++ has</p>
<p>operator overloading.</p>
<p>A: Java was indeed based on C++, but it was also designed to be simple, so many<br />
of C++&#8217;s features</p>
<p>have been removed. The argument against operator overloading is that because the<br />
operator can</p>
<p>be defined to mean anything; it makes it very difficult to figure out what any<br />
given operator is</p>
<p>doing at any one time. This can result in entirely unreadable code. When you use<br />
a method, you</p>
<p>know it can mean many things to many classes, but when you use an operator you<br />
would like to</p>
<p>know that it always means the same thing. Given the potential for abuse, the<br />
designers of Java felt</p>
<p>it was one of the C++ features that was best left out.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/swebsolution.wordpress.com/25/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/swebsolution.wordpress.com/25/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/swebsolution.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/swebsolution.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/swebsolution.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/swebsolution.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/swebsolution.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/swebsolution.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/swebsolution.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/swebsolution.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/swebsolution.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/swebsolution.wordpress.com/25/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=25&subd=swebsolution&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://swebsolution.wordpress.com/2008/01/08/java-help-java-tutorials-java-programming-java-tricks-4/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4fc1b8adaf945b9ecf45239af6e622af?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Prakash Sherawat</media:title>
		</media:content>
	</item>
		<item>
		<title>Java Help, Java Tutorials, Java Programming, Java Tricks</title>
		<link>http://swebsolution.wordpress.com/2008/01/08/java-help-java-tutorials-java-programming-java-tricks-3/</link>
		<comments>http://swebsolution.wordpress.com/2008/01/08/java-help-java-tutorials-java-programming-java-tricks-3/#comments</comments>
		<pubDate>Tue, 08 Jan 2008 08:48:00 +0000</pubDate>
		<dc:creator>Prakash Sherawat</dc:creator>
				<category><![CDATA[Java Help]]></category>

		<guid isPermaLink="false">http://swebsolution.wordpress.com/2008/01/08/java-help-java-tutorials-java-programming-java-tricks-3/</guid>
		<description><![CDATA[
Java Help, Java Tutorials, Java Programming, Java Tricks
Lesson Three
Java Basics
CONTENTS
Statements and Expressions
Variables and Data Types
Declaring Variables
Notes on Variable Names
Variable Types
Assigning Values to Variables
Comments
Literals
Number Literals
Boolean Literals
Character Literals
String Literals
Expressions and Operators
Arithmetic
More About Assignment
Incrementing and Decrementing
Comparisons
Logical Operators
Bitwise Operators
Operator Precedence
String Arithmetic
Summary
Q&#38;A
Already this week you&#8217;ve learned about Java programming in very broad terms-what
a Java program andan executable look like, and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=24&subd=swebsolution&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://swebsolution.blogspot.com/2008/01/java-help-java-tutorials-java_04.html"><br />
Java Help, Java Tutorials, Java Programming, Java Tricks</a></p>
<p>Lesson Three</p>
<p>Java Basics</p>
<p>CONTENTS</p>
<p>Statements and Expressions</p>
<p>Variables and Data Types</p>
<p>Declaring Variables</p>
<p>Notes on Variable Names</p>
<p>Variable Types</p>
<p>Assigning Values to Variables</p>
<p>Comments</p>
<p>Literals</p>
<p>Number Literals</p>
<p>Boolean Literals</p>
<p>Character Literals</p>
<p>String Literals</p>
<p>Expressions and Operators</p>
<p>Arithmetic</p>
<p>More About Assignment</p>
<p>Incrementing and Decrementing</p>
<p>Comparisons</p>
<p>Logical Operators</p>
<p>Bitwise Operators</p>
<p>Operator Precedence</p>
<p>String Arithmetic</p>
<p>Summary</p>
<p>Q&amp;A</p>
<p>Already this week you&#8217;ve learned about Java programming in very broad terms-what<br />
a Java program andan executable look like, and how to create simple classes. For<br />
the remainder of this week, you&#8217;re going to get down to details and deal with<br />
the specifics of what the Java language looks like.</p>
<p>Today you won&#8217;t define any classes or objects or worry about how any of them<br />
communicate inside a</p>
<p>Java program. Rather, you&#8217;ll draw closer and examine simple Java statements-the<br />
basic things you can do</p>
<p>in Java within a method definition such as main().</p>
<p>Today you&#8217;ll learn about the following:</p>
<p>Java statements and expressions</p>
<p>Variables and data types</p>
<p>Comments</p>
<p>Literals</p>
<p>Arithmetic</p>
<p>Comparisons</p>
<p>Logical operators</p>
<p>Technical Note</p>
<p>Java looks a lot like C++, and-by extension-like C. Much of the</p>
<p>syntax will be very familiar to you if you are used to working in these</p>
<p>languages. If you are an experienced C or C++ programmer, you may</p>
<p>want to pay special attention to the technical notes (such as this one),</p>
<p>because they provide information about the specific differences</p>
<p>between these and other traditional languages and Java.</p>
<p>Statements and Expressions</p>
<p>A statement indicates the simplest tasks you can accomplish in Java; a statement<br />
forms a single Java</p>
<p>operation. All the following are simple Java statements:</p>
<p>int i = 1;</p>
<p>import java.awt.Font;</p>
<p>System.out.println(&#8220;This motorcycle is a &#8220;</p>
<p>+ color + &#8221; &#8221; + make);</p>
<p>m.engineState = true;</p>
<p>Statements sometimes return values-for example, when you add two numbers<br />
together or test to see</p>
<p>whether one value is equal to another. These kind of statements are called<br />
expressions. You&#8217;ll learn about</p>
<p>these later today.</p>
<p>White space in Java statements, as with C, is unimportant. A statement can be<br />
contained on a single line</p>
<p>or on multiple lines, and the Java compiler will be able to read it just fine.<br />
The most important thing to</p>
<p>remember about Java statements is that each one ends with a semicolon (;).<br />
Forget the semicolon, and</p>
<p>your Java program won&#8217;t compile.</p>
<p>Java also has compound statements, or blocks, which can be placed wherever a<br />
single statement can.</p>
<p>Block statements are surrounded by braces ({}). You&#8217;ll learn more about blocks<br />
on Day 5, &#8220;Arrays,</p>
<p>Conditionals, and Loops.&#8221;</p>
<p>Variables and Data Types</p>
<p>Variables are locations in memory in which values can be stored. Each one has a<br />
name, a type, and a</p>
<p>value. Before you can use a variable, you have to declare it. After it is<br />
declared, you can then assign</p>
<p>values to it (you can also declare and assign a value to a variable at the same<br />
time, as you&#8217;ll learn in this</p>
<p>section).</p>
<p>Java actually has three kinds of variables: instance variables, class variables,<br />
and local variables.</p>
<p>Instance variables, as you learned yesterday, are used to define the attributes<br />
of a particular object. Class</p>
<p>variables are similar to instance variables, except their values apply to all<br />
that class&#8217;s instances (and to the</p>
<p>class itself) rather than having different values for each object.</p>
<p>Local variables are declared and used inside method definitions, for example,<br />
for index counters in loops,</p>
<p>as temporary variables, or to hold values that you need only inside the method<br />
definition itself. They can</p>
<p>also be used inside blocks, which you&#8217;ll learn about on Day 5. Once the method<br />
(or block) finishes</p>
<p>executing, the variable definition and its value cease to exist. Use local<br />
variables to store information</p>
<p>needed by a single method and instance variables to store information needed by<br />
multiple methods in the</p>
<p>object.</p>
<p>Although all three kinds of variables are declared in much the same ways, class<br />
and instance variables</p>
<p>are accessed and assigned in slightly different ways from local variables. Today<br />
you&#8217;ll focus on variables</p>
<p>as used within method definitions; tomorrow you&#8217;ll learn how to deal with<br />
instance and class variables.</p>
<p>Note Unlike other languages, Java does not have global variables-that is,</p>
<p>variables that are global to all parts of a program. Instance and class</p>
<p>variables can be used to communicate global information between</p>
<p>and among objects. Remember that Java is an object-oriented</p>
<p>language, so you should think in terms of objects and how they</p>
<p>interact, rather than in terms of programs.</p>
<p>Declaring Variables</p>
<p>To use any variable in a Java program, you must first declare it. Variable<br />
declarations consist of a type</p>
<p>and a variable name:</p>
<p>int myAge;</p>
<p>String myName;</p>
<p>boolean isTired;</p>
<p>Variable definitions can go anywhere in a method definition (that is, anywhere a<br />
regular Java statement</p>
<p>can go), although they are most commonly declared at the beginning of the<br />
definition before they are</p>
<p>used:</p>
<p>public static void main (String args[]) {</p>
<p>int count;</p>
<p>String title;</p>
<p>boolean isAsleep;</p>
<p>&#8230;</p>
<p>}</p>
<p>You can string together variable names with the same type on one line:</p>
<p>int x, y, z;</p>
<p>String firstName, LastName;</p>
<p>You can also give each variable an initial value when you declare it:</p>
<p>int myAge, mySize, numShoes = 28;</p>
<p>String myName = &#8220;Laura&#8221;;</p>
<p>boolean isTired = true;</p>
<p>int a = 4, b = 5, c = 6;</p>
<p>If there are multiple variables on the same line with only one initializer (as<br />
in the first of the previous</p>
<p>examples), the initial value applies to only the last variable in a declaration.<br />
You can also group</p>
<p>individual variables and initializers on the same line using commas, as with the<br />
last example.</p>
<p>Local variables must be given values before they can be used (your Java program<br />
will not compile if you</p>
<p>try to use an unassigned local variable). For this reason, it&#8217;s a good idea<br />
always to give local variables</p>
<p>initial values. Instance and class variable definitions do not have this<br />
restriction. (Their initial value</p>
<p>depends on the type of the variable: null for instances of classes, 0 for<br />
numeric variables, &#8221; for</p>
<p>characters, and false for booleans.)</p>
<p>Notes on Variable Names</p>
<p>Variable names in Java can start with a letter, an underscore (_), or a dollar<br />
sign ($). They cannot start</p>
<p>with a number. After the first character, your variable names can include any<br />
letter or number. Symbols,</p>
<p>such as %, *, @, and so on, are often reserved for operators in Java, so be<br />
careful when using symbols in</p>
<p>variable names.</p>
<p>In addition, the Java language uses the Unicode character set. Unicode is a<br />
character set definition that</p>
<p>not only offers characters in the standard ASCII character set, but also<br />
includes several thousand other</p>
<p>characters for representing most international alphabets. This means that you<br />
can use accented characters</p>
<p>and other glyphs as legal characters in variable names, as long as they have a<br />
Unicode character number</p>
<p>above 00C0.</p>
<p>Warning</p>
<p>The Unicode specification is a two-volume set of lists of thousands of</p>
<p>characters. If you don&#8217;t understand Unicode, or don&#8217;t think you have a</p>
<p>use for it, it&#8217;s safest just to use plain numbers and letters in your</p>
<p>variable names. You&#8217;ll learn a little more about Unicode later.</p>
<p>Finally, note that the Java language is case sensitive, which means that<br />
uppercase letters are different</p>
<p>from lowercase letters. This means that the variable X is different from the<br />
variable x, and a rose is not</p>
<p>a Rose is not a ROSE. Keep this in mind as you write your own Java programs and<br />
as you read Java</p>
<p>code other people have written.</p>
<p>By convention, Java variables have meaningful names, often made up of several<br />
words combined. The</p>
<p>first word is lowercase, but all following words have an initial uppercase<br />
letter:</p>
<p>Button theButton;</p>
<p>long reallyBigNumber;</p>
<p>boolean currentWeatherStateOfPlanetXShortVersion;</p>
<p>Variable Types</p>
<p>In addition to the variable name, each variable declaration must have a type,<br />
which defines what values</p>
<p>that variable can hold. The variable type can be one of three things:</p>
<p>One of the eight primitive data types</p>
<p>The name of a class or interface</p>
<p>An array</p>
<p>You&#8217;ll learn about how to declare and use array variables on Day 5; this lesson<br />
focuses on the primitive</p>
<p>and class types.</p>
<p>Primitive Types</p>
<p>The eight primitive data types handle common types for integers, floating-point<br />
numbers, characters, and</p>
<p>boolean values (true or false). They&#8217;re called primitive because they&#8217;re built<br />
into the system and are</p>
<p>not actual objects, which makes them more efficient to use. Note that these data<br />
types are</p>
<p>machine-independent, which means that you can rely on their sizes and<br />
characteristics to be consistent</p>
<p>across your Java programs.</p>
<p>There are four Java integer types, each with a different range of values (as<br />
listed in Table 3.1). All are</p>
<p>signed, which means they can hold either positive or negative numbers. Which<br />
type you choose for your</p>
<p>variables depends on the range of values you expect that variable to hold; if a<br />
value becomes too big for</p>
<p>the variable type, it is silently truncated.</p>
<p>Table 3.1. Integer types.</p>
<p>Type Size Range</p>
<p>byte 8 bits -128 to 127</p>
<p>short 16 bits -32,768 to 32,767</p>
<p>int 32 bits -2,147,483,648 to 2,147,483,647</p>
<p>long 64 bits -9,223,372,036,854,775,808 to</p>
<p>9,223,372,036,854,775,807</p>
<p>Floating-point numbers are used for numbers with a decimal part. Java<br />
floating-point numbers are</p>
<p>compliant with IEEE 754 (an international standard for defining floating-point<br />
numbers and arithmetic).</p>
<p>There are two floating-point types: float (32 bits, single precision) and double<br />
(64 bits, double</p>
<p>precision).</p>
<p>The char type is used for individual characters. Because Java uses the Unicode<br />
character set, the char</p>
<p>type has 16 bits of precision, unsigned.</p>
<p>Finally, the boolean type can have one of two values, true or false. Note that<br />
unlike in other C-like</p>
<p>languages, boolean is not a number, nor can it be treated as one. All tests of<br />
boolean variables should</p>
<p>test for true or false.</p>
<p>Note that all the primitive types are in lowercase. Be careful when you use them<br />
in your programs that</p>
<p>you do use the lowercase, because there are also classes with the same names<br />
(and an initial capital</p>
<p>letter) that have different behavior-so, for example, the primitive type boolean<br />
is different from the</p>
<p>Boolean class. You&#8217;ll learn more about these special classes and what they&#8217;re<br />
used for on Day 4,</p>
<p>&#8220;Working with Objects.&#8221;</p>
<p>Class Types</p>
<p>In addition to the eight primitive data types, variables in Java can also be<br />
declared to hold an instance of</p>
<p>a particular class:</p>
<p>String LastName;</p>
<p>Font basicFont;</p>
<p>OvalShape myOval;</p>
<p>Each of these variables can hold instances of the named class or of any of its<br />
subclasses. The latter is</p>
<p>useful when you want a variable to be able to hold different instances of<br />
related classes. For example,</p>
<p>let&#8217;s say you had a set of fruit classes-Apple, Pear, Strawberry, and so on- all<br />
of which inherited</p>
<p>from the general class Fruit. By declaring a variable of type Fruit, that<br />
variable can then hold</p>
<p>instances of any of the Fruit classes. Declaring a variable of type Object means<br />
that variable can</p>
<p>hold any object.</p>
<p>Technical Note</p>
<p>Java does not have a typedef statement (as in C and C++). To</p>
<p>declare new types in Java, you declare a new class; then variables can</p>
<p>be declared to be of that class&#8217;s type.</p>
<p>Assigning Values to Variables</p>
<p>Once a variable has been declared, you can assign a value to that variable by<br />
using the assignment</p>
<p>operator =, like this:</p>
<p>size = 14;</p>
<p>tooMuchCaffiene = true;</p>
<p>Comments</p>
<p>Java has three kinds of comments: two for regular comments in source code and<br />
one for the special</p>
<p>documentation system javadoc.</p>
<p>The symbols /* and */ surround multiline comments, as in C or C++. All text<br />
between the two</p>
<p>delimiters is ignored:</p>
<p>/* I don&#8217;t know how I wrote this next part; I was working</p>
<p>really late one night and it just sort of appeared. I</p>
<p>suspect the code elves did it for me. It might be wise</p>
<p>not to try and change it.</p>
<p>*/</p>
<p>These comments cannot be nested; that is, you cannot have a comment inside a<br />
comment.</p>
<p>Double-slashes (//) can be used for a single line of comment. All the text up to<br />
the end of the line is</p>
<p>ignored:</p>
<p>int vices = 7; // are there really only 7 vices?</p>
<p>The final type of comment begins with /** and ends with */. The contents of<br />
these special comments</p>
<p>are used by the javadoc system, but are otherwise used identically to the first<br />
type of comment.</p>
<p>javadoc is used to generate API documentation from the code. You&#8217;ll learn more<br />
about javadoc on</p>
<p>Day 22, &#8220;Java Programming Tools.&#8221;</p>
<p>Literals</p>
<p>Literal is a programming language term that essentially means that what you type<br />
is what you get. For</p>
<p>example, if you type 4 in a Java program, you automatically get an integer with<br />
the value 4. If you type</p>
<p>&#8216;a&#8217;, you get a character with the value a. Literals are used to indicate simple<br />
values in your Java</p>
<p>programs.</p>
<p>New Term</p>
<p>A literal is a simple value where &#8220;what you type is what you get.&#8221;</p>
<p>Numbers, characters, and strings are all examples of literals.</p>
<p>Literals may seem intuitive most of the time, but there are some special cases<br />
of literals in Java for</p>
<p>different kinds of numbers, characters, strings, and boolean values.</p>
<p>Number Literals</p>
<p>There are several integer literals. 4, for example, is a decimal integer literal<br />
of type int (although you</p>
<p>can assign it to a variable of type byte or short because it&#8217;s small enough to<br />
fit into those types). A</p>
<p>decimal integer literal larger than an int is automatically of type long. You<br />
also can force a smaller</p>
<p>number to a long by appending an L or l to that number (for example, 4L is a<br />
long integer of value</p>
<p>4). Negative integers are preceded by a minus sign-for example, -45.</p>
<p>Integers can also be expressed as octal or hexadecimal: A leading 0 indicates<br />
that a number is octal-for</p>
<p>example, 0777 or 0004. A leading 0x (or 0X) means that it is in hex (0xFF,<br />
0XAf45). Hexadecimal</p>
<p>numbers can contain regular digits (0-9) or upper- or lowercase hex digits (a-f<br />
or A-F).</p>
<p>Floating-point literals usually have two parts, the integer part and the decimal<br />
part-for example,</p>
<p>5.77777. A floating-point literal results in a floating-point number of type<br />
double, regardless of the</p>
<p>precision of the number. You can force the number to the type float by appending<br />
the letter f (or F) to</p>
<p>that number-for example, 2.56F.</p>
<p>You can use exponents in floating-point literals using the letter e or E<br />
followed by the exponent (which</p>
<p>can be a negative number): 10e45 or .36E-2.</p>
<p>Boolean Literals</p>
<p>Boolean literals consist of the keywords true and false. These keywords can be<br />
used anywhere you</p>
<p>need a test or as the only possible values for boolean variables.</p>
<p>Character Literals</p>
<p>Character literals are expressed by a single character surrounded by single<br />
quotes: &#8216;a&#8217;, &#8216;#&#8217;, &#8216;3&#8242;, and</p>
<p>so on. Characters are stored as 16-bit Unicode characters. Table 3.2 lists the<br />
special codes that can</p>
<p>represent nonprintable characters, as well as characters from the Unicode<br />
character set. The letter d in the</p>
<p>octal, hex, and Unicode escapes represents a number or a hexadecimal digit (a-f<br />
or A-F).</p>
<p>Table 3.2. Character escape codes.</p>
<p>Escape Meaning</p>
<p>\n Newline</p>
<p>\t Tab</p>
<p>\b Backspace</p>
<p>\r Carriage return</p>
<p>\f Formfeed</p>
<p>\\ Backslash</p>
<p>\&#8217; Single quote</p>
<p>\&#8221; Double quote</p>
<p>\ddd Octal</p>
<p>\xdd Hexadecimal</p>
<p>\udddd Unicode character</p>
<p>Technical Note</p>
<p>C and C++ programmers should note that Java does not include</p>
<p>character codes for \a (bell) or \v (vertical tab).</p>
<p>String Literals</p>
<p>A combination of characters is a string. Strings in Java are instances of the<br />
class String. Strings are not</p>
<p>simply arrays of characters as they are in C or C++, although they do have many<br />
array-like</p>
<p>characteristics (for example, you can test their length, and access and change<br />
individual characters).</p>
<p>Because string objects are real objects in Java, they have methods that enable<br />
you to combine, test, and</p>
<p>modify strings very easily.</p>
<p>String literals consist of a series of characters inside double quotes:</p>
<p>&#8220;Hi, I&#8217;m a string literal.&#8221;</p>
<p>&#8220;&#8221; //an empty string</p>
<p>Strings can contain character constants such as newline, tab, and Unicode<br />
characters:</p>
<p>&#8220;A string with a \t tab in it&#8221;</p>
<p>&#8220;Nested strings are \&#8221;strings inside of\&#8221; other strings&#8221;</p>
<p>&#8220;This string brought to you by Java\u2122&#8243;</p>
<p>In the last example, the Unicode code sequence for \u2122 produces a trademark<br />
symbol ( ).</p>
<p>Note</p>
<p>Just because you can represent a character using a Unicode escape</p>
<p>does not mean your computer can display that character-the computer</p>
<p>or operating system you are running may not support Unicode, or the</p>
<p>font you&#8217;re using may not have a glyph (picture) for that character.</p>
<p>All that Unicode escapes in Java provide is a way to encode Unicode</p>
<p>characters for systems that support Unicode.</p>
<p>Java 1.1 will provide better capabilities for the display of Unicode</p>
<p>characters and for handling international character sets.</p>
<p>When you use a string literal in your Java program, Java automatically creates<br />
an instance of the class</p>
<p>String for you with the value you give it. Strings are unusual in this respect;<br />
the other literals do not</p>
<p>behave in this way (none of the primitive data types are actual objects), and<br />
usually creating a new object</p>
<p>involves explicitly creating a new instance of a class. You&#8217;ll learn more about<br />
strings, the String class,</p>
<p>and the things you can do with strings later today and tomorrow.</p>
<p>Expressions and Operators</p>
<p>Expressions are the simplest form of statement in Java that actually<br />
accomplishes something: All</p>
<p>expressions, when evaluated, return a value (other statements don&#8217;t necessarily<br />
do so). Arithmetic and</p>
<p>tests for equality and magnitude are common examples of expressions. Because<br />
they return a value, you</p>
<p>can assign that result to a variable or test that value in other Java<br />
statements.</p>
<p>Most of the expressions in Java use operators. Operators are special symbols for<br />
things like arithmetic,</p>
<p>various forms of assignment, increment and decrement, and logical operations.</p>
<p>New Term</p>
<p>Expressions are statements that return a value.</p>
<p>New Term</p>
<p>Operators are special symbols that are commonly used in expressions.</p>
<p>Arithmetic</p>
<p>Java has five operators for basic arithmetic (see Table 3.3).</p>
<p>Table 3.3. Arithmetic operators.</p>
<p>Operator Meaning Example</p>
<p>+ Addition 3 + 4</p>
<p>- Subtraction 5 &#8211; 7</p>
<p>* Multiplication 5 * 5</p>
<p>/ Division 14 / 7</p>
<p>% Modulus 20 % 7</p>
<p>Each operator takes two operands, one on either side of the operator. The<br />
subtraction operator (-) can</p>
<p>also be used to negate a single operand.</p>
<p>Integer division results in an integer. Because integers don&#8217;t have decimal<br />
fractions, any remainder is</p>
<p>ignored. The expression 31 / 9, for example, results in 3 (9 goes into 31 only 3<br />
times).</p>
<p>Modulus (%) gives the remainder once the operands have been evenly divided. For<br />
example, 31 % 9</p>
<p>results in 4 because 9 goes into 31 three times, with 4 left over.</p>
<p>Note that the result type of most arithmetic operations involving integers is an<br />
int regardless of the</p>
<p>original type of the operands (shorts and bytes are both automatically converted<br />
to int). If either or</p>
<p>both operands is of type long, the result is of type long. If one operand is an<br />
integer and another is a</p>
<p>floating-point number, the result is a floating point. (If you&#8217;re interested in<br />
the details of how Java</p>
<p>promotes and converts numeric types from one type to another, you may want to<br />
check out the Java</p>
<p>Language Specification on Sun&#8217;s official Java Web site at http://java.sun.com/;<br />
that&#8217;s more</p>
<p>detail than I want to cover here.)</p>
<p>Listing 3.1 is an example of simple arithmetic in Java.</p>
<p>Listing 3.1. Simple arithmetic.</p>
<p>1: class ArithmeticTest {</p>
<p>2: public static void main (String args[]) {</p>
<p>3: short x = 6;</p>
<p>4: int y = 4;</p>
<p>5: float a = 12.5f;</p>
<p>6: float b = 7f;</p>
<p>7:</p>
<p>8: System.out.println(&#8220;x is &#8221; + x + &#8220;, y is &#8221; + y);</p>
<p>9: System.out.println(&#8220;x + y = &#8221; + (x + y));</p>
<p>10: System.out.println(&#8220;x &#8211; y = &#8221; + (x &#8211; y));</p>
<p>11: System.out.println(&#8220;x / y = &#8221; + (x / y));</p>
<p>12: System.out.println(&#8220;x % y = &#8221; + (x % y));</p>
<p>13:</p>
<p>14: System.out.println(&#8220;a is &#8221; + a + &#8220;, b is &#8221; + b);</p>
<p>15: System.out.println(&#8220;a / b = &#8221; + (a / b));</p>
<p>16: }</p>
<p>17: }</p>
<p>x is 6, y is 4</p>
<p>x + y = 10</p>
<p>x &#8211; y = 2</p>
<p>x / y = 1</p>
<p>x % y = 2</p>
<p>a is 12.5, b is 7</p>
<p>a / b = 1.78571</p>
<p>Analysis</p>
<p>In this simple Java application (note the main() method), you</p>
<p>initially define four variables in lines 3 through 6: x and y, which are</p>
<p>integers (type int), and a and b, which are floating-point numbers</p>
<p>(type float). Keep in mind that the default type for floating-point</p>
<p>literals (such as 12.5) is double, so to make sure these are</p>
<p>numbers of type float, you have to use an f after each one (lines 5</p>
<p>and 6).</p>
<p>The remainder of the program merely does some math with integers and<br />
floating-point numbers and</p>
<p>prints out the results.</p>
<p>There is one other thing to mention about this program: the method<br />
System.out.println().</p>
<p>You&#8217;ve seen this method on previous days, but you haven&#8217;t really learned exactly<br />
what it does. The</p>
<p>System.out.println() method merely prints a message to the standard output of<br />
your system-to</p>
<p>the screen, to a special window, or maybe just to a special log file, depending<br />
on your system and the</p>
<p>development environment you&#8217;re running. The System.out.println() method takes a<br />
single</p>
<p>argument-a string-but you can use + to concatenate multiple values into a single<br />
string, as you&#8217;ll learn</p>
<p>later today.</p>
<p>More About Assignment</p>
<p>Variable assignment is a form of expression; in fact, because one assignment<br />
expression results in a</p>
<p>value, you can string them together like this:</p>
<p>x = y = z = 0;</p>
<p>In this example, all three variables now have the value 0.</p>
<p>The right side of an assignment expression is always evaluated before the<br />
assignment takes place. This</p>
<p>means that expressions such as x = x + 2 do the right thing; 2 is added to the<br />
value of x, and then</p>
<p>that new value is reassigned to x. In fact, this sort of operation is so common<br />
that Java has several</p>
<p>operators to do a shorthand version of this, borrowed from C and C++. Table 3.4<br />
shows these shorthand</p>
<p>assignment operators.</p>
<p>Table 3.4. Assignment operators.</p>
<p>Expression Meaning</p>
<p>x += y x = x + y</p>
<p>x -= y x = x &#8211; y</p>
<p>x *= y x = x * y</p>
<p>x /= y x = x / y</p>
<p>Technical Note</p>
<p>Technically, the shorthand assignment and longhand expressions are</p>
<p>not exactly equivalent, particularly in cases where x or y may</p>
<p>themselves be complicated expressions and your code relies on side</p>
<p>effects of those expressions. In most instances, however, they are</p>
<p>functionally equivalent. For more information about very complicated</p>
<p>expressions, evaluation order, and side effects, you may want to</p>
<p>consult the Java Language Specification.</p>
<p>Incrementing and Decrementing</p>
<p>As in C and C++, the ++ and &#8212; operators are used to increment or decrement a<br />
variable&#8217;s value by 1.</p>
<p>For example, x++ increments the value of x by 1 just as if you had used the<br />
expression x = x + 1.</p>
<p>Similarly x&#8211; decrements the value of x by 1. (Unlike C and C++, Java allows x<br />
to be floating point.)</p>
<p>These increment and decrement operators can be prefixed or postfixed; that is,<br />
the ++ or &#8212; can appear</p>
<p>before or after the value it increments or decrements. For simple increment or<br />
decrement expressions,</p>
<p>which one you use isn&#8217;t overly important. In complex assignments, where you are<br />
assigning the result of</p>
<p>an increment or decrement expression, which one you use makes a difference.</p>
<p>Take, for example, the following two expressions:</p>
<p>y = x++;</p>
<p>y = ++x;</p>
<p>These two expressions yield very different results because of the difference<br />
between prefix and postfix.</p>
<p>When you use postfix operators (x++ or x&#8211;), y gets the value of x before x is<br />
changed; using prefix,</p>
<p>the value of x is assigned to y after the change has occurred. Listing 3.2 is a<br />
Java example of how all this</p>
<p>works.</p>
<p>Listing 3.2. Test of prefix and postfix increment operators.</p>
<p>1: class PrePostFixTest {</p>
<p>2:</p>
<p>3: public static void main (String args[]) {</p>
<p>4: int x = 0;</p>
<p>5: int y = 0;</p>
<p>6:</p>
<p>7: System.out.println(&#8220;x and y are &#8221; + x + &#8221; and &#8221; + y );</p>
<p>8: x++;</p>
<p>9: System.out.println(&#8220;x++ results in &#8221; + x);</p>
<p>10: ++x;</p>
<p>11: System.out.println(&#8220;++x results in &#8221; + x);</p>
<p>12: System.out.println(&#8220;Resetting x back to 0.&#8221;);</p>
<p>13: x = 0;</p>
<p>14: System.out.println(&#8220;&#8212;&#8212;&#8212;&#8212;&#8221;);</p>
<p>15: y = x++;</p>
<p>16: System.out.println(&#8220;y = x++ (postfix) results in:&#8221;);</p>
<p>17: System.out.println(&#8220;x is &#8221; + x);</p>
<p>18: System.out.println(&#8220;y is &#8221; + y);</p>
<p>19: System.out.println(&#8220;&#8212;&#8212;&#8212;&#8212;&#8221;);</p>
<p>20:</p>
<p>21: y = ++x;</p>
<p>22: System.out.println(&#8220;y = ++x (prefix) results in:&#8221;);</p>
<p>23: System.out.println(&#8220;x is &#8221; + x);</p>
<p>24: System.out.println(&#8220;y is &#8221; + y);</p>
<p>25: System.out.println(&#8220;&#8212;&#8212;&#8212;&#8212;&#8221;);</p>
<p>26:</p>
<p>27: }</p>
<p>28: }</p>
<p>x and y are 0 and 0</p>
<p>x++ results in 1</p>
<p>++x results in 2</p>
<p>Resetting x back to 0.</p>
<p>&#8212;&#8212;&#8212;&#8212;</p>
<p>y = x++ (postfix) results in:</p>
<p>x is 1</p>
<p>y is 0</p>
<p>&#8212;&#8212;&#8212;&#8212;</p>
<p>y = ++x (prefix) results in:</p>
<p>x is 2</p>
<p>y is 2</p>
<p>&#8212;&#8212;&#8212;&#8212;</p>
<p>In the first part of this example, you increment x alone using both prefix and<br />
postfix increment</p>
<p>operators. In each, x is incremented by 1 each time. In this simple form, using<br />
either prefix or</p>
<p>postfix works the same way.</p>
<p>In the second part of this example, you use the expression y = x++, in which the<br />
postfix increment</p>
<p>operator is used. In this result, the value of x is incremented after that value<br />
is assigned to y. Hence the</p>
<p>result: y is assigned the original value of x (0), and then x is incremented by<br />
1.</p>
<p>In the third part, you use the prefix expression y = ++x. Here, the reverse<br />
occurs: x is incremented</p>
<p>before its value is assigned to y. Because x is 1 from the previous step, its<br />
value is incremented (to 2),</p>
<p>and then that value is assigned to y. Both x and y end up being 2.</p>
<p>Technical Note</p>
<p>Technically, this description is not entirely correct. In reality, Java</p>
<p>always completely evaluates all expressions on the right of an</p>
<p>expression before assigning that value to a variable, so the concept of</p>
<p>&#8220;assigning x to y before x is incremented&#8221; isn&#8217;t precisely right.</p>
<p>Instead, Java takes the value of x and &#8220;remembers&#8221; it, evaluates</p>
<p>(increments) x, and then assigns the original value of x to y. Although</p>
<p>in most simple cases this distinction may not be important, for more</p>
<p>complex expressions with side effects, it may change the behavior of</p>
<p>the expression overall. See the Language Specification for many more</p>
<p>details about expression evaluation in Java.</p>
<p>Comparisons</p>
<p>Java has several expressions for testing equality and magnitude. All of these<br />
expressions return a boolean</p>
<p>value (that is, true or false). Table 3.5 shows the comparison operators.</p>
<p>Table 3.5. Comparison operators.</p>
<p>Operator Meaning Example</p>
<p>== Equal x == 3</p>
<p>!= Not equal x != 3</p>
<p>&lt; Less than x &lt; 3</p>
<p>&gt; Greater than x &gt; 3</p>
<p>&lt;= Less than or equal to x &lt;= 3</p>
<p>&gt;= Greater than or equal to x &gt;= 3</p>
<p>Logical Operators</p>
<p>Expressions that result in boolean values (for example, the comparison<br />
operators) can be combined by</p>
<p>using logical operators that represent the logical combinations AND, OR, XOR,<br />
and logical NOT.</p>
<p>For AND combinations, use either the &amp; or &amp;&amp; operators. The entire expression<br />
will be true only if both</p>
<p>expressions on either side of the operator are also true; if either expression<br />
is false, the entire expression</p>
<p>is false. The difference between the two operators is in expression evaluation.<br />
Using &amp;, both sides of the</p>
<p>expression are evaluated regardless of the outcome. Using &amp;&amp;, if the left side<br />
of the expression is false,</p>
<p>the entire expression is assumed to be false (the value of the right side<br />
doesn&#8217;t matter), so the expression</p>
<p>returns false, and the right side of the expression is never evaluated. (This is<br />
often called a</p>
<p>&#8220;short-circuited&#8221; expression.)</p>
<p>For OR expressions, use either | or ||. OR expressions result in true if either<br />
or both of the expressions</p>
<p>on either side is also true; if both expression operands are false, the<br />
expression is false. As with &amp; and</p>
<p>&amp;&amp;, the single | evaluates both sides of the expression regardless of the<br />
outcome; and || is</p>
<p>short-circuited: If the left expression is true, the expression returns true and<br />
the right side is never</p>
<p>evaluated.</p>
<p>In addition, there is the XOR operator ^, which returns true only if its<br />
operands are different (one true</p>
<p>and one false, or vice versa) and false otherwise (even if both are true).</p>
<p>In general, only the &amp;&amp; and || are commonly used as actual logical combinations.<br />
&amp;, |, and ^ are more</p>
<p>commonly used for bitwise logical operations.</p>
<p>For NOT, use the ! operator with a single expression argument. The value of the<br />
NOT expression is the</p>
<p>negation of the expression; if x is true, !x is false.</p>
<p>Bitwise Operators</p>
<p>Finally, here&#8217;s a short summary of the bitwise operators in Java. Most of these<br />
expressions are inherited</p>
<p>from C and C++ and are used to perform operations on individual bits in<br />
integers. This book does not go</p>
<p>into bitwise operations; it&#8217;s an advanced topic covered better in books on C or<br />
C++. Table 3.6</p>
<p>summarizes the bitwise operators.</p>
<p>Table 3.6. Bitwise operators.</p>
<p>Operator Meaning</p>
<p>&amp; Bitwise AND</p>
<p>| Bitwise OR</p>
<p>^ Bitwise XOR</p>
<p>&lt;&lt; Left shift</p>
<p>&gt;&gt; Right shift</p>
<p>&gt;&gt;&gt; Zero fill right shift</p>
<p>~ Bitwise complement</p>
<p>&lt;&lt;= Left shift assignment (x = x &lt;&lt; y)</p>
<p>&gt;&gt;= Right shift assignment (x = x &gt;&gt; y)</p>
<p>&gt;&gt;&gt;= Zero fill right shift assignment (x = x</p>
<p>&gt;&gt;&gt; y)</p>
<p>x&amp;=y AND assignment (x = x &amp; y)</p>
<p>x|=y OR assignment (x = x | y)</p>
<p>x^=y XOR assignment (x = x ^ y)</p>
<p>Operator Precedence</p>
<p>Operator precedence determines the order in which expressions are evaluated.<br />
This, in some cases, can</p>
<p>determine the overall value of the expression. For example, take the following<br />
expression:</p>
<p>y = 6 + 4 / 2</p>
<p>Depending on whether the 6 + 4 expression or the 4 / 2 expression is evaluated<br />
first, the value of y</p>
<p>can end up being 5 or 8. Operator precedence determines the order in which<br />
expressions are evaluated,</p>
<p>so you can predict the outcome of an expression. In general, increment and<br />
decrement are evaluated</p>
<p>before arithmetic, arithmetic expressions are evaluated before comparisons, and<br />
comparisons are</p>
<p>evaluated before logical expressions. Assignment expressions are evaluated last.</p>
<p>Table 3.7 shows the specific precedence of the various operators in Java.<br />
Operators further up in the table</p>
<p>are evaluated first; operators on the same line have the same precedence and are<br />
evaluated left to right</p>
<p>based on how they appear in the expression itself. For example, given that same<br />
expression y = 6 + 4</p>
<p>/ 2, you now know, according to this table, that division is evaluated before<br />
addition, so the value of y</p>
<p>will be 8.</p>
<p>Table 3.7. Operator precedence.</p>
<p>Operator Notes</p>
<p>. [] () Parentheses (()) are used to group expressions; dot</p>
<p>(.) is used for access to methods and variables</p>
<p>within objects and classes (discussed tomorrow);</p>
<p>square brackets ([]) are used for arrays (this is</p>
<p>discussed later on in the week)</p>
<p>++ &#8212; ! ~</p>
<p>instanceof</p>
<p>The instanceof operator returns true or</p>
<p>false based on whether the object is an instance</p>
<p>of the named class or any of that class&#8217;s subclasses</p>
<p>(discussed tomorrow)</p>
<p>new (type)expression The new operator is used for creating new instances</p>
<p>of classes; () in this case is for casting a value to</p>
<p>another type (you&#8217;ll learn about both of these</p>
<p>tomorrow)</p>
<p>* / % Multiplication, division, modulus</p>
<p>+ &#8211; Addition, subtraction</p>
<p>&lt;&lt; &gt;&gt; &gt;&gt;&gt; Bitwise left and right shift</p>
<p>&lt; &gt; &lt;= &gt;= Relational comparison tests</p>
<p>== != Equality</p>
<p>&amp; AND</p>
<p>^ XOR</p>
<p>| OR</p>
<p>&amp;&amp; Logical AND</p>
<p>|| Logical OR</p>
<p>? : Shorthand for if&#8230;then&#8230;else (discussed on</p>
<p>Day 5)</p>
<p>= += -= *= /= %= ^= Various assignments</p>
<p>&amp;= |= &lt;&lt;= &gt;&gt;= &gt;&gt;&gt;= More assignments</p>
<p>You can always change the order in which expressions are evaluated by using<br />
parentheses around the</p>
<p>expressions you want to evaluate first. You can nest parentheses to make sure<br />
expressions evaluate in the</p>
<p>order you want them to (the innermost parenthetic expression is evaluated<br />
first). The following</p>
<p>expression results in a value of 5, because the 6 + 4 expression is evaluated<br />
first, and then the result of</p>
<p>that expression (10) is divided by 2:</p>
<p>y = (6 + 4) / 2</p>
<p>Parentheses also can be useful in cases where the precedence of an expression<br />
isn&#8217;t immediately clear-in</p>
<p>other words, they can make your code easier to read. Adding parentheses doesn&#8217;t<br />
hurt, so if they help you</p>
<p>figure out how expressions are evaluated, go ahead and use them.</p>
<p>String Arithmetic</p>
<p>One special expression in Java is the use of the addition operator (+) to create<br />
and concatenate strings. In</p>
<p>most of the examples shown today and in earlier lessons, you&#8217;ve seen lots of<br />
lines that looked something</p>
<p>like this:</p>
<p>System.out.println(name + &#8221; is a &#8221; + color + &#8221; beetle&#8221;);</p>
<p>The output of that line (to the standard output) is a single string, with the<br />
values of the variables (name</p>
<p>and color), inserted in the appropriate spots in the string. So what&#8217;s going on<br />
here?</p>
<p>The + operator, when used with strings and other objects, creates a single<br />
string that contains the</p>
<p>concatenation of all its operands. If any of the operands in string<br />
concatenation is not a string, it is</p>
<p>automatically converted to a string, making it easy to create these sorts of<br />
output lines.</p>
<p>Technical Note</p>
<p>An object or type can be converted to a string if you implement the</p>
<p>method toString(). All objects have a default string</p>
<p>representation, but most classes override toString() to provide a</p>
<p>more meaningful printable representation.</p>
<p>String concatenation makes lines such as the previous one especially easy to<br />
construct. To create a string,</p>
<p>just add all the parts together-the descriptions plus the variables-and print it<br />
to the standard output, to the</p>
<p>screen, to an applet, or anywhere.</p>
<p>The += operator, which you learned about earlier, also works for strings. For<br />
example, take the following</p>
<p>expression:</p>
<p>myName += &#8221; Jr.&#8221;;</p>
<p>This expression is equivalent to this:</p>
<p>myName = myName + &#8221; Jr.&#8221;;</p>
<p>just as it would be for numbers. In this case, it changes the value of myName,<br />
which might be something</p>
<p>like John Smith to have a Jr. at the end (John Smith Jr.).</p>
<p>Summary</p>
<p>As you have learned in the last two lessons, a Java program is made up primarily<br />
of classes and objects.</p>
<p>Classes and objects, in turn, are made up of methods and variables, and methods<br />
are made up of</p>
<p>statements and expressions. It is those last two things that you&#8217;ve learned<br />
about today; the basic building</p>
<p>blocks that enable you to create classes and methods and build them up to a<br />
full-fledged Java program.</p>
<p>Today, you have learned about variables, how to declare them and assign values<br />
to them; literals for</p>
<p>easily creating numbers, characters, and strings; and operators for arithmetic,<br />
tests, and other simple</p>
<p>operations. With this basic syntax, you can move on tomorrow to learning about<br />
working with objects</p>
<p>and building simple, useful Java programs.</p>
<p>To finish up this summary, Table 3.8 is a list of all the operators you have<br />
learned about today so that</p>
<p>you can refer back to them.</p>
<p>Table 3.8. Operator summary.</p>
<p>Operator Meaning</p>
<p>+ Addition</p>
<p>- Subtraction</p>
<p>* Multiplication</p>
<p>/ Division</p>
<p>% Modulus</p>
<p>&lt; Less than</p>
<p>&gt; Greater than</p>
<p>&lt;= Less than or equal to</p>
<p>&gt;= Greater than or equal to</p>
<p>== Equal</p>
<p>!= Not equal</p>
<p>&amp;&amp; Logical AND</p>
<p>|| Logical OR</p>
<p>! Logical NOT</p>
<p>&amp; AND</p>
<p>| OR</p>
<p>^ XOR</p>
<p>&lt;&lt; Left shift</p>
<p>&gt;&gt; Right shift</p>
<p>&gt;&gt;&gt; Zero fill right shift</p>
<p>~ Complement</p>
<p>= Assignment</p>
<p>++ Increment</p>
<p>&#8212;- Decrement</p>
<p>+= Add and assign</p>
<p>-= Subtract and assign</p>
<p>*= Multiply and assign</p>
<p>/= Divide and assign</p>
<p>%= Modulus and assign</p>
<p>&amp;= AND and assign</p>
<p>|= OR and assign</p>
<p>&lt;&lt;= Left shift and assign</p>
<p>^= XOR and assign</p>
<p>&gt;&gt;= Right shift and assign</p>
<p>&gt;&gt;&gt;= Zero fill right shift and assign</p>
<p>Q&amp;A</p>
<p>Q: I didn&#8217;t see any way to define constants.</p>
<p>A: You can&#8217;t create local constants in Java; you can create only constant<br />
instance and class</p>
<p>variables. You&#8217;ll learn how to do this tomorrow.</p>
<p>Q: What happens if you assign an integer value to a variable that is too large<br />
for that variable</p>
<p>to hold?</p>
<p>A: Logically, you would think that the variable is just converted to the next<br />
larger type, but this isn&#8217;t</p>
<p>what happens. What does happen is called overflow. This means that if a number<br />
becomes too</p>
<p>big for its variable, that number wraps around to the smallest possible negative<br />
number for that</p>
<p>type and starts counting upward toward zero again.</p>
<p>Because this can result in some very confusing (and wrong) results, make sure<br />
that you declare</p>
<p>the right integer type for all your numbers. If there&#8217;s a chance a number will<br />
overflow its type,</p>
<p>use the next larger type instead.</p>
<p>Q: How can you find out the type of a given variable?</p>
<p>A: If you&#8217;re using any of the primitive types (int, float, boolean), and so on,<br />
you can&#8217;t. If you</p>
<p>care about the type, you can convert the value to some other type by using<br />
casting. (You&#8217;ll learn</p>
<p>about this tomorrow.)</p>
<p>If you&#8217;re using class types, you can use the instanceof operator, which you&#8217;ll<br />
learn more</p>
<p>about tomorrow.</p>
<p>Q: Why does Java have all these shorthand operators for arithmetic and<br />
assignment? It&#8217;s</p>
<p>really hard to read that way.</p>
<p>A: The syntax of Java is based on C++, and therefore on C. One of C&#8217;s implicit<br />
goals is the</p>
<p>capability of doing very powerful things with a minimum of typing. Because of<br />
this, shorthand</p>
<p>operators, such as the wide array of assignments, are common.</p>
<p>There&#8217;s no rule that says you have to use these operators in your own programs,<br />
however. If you</p>
<p>find your code to be more readable using the long form, no one will come to your<br />
house and</p>
<p>make you change it.</p>
<p>Q: You covered simple math in this section using operators. I&#8217;m assuming that<br />
Java has ways</p>
<p>of doing more complex math operations?</p>
<p>A: You assume correctly. A special class in the java.lang package, called<br />
java.lang.Math,</p>
<p>has a number of methods for exponential, trigonometric, and other basic math<br />
operations. In fact,</p>
<p>because you call these methods using the Math class itself, these are prime<br />
examples of class</p>
<p>methods. You&#8217;ll learn more about this tomorrow.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/swebsolution.wordpress.com/24/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/swebsolution.wordpress.com/24/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/swebsolution.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/swebsolution.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/swebsolution.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/swebsolution.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/swebsolution.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/swebsolution.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/swebsolution.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/swebsolution.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/swebsolution.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/swebsolution.wordpress.com/24/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=24&subd=swebsolution&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://swebsolution.wordpress.com/2008/01/08/java-help-java-tutorials-java-programming-java-tricks-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/4fc1b8adaf945b9ecf45239af6e622af?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Prakash Sherawat</media:title>
		</media:content>
	</item>
		<item>
		<title>Java Help, Java Tutorials, Java Programming, Java Tricks</title>
		<link>http://swebsolution.wordpress.com/2008/01/04/java-help-java-tutorials-java-programming-java-tricks-2/</link>
		<comments>http://swebsolution.wordpress.com/2008/01/04/java-help-java-tutorials-java-programming-java-tricks-2/#comments</comments>
		<pubDate>Fri, 04 Jan 2008 14:54:00 +0000</pubDate>
		<dc:creator>Prakash Sherawat</dc:creator>
				<category><![CDATA[Java Help]]></category>

		<guid isPermaLink="false">http://swebsolution.wordpress.com/2008/01/04/java-help-java-tutorials-java-programming-java-tricks-2/</guid>
		<description><![CDATA[Lesson Two
Thinking in Objects: An Analogy
CONTENTS
Objects and Classes
Behavior and Attributes
Attributes
Behavior
Creating a Class
Inheritance, Interfaces, and Packages
Inheritance
Creating a Class Hierarchy
How Inheritance Works
Single and Multiple Inheritance
Interfaces and Packages
Creating a Subclass
Summary
Q&#38;A
Object-oriented programming (OOP) is one of the biggest programming ideas of
recent years, and you might worry that you must spend ears learning all about
object-oriented programming methodologies and how they [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=swebsolution.wordpress.com&blog=2327723&post=23&subd=swebsolution&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p align="justify"><b>Lesson Two</b></p>
<p>Thinking in Objects: An Analogy</p>
<p>CONTENTS</p>
<p>Objects and Classes</p>
<p>Behavior and Attributes</p>
<p>Attributes</p>
<p>Behavior</p>
<p>Creating a Class</p>
<p>Inheritance, Interfaces, and Packages</p>
<p>Inheritance</p>
<p>Creating a Class Hierarchy</p>
<p>How Inheritance Works</p>
<p>Single and Multiple Inheritance</p>
<p>Interfaces and Packages</p>
<p>Creating a Subclass</p>
<p>Summary</p>
<p>Q&amp;A</p>
<p>Object-oriented programming (OOP) is one of the biggest programming ideas of<br />
recent years, and you might worry that you must spend ears learning all about<br />
object-oriented programming methodologies and how they can make your life easier<br />
than The Old Way of programming. It all comes down to organizing your programs<br />
in ways that echo how things are put together in the real world.</p>
<p>Today you&#8217;ll get an overview of object-oriented programming concepts in Java and<br />
how they relate to how you structure your own</p>
<p>programs:</p>
<p>What classes and objects are and how they relate to each other</p>
<p>The two main parts of a class or object: its behaviors and its attributes</p>
<p>Class inheritance and how inheritance affects the way you design your programs</p>
<p>Some information about packages and interfaces</p>
<p>If you&#8217;re already familiar with object-oriented programming, much of today&#8217;s<br />
lesson will be old hat to you.</p>
<p>You may want to skim it and go to a movie today instead. Tomorrow, you&#8217;ll get<br />
into more specific details.</p>
<p>Thinking in Objects: An Analogy</p>
<p>Consider, if you will, Legos. Legos, for those who do not spend much time with<br />
children, are small plastic building blocks in various colors and sizes. They<br />
have small round bits on one side that fit into small round holes on other Legos<br />
so that they fit together snugly to create larger shapes. With different Lego<br />
parts (Lego wheels, Lego engines, Lego hinges, Lego pulleys), you can put<br />
together castles, automobiles, giant robots that swallow cities, or just about<br />
anything else you can imagine. Each Lego part is a small object that fits<br />
together with other small objects in predefined ways to create other larger<br />
objects. That is roughly how object-oriented</p>
<p>programming works: putting together smaller elements to build larger ones.</p>
<p>Here&#8217;s another example. You can walk into a computer store and, with a little<br />
background and often some help, assemble an entire pc computer system from<br />
various components: a motherboard, a CPU chip, a video card, a hard disk, a<br />
keyboard, and so on. Ideally, when you finish assembling all the various<br />
self-contained units, you have a system in which all the units work together to<br />
create a larger system with which you can solve the problems you bought the<br />
computer for in the first place.</p>
<p>Internally, each of those components may be vastly complicated and engineered by<br />
different companies with different methods of design. But you don&#8217;t need to know<br />
how the component works, what every chip on the board does, or how, when you<br />
press the A key, an A gets sent to your computer. As the assembler of the<br />
overall system, each component you use is a self-contained unit, and all you are<br />
interested in is how the units interact with each other. Will this video card<br />
fit into the slots on the motherboard, and will this monitor work with this<br />
video card? Will each particular component speak the right commands to the other<br />
components it interacts with so that each part of the computer is understood by<br />
every other part? Once you know what the interactions are between the components<br />
and can match the interactions, putting together the overall system is easy.</p>
<p>What does this have to do with programming? Everything. Object-oriented<br />
programming works in exactly this same way. Using object-oriented programming,<br />
your overall program is made up of lots of different self-contained components<br />
(objects), each of which has a specific role in the program and all of which can<br />
talk to each other in predefined ways.</p>
<p>Objects and Classes</p>
<p>Object-oriented programming is modeled on how, in the real world, objects are<br />
often ade up of many kindsof smaller objects. This capability of combining<br />
objects, owever, is only one very general aspect ofobject-oriented programming.<br />
Object-oriented rogramming provides several other concepts and features to make<br />
creating and using objects easier and more flexible, and the most important of<br />
these features is classes.</p>
<p>When you write a program in an object-oriented language, you don&#8217;t define actual<br />
objects. You define classes of objects, where a class is a template for multiple<br />
objects with similar features. Classes embody all the features of a particular<br />
set of objects. For example, you might have a Tree class that describes the<br />
features of all trees (has leaves and roots, grows, creates chlorophyll). The<br />
Tree class serves as an abstract model for the concept of a tree-to reach out<br />
and grab, or interact with, or cut down a tree you have to have a concrete</p>
<p>instance of that tree. Of course, once you have a tree class, you can create<br />
lots of different instances of that tree, and each different tree instance can<br />
have different features (short, tall, bushy, drops leaves in autumn), while<br />
still behaving like and being immediately recognizable as a tree (see Figure<br />
2.1).</p>
<p>Figure 2.1 : The Tree class and several Tree instances.</p>
<p>New Term</p>
<p>A class is a generic template for a set of objects with similar features.</p>
<p>An instance of a class is another word for an actual object. If class is the<br />
general (generic) representation of an object, an instance is its concrete<br />
representation. So what, precisely, is the difference between an instance and an<br />
object? Nothing, really. Object is the more general term, but both instances and<br />
objects are the concrete representation of a class. In fact, the terms instance<br />
and object are often used interchangeably in OOP lingo.</p>
<p>An instance of a tree and a tree object are both the same thing.</p>
<p>New Term</p>
<p>An instance is the specific concrete representation of a class.</p>
<p>Instances and objects are the same thing.</p>
<p>What about an example closer to the sort of things you might want to do in Java<br />
programming? You might create a class for the user interface element called a<br />
button. The Button class defines the features of a button (its label, its size,<br />
its appearance) and how it behaves. (Does it need a single-click or a<br />
double-click to activate it? Does it change color when it&#8217;s clicked? What does<br />
it do when it&#8217;s activated?) After you define the Button class, you can then<br />
easily create instances of that button-that is, button objects-that all take on<br />
the basic features of the button as defined by the class, but may have different<br />
appearances and behavior based on what you want that particular button to do. By<br />
creating a Button class, you don&#8217;t have to keep rewriting the code for each<br />
individual button you want to use in your program, and you can reuse the Button<br />
class to create different kinds of buttons as you need them in this program and<br />
in other programs.</p>
<p>Tip</p>
<p>If you&#8217;re used to programming in C, you can think of a class as sort of creating<br />
a new composite data type by using struct and typedef. Classes, however, can<br />
provide much more than just a collection of data, as you&#8217;ll discover in the rest<br />
of today&#8217;s lesson. When you write a Java program, you design and construct a set<br />
of classes. Then when your program runs, instances of those classes are created<br />
and discarded as needed. Your task, as a Java programmer, is to create the right<br />
set of classes to accomplish what your program needs to accomplish. Fortunately,<br />
you don&#8217;t have to start from the very beginning: The Java environment comes with<br />
a standard set</p>
<p>of classes (called a class library) that implement a lot of the basic behavior<br />
you need-not only for basic programming tasks (classes to provide basic math<br />
functions, arrays, strings, and so on), but also for graphics and networking<br />
behavior. In many cases, the Java class libraries may be enough so that all you<br />
have to do in your Java program is create a single class that uses the standard<br />
class libraries. For complicated Java programs, you may have to create a whole<br />
set of classes with defined interactions between them.</p>
<p>New Term</p>
<p>A class library is a collection of classes intended to be reused repeatedly in<br />
different programs. The standard Java class libraries contain quite a few<br />
classes for accomplishing basic programming tasks in Java.</p>
<p>Behavior and Attributes</p>
<p>Every class you write in Java has two basic features: attributes and behavior.<br />
In this section you&#8217;ll learn about each one as it applies to a theoretical<br />
simple class called Motorcycle. To finish up this section, you&#8217;ll create the<br />
Java code to implement a representation of a motorcycle.</p>
<p>Attributes</p>
<p>Attributes are the individual things that differentiate one object from another<br />
and determine the appearance, state, or other qualities of that object. Let&#8217;s<br />
create a theoretical class called Motorcycle. A motorcycle class might include<br />
the following attributes and have these typical values:</p>
<p>l Color: red, green, silver, brown</p>
<p>l Style: cruiser, sport bike, standard</p>
<p>l Make: Honda, BMW, Bultaco</p>
<p>Attributes of an object can also include information about its state; for<br />
example, you could have features for engine condition (off or on) or current<br />
gear selected.</p>
<p>Attributes are defined in classes by variables. Those variables&#8217; types and names<br />
are defined in the class, and each object can have its own values for those<br />
variables. Because each instance of a class can have different values for its<br />
variables, these variables are often called instance variables.</p>
<p>New Term</p>
<p>An instance variable defines the attributes of the object. Instance variables&#8217;<br />
types and names are defined in the class, but their values</p>
<p>are set and changed in the object. Instance variables may be initially set when<br />
an object is created and stay constant throughout the life of the object, or<br />
they may be able to change at will as the program runs. Change the value of the<br />
variable, and you</p>
<p>change an object&#8217;s attributes. In addition to instance variables, there are also<br />
class variables, which apply to the class itself and to all its</p>
<p>instances. Unlike instance variables, whose values are stored in the instance,<br />
class variables&#8217; values are stored in the class itself. You&#8217;ll learn about class<br />
variables later on this week and more specifics about instance variables<br />
tomorrow.</p>
<p>Behavior</p>
<p>A class&#8217;s behavior determines how an instance of that class operates; for<br />
example, how it will &#8220;react&#8221; if asked to do something by another class or object<br />
or if its internal state changes. Behavior is the only way objects can do<br />
anything to themselves or have anything done to them. For example, to go back to<br />
the theoretical Motorcycle class, here are some behaviors that the Motorcycle<br />
class might have:</p>
<p>l Start the engine</p>
<p>l Stop the engine</p>
<p>l Speed up</p>
<p>l Change gear</p>
<p>l Stall</p>
<p>To define an object&#8217;s behavior, you create methods, a set of Java statements<br />
that accomplish some task. Methods look and behave just like functions in other<br />
languages but are defined and accessible solely inside a class. Java does not<br />
have functions defined outside classes (as C++ does).</p>
<p>New Term</p>
<p>Methods are functions defined inside classes that operate on instances</p>
<p>of those classes.</p>
<p>While methods can be used solely to operate on an individual object, methods are<br />
also used between objects to communicate with each other. A class or an object<br />
can call methods in another class or object to communicate changes in the<br />
environment or to ask that object to change its state. Just as there are<br />
instance and class variables, there are also instance and class methods.<br />
Instance methods (which are so common that they&#8217;re usually just called methods)<br />
apply and operate on an instance of a class; class methods apply and operate on<br />
the class itself. You&#8217;ll learn more about class methods later on this week.</p>
<p>Creating a Class</p>
<p>Up to this point, today&#8217;s lesson has been pretty theoretical. In this section,<br />
you&#8217;ll create a working example of the Motorcycle class so that you can see how<br />
instance variables and methods are defined in a class in Java. You&#8217;ll also<br />
create a Java application that creates a new instance of the Motorcycle class<br />
and shows its instance variables.</p>
<p>Note</p>
<p>I&#8217;m not going to go into a lot of detail about the actual syntax of this example<br />
here. Don&#8217;t worry too much about it if you&#8217;re not really sure</p>
<p>what&#8217;s going on; it will become clear to you later on this week. All you really<br />
need to worry about in this example is understanding the</p>
<p>basic parts of this class definition. Ready? Let&#8217;s start with a basic class<br />
definition. Open the text editor you&#8217;ve been using to create Java source code<br />
and enter the following (remember, upper- and lowercase matters):</p>
<p>class Motorcycle {</p>
<p>}</p>
<p>Congratulations! You&#8217;ve now created a class. Of course, it doesn&#8217;t do very much<br />
at the moment, but that&#8217;s a</p>
<p>Java class at its very simplest.</p>
<p>First, let&#8217;s create some instance variables for this class-three of them, to be<br />
specific. Just below the first line,</p>
<p>add the following three lines:</p>
<p>String make;</p>
<p>String color;</p>
<p>boolean engineState = false;</p>
<p>Here you&#8217;ve created three instance variables: Two, make and color, can contain<br />
String objects (a string is the generic term for a series of characters; String,<br />
with a capital S, is part of that standard class library mentioned earlier). The<br />
third, engineState, is a boolean variable that refers to whether the engine is<br />
off or on; a value of false means that the engine is off, and true means that<br />
the engine is on. Note that boolean is lowercase b.</p>
<p>New Term</p>
<p>A boolean is a value of either true or false.</p>
<p>Technical Note</p>
<p>boolean in Java is a real data type that can have the values true or false.<br />
Unlike in C, booleans are not numbers. You&#8217;ll hear about this again tomorrow so<br />
that you won&#8217;t forget. Now let&#8217;s add some behavior (methods) to the class. There<br />
are all kinds of things a motorcycle can do, but to keep things short, let&#8217;s add<br />
just one method-a method that starts the engine. Add the following lines below<br />
the</p>
<p>instance variables in your class definition:</p>
<p>void startEngine() {</p>
<p>if (engineState == true)</p>
<p>System.out.println(&#8220;The engine is already on.&#8221;);</p>
<p>else {</p>
<p>engineState = true;</p>
<p>System.out.println(&#8220;The engine is now on.&#8221;);</p>
<p>}</p>
<p>}</p>
<p>The startEngine() method tests to see whether the engine is already running (in<br />
the part engineState == true) and, if it is, merely prints a message to that<br />
effect. If the engine isn&#8217;t already running, it changes the state of the engine<br />
to true (turning the engine on) and then prints a message. Finally, because the<br />
startEngine() method doesn&#8217;t return a value, its definition includes the word<br />
void at the beginning. (You can also define methods to return values; you&#8217;ll<br />
learn more about method definitions on Day 6, &#8220;Creating Classes and Applications<br />
in Java.&#8221;)</p>
<p>Tip</p>
<p>Here and throughout this book, whenever I refer to the name of a method, I&#8217;ll<br />
add empty parentheses to the end of the name (for</p>
<p>example, as I did in the first sentence of the previous paragraph: &#8220;The<br />
startEngine() method…&#8221; This is a convention used in the</p>
<p>programming community at large to indicate that a particular name is a method<br />
and not a variable. The parentheses are silent.</p>
<p>With your methods and variables in place, save the program to a file called<br />
Motorcycle.java (remember that you should always name your Java source files the<br />
same names as the class they define). Listing 2.1 shows what your program should<br />
look like so far.</p>
<p>Listing 2.1. The Motorcycle.java file.</p>
<p>1:class Motorcycle {</p>
<p>2:</p>
<p>3: String make;</p>
<p>4: String color;</p>
<p>5: boolean engineState = false;</p>
<p>6:</p>
<p>7: void startEngine() {</p>
<p>8: if (engineState == true)</p>
<p>9: System.out.println(&#8220;The engine is already on.&#8221;);</p>
<p>10: else {</p>
<p>11: engineState = true;</p>
<p>12: System.out.println(&#8220;The engine is now on.&#8221;);</p>
<p>13: }</p>
<p>14: }</p>
<p>15:}</p>
<p>Tip</p>
<p>The indentation of each part of the class isn&#8217;t important to the Java compiler.<br />
Using some form of indentation, however, makes your lass definition easier for<br />
you and other people to read. The indentation used here, with instance variables<br />
and methods indented from the lass definition, is the style used throughout this<br />
book. The Java class libraries use a similar indentation. You can choose any<br />
indentation style hat you like.</p>
<p>Before you compile this class, let&#8217;s add one more method just below the<br />
startEngine() method (that is, between lines 14 and 15). The showAtts() method<br />
is used to print the current values of all the instance variables in an instance<br />
of your Motorcycle class. Here&#8217;s what it looks like:</p>
<p>void showAtts() {</p>
<p>System.out.println(&#8220;This motorcycle is a &#8220;</p>
<p>+ color + &#8221; &#8221; + make);</p>
<p>if (engineState == true)</p>
<p>System.out.println(&#8220;The engine is on.&#8221;);</p>
<p>else System.out.println(&#8220;The engine is off.&#8221;);</p>
<p>}</p>
<p>The showAtts() method prints two lines to the screen: the make and color of the<br />
motorcycle object and whether the engine is on or off. Now you have a Java class<br />
with three instance variables and two methods defined. Save that file again, and<br />
compile it using one of the following methods:</p>
<p>Note</p>
<p>After this point, I&#8217;m going to assume you know how to compile and run Java<br />
programs. I won&#8217;t repeat this information after this.</p>
<p>Windows</p>
<p>From inside a DOS shell, CD to the directory containing your Java source file,<br />
and use the javac command to compile it:</p>
<p>javac Motorcycle.java</p>
<p>Macintosh</p>
<p>Drag and drop the Motorcycle.java file onto the Java Compiler icon.</p>
<p>Salaris</p>
<p>From a command line, CD to the directory containing your Java source file, and<br />
use the javac command to compile it:</p>
<p>javac Motorcycle.java</p>
<p>When you run this little program using the java or Java Runner programs, you&#8217;ll<br />
get an error. Why? When you run a compiled Java class directly, Java assumes<br />
that the class is an application and looks for a main()</p>
<p>method. Because we haven&#8217;t defined a main() method inside the class, the Java<br />
interpreter (java) gives you</p>
<p>an error something like one of these two errors:</p>
<p>In class Motorcycle: void main(String argv[]) is not defined</p>
<p>Exception in thread &#8220;main&#8221;: java.lang.UnknownError</p>
<p>To do something with the Motorcycle class-for example, to create instances of<br />
that class and play with them-you&#8217;re going to need to create a separate Java<br />
applet or application that uses this class or add a main()method to this one.<br />
For simplicity&#8217;s sake, let&#8217;s do the latter. Listing 2.2 shows the main() method<br />
you&#8217;ll add to the Motorcycle class. You&#8217;ll want to add this method to your<br />
Motorcycle.java source file just before the last closing brace (}), underneath<br />
the startEngine() and showAtts() methods.</p>
<p>Listing 2.2. The main() method for Motorcycle.java.</p>
<p>1: public static void main (String args[]) {</p>
<p>2: Motorcycle m = new Motorcycle();</p>
<p>3: m.make = &#8220;Yamaha RZ350&#8243;;</p>
<p>4: m.color = &#8220;yellow&#8221;;</p>
<p>5: System.out.println(&#8220;Calling showAtts&#8230;&#8221;);</p>
<p>6: m.showAtts();</p>
<p>7: System.out.println(&#8220;&#8212;&#8212;&#8211;&#8221;);</p>
<p>8: System.out.println(&#8220;Starting engine&#8230;&#8221;);</p>
<p>9: m.startEngine();</p>
<p>10: System.out.println(&#8220;&#8212;&#8212;&#8211;&#8221;);</p>
<p>11: System.out.println(&#8220;Calling showAtts&#8230;&#8221;);</p>
<p>12: m.showAtts();</p>
<p>13: System.out.println(&#8220;&#8212;&#8212;&#8211;&#8221;);</p>
<p>14: System.out.println(&#8220;Starting engine&#8230;&#8221;);</p>
<p>15: m.startEngine();</p>
<p>16:}</p>
<p>With the main() method in place, the Motorcycle class is now an official<br />
application, and you can</p>
<p>compile it again and this time it&#8217;ll run. Here&#8217;s how the output should look:</p>
<p>Calling showAtts&#8230;</p>
<p>This motorcycle is a yellow Yamaha RZ350</p>
<p>The engine is off.</p>
<p>&#8212;&#8212;&#8211;</p>
<p>Starting engine&#8230;</p>
<p>The engine is now on.</p>
<p>&#8212;&#8212;&#8211;</p>
<p>Calling showAtts&#8230;</p>
<p>This motorcycle is a yellow Yamaha RZ350</p>
<p>The engine is on.</p>
<p>&#8212;&#8212;&#8211;</p>
<p>Starting engine&#8230;</p>
<p>The engine is already on.</p>
<p>Analysis</p>
<p>The contents of the main() method are all going to look very new to you, so<br />
let&#8217;s go through it line by line so that you at least have a basic idea of what<br />
it does (you&#8217;ll get details about the specifics of all of this tomorrow and the<br />
day after).</p>
<p>The first line declares the main() method. The first line of the main() method<br />
always looks like this; you&#8217;ll learn the specifics of each part later this week.</p>
<p>Line 2, Motorcycle m = new Motorcycle();, creates a new instance of the<br />
Motorcycle class and stores a reference to it in the variable m. Remember, you<br />
don&#8217;t usually operate directly on classes in your Java programs; instead, you<br />
create objects from those classes and then call methods in those objects. Lines<br />
3 and 4 set the instance variables for this Motorcycle object: The make is now a<br />
Yamaha RZ350 (a very pretty motorcycle from the mid-1980s), and the color is<br />
yellow.</p>
<p>Lines 5 and 6 call the showAtts() method, defined in your Motorcycle object.<br />
(Actually, only 6 does; 5 just prints a message that you&#8217;re about to call this<br />
method.) The new motorcycle object then prints out the values of its instance<br />
variables-the make and color as you set in the previous lines-and shows that the<br />
engine is off.</p>
<p>Line 7 prints a divider line to the screen; this is just for prettier output.</p>
<p>Line 9 calls the startEngine() method in the motorcycle object to start the<br />
engine. The engine should now be on.</p>
<p>Line 11 prints the values of the instance variables again. This time, the report<br />
should say the engine is now on.</p>
<p>Line 15 tries to start the engine again, just for fun. Because the engine is<br />
already on, this should print the message The engine is already on.</p>
<p>Listing 2.3 shows the final Motorcycle class, in case you&#8217;ve been having trouble<br />
compiling and running the one you&#8217;ve got (and remember, this example and all the<br />
examples in this book are available on the CD that accompanies the book):</p>
<p>Listing 2.3. The final version of Motorcycle.java.</p>
<p>1: class Motorcycle {</p>
<p>2:</p>
<p>3: String make;</p>
<p>4: String color;</p>
<p>5: boolean engineState;</p>
<p>6:</p>
<p>7: void startEngine() {</p>
<p>8: if (engineState == true)</p>
<p>9: System.out.println(&#8220;The engine is already on.&#8221;);</p>
<p>10: else {</p>
<p>11: engineState = true;</p>
<p>12: System.out.println(&#8220;The engine is now on.&#8221;);</p>
<p>13: }</p>
<p>14: }</p>
<p>15:</p>
<p>16: void showAtts() {</p>
<p>17: System.out.println(&#8220;This motorcycle is a &#8220;</p>
<p>18: + color + &#8221; &#8221; + make);</p>
<p>19: if (engineState == true)</p>
<p>20: System.out.println(&#8220;The engine is on.&#8221;);</p>
<p>21: else System.out.println(&#8220;The engine is off.&#8221;);</p>
<p>22: }</p>
<p>23:</p>
<p>24: public static void main (String args[]) {</p>
<p>25: Motorcycle m = new Motorcycle();</p>
<p>26: m.make = &#8220;Yamaha RZ350&#8243;;</p>
<p>27: m.color = &#8220;yellow&#8221;;</p>
<p>28: System.out.println(&#8220;Calling showAtts&#8230;&#8221;);</p>
<p>29: m.showAtts();</p>
<p>30: System.out.println(&#8220;&#8212;&#8212;&#8221;);</p>
<p>31: System.out.println(&#8220;Starting engine&#8230;&#8221;);</p>
<p>32: m.startEngine();</p>
<p>33: System.out.println(&#8220;&#8212;&#8212;&#8221;);</p>
<p>34: System.out.println(&#8220;Calling showAtts&#8230;&#8221;);</p>
<p>35: m.showAtts();</p>
<p>36: System.out.println(&#8220;&#8212;&#8212;&#8221;);</p>
<p>37: System.out.println(&#8220;Starting engine&#8230;&#8221;);</p>
<p>38: m.startEngine();</p>
<p>39: }</p>
<p>40:}</p>
<p>Inheritance, Interfaces, and Packages</p>
<p>Now that you have a basic grasp of classes, objects, methods, variables, and how<br />
to put them all together in a Java program, it&#8217;s time to confuse you again.<br />
Inheritance, interfaces, and packages are all mechanisms for organizing classes<br />
and class behaviors. The Java class libraries use all these concepts, and the<br />
best class libraries you write for your own programs will also use these<br />
concepts.</p>
<p>Inheritance</p>
<p>Inheritance is one of the most crucial concepts in object-oriented programming,<br />
and it has a very direct effect on how you design and write your Java classes.<br />
Inheritance is a powerful mechanism that means when you write a class you only<br />
have to specify how that class is different from some other class; inheritance<br />
will give you automatic access to the information contained in that other class.</p>
<p>With inheritance, all classes-those you write, those from other class libraries<br />
that you use, and those from the standard utility classes as well-are arranged<br />
in a strict hierarchy (see Figure 2.2). Each class has a superclass (the class<br />
above it in the hierarchy), and each class can have one or more subclasses<br />
(classes below that class in the hierarchy). Classes further down in the<br />
hierarchy are said to inherit from classes further up in the hierarchy.</p>
<p>Figure 2.2 : A class hierarchy.</p>
<p>Subclasses inherit all the methods and variables from their superclasses-that<br />
is, in any particular class, if the superclass defines behavior that your class<br />
needs, you don&#8217;t have to redefine it or copy that code from some other class.<br />
Your class automatically gets that behavior from its superclass, that superclass<br />
gets behavior from its superclass, and so on all the way up the hierarchy. Your<br />
class becomes a combination of all the features of the classes above it in the<br />
hierarchy.</p>
<p>New Term</p>
<p>Inheritance is a concept in object-oriented programming where all classes are<br />
arranged in a strict hierarchy. Each class in the hierarchy</p>
<p>has superclasses (classes above it in the hierarchy) and any number of<br />
subclasses (classes below it in the hierarchy). Subclasses inherit</p>
<p>attributes and behavior from their superclasses.</p>
<p>At the top of the Java class hierarchy is the class Object; all classes inherit<br />
from this one superclass. Object is the most general class in the hierarchy; it<br />
defines behavior inherited by all the classes in Java. Each class further down<br />
in the hierarchy adds more information and becomes more tailored to a specific<br />
purpose. In this way, you can think of a class hierarchy as defining very<br />
abstract concepts at the top of the hierarchy and those ideas becoming more<br />
concrete the farther down the chain of superclasses you go. Most of the time<br />
when you write new Java classes, you&#8217;ll want to create a class that has all the<br />
information some other class has, plus some extra information. For example, you<br />
may want a version of a Button with its own built-in label. To get all the<br />
Button information, all you have to do is define your class to inherit from<br />
Button. Your class will automatically get all the behavior defined in Button<br />
(and in Button&#8217;s superclasses), so all you have to worry about are the things<br />
that make your class different from Button itself.</p>
<p>This mechanism for defining new classes as the differences between them and<br />
their superclasses is called subclassing.</p>
<p>Subclassing involves creating a new class that inherits from some other class in<br />
the class hierarchy. Using subclassing, you only need to define the differences<br />
between your class and its parent; the additional behavior is all available to<br />
your class through inheritance.</p>
<p>New Term</p>
<p>Subclassing is the process of creating a new class that inherits from some other<br />
already-existing class.</p>
<p>What if your class defines an entirely new behavior and isn&#8217;t really a subclass<br />
of another class? Your class can also inherit directly from Object, which still<br />
allows it to fit neatly into the Java class hierarchy. In fact, if you create a<br />
class definition that doesn&#8217;t indicate its superclass in the first line, Java<br />
automatically assumes you&#8217;re inheriting from Object. The Motorcycle class you<br />
created in the previous section inherited from</p>
<p>Object.</p>
<p>Creating a Class Hierarchy</p>
<p>If you&#8217;re creating a larger set of classes for a very complex program, it makes<br />
sense for your classes not only to inherit from the existing class hierarchy,<br />
but also to make up a hierarchy themselves. This may take some planning<br />
beforehand when you&#8217;re trying to figure out how to organize your Java code, but<br />
the advantages are significant once it&#8217;s done:</p>
<p>When you develop your classes in a hierarchy, you can factor out information<br />
common to multiple classes in superclasses, and then reuse that superclass&#8217;s<br />
information over and over again. Each subclass gets that common information from<br />
its superclass.</p>
<p>l</p>
<p>Changing (or inserting) a class further up in the hierarchy automatically<br />
changes the behavior of its subclasses-no need to change or recompile any of the<br />
lower classes because they get the new information through inheritance and not<br />
by copying any of the code.</p>
<p>l</p>
<p>For example, let&#8217;s go back to that Motorcycle class and pre tend you created a<br />
Java program to implement all the features of a motorcycle. It&#8217;s done, it works,<br />
and everything is fine. Now, your next task is to create a Java class called<br />
Car.</p>
<p>Car and Motorcycle have many similar features-both are vehicles driven by<br />
engines. Both have transmissions, headlamps, and speedometers. So your first<br />
impulse may be to open your Motorcycle class file and copy over a lot of the<br />
information you already defined into the new class Car.</p>
<p>A far better plan is to factor out the common information for Car and Motorcycle<br />
into a more general class hierarchy. This may be a lot of work just for the<br />
classes Motorcycle and Car, but once you add Bicycle, Scooter, Truck, and so on,<br />
having common behavior in a reusable superclass significantly reduces the amount<br />
of work you have to do overall.</p>
<p>Let&#8217;s design a class hierarchy that might serve this purpose. Starting at the<br />
top is the class Object, which is the root of all Java classes. The most general<br />
class to which a motorcycle and a car both belong might be called Vehicle. A<br />
vehicle, generally, is defined as a thing that propels someone from one place to<br />
another. In the Vehicle class, you define only the behavior that enables someone<br />
to be propelled from point a to point b, and nothing more.</p>
<p>Below Vehicle? How about two classes: PersonPoweredVehicle and<br />
EnginePoweredVehicle? EnginePoweredVehicle is different from Vehicle because it<br />
has an engine, and the behaviors might include stopping and starting the engine,<br />
having certain amounts of gasoline and oil, and perhaps the speed or gear in<br />
which the engine is running. Person-powered vehicles have some kind of mechanism<br />
for translating people motion into vehicle motion-pedals, for example. Figure<br />
2.3 shows what you have so far.</p>
<p>Figure 2.3 : The basic vehicle hierarchy.</p>
<p>Now let&#8217;s become even more specific. With EnginePoweredVehicle, you might have<br />
several classes:</p>
<p>Motorcycle, Car, Truck, and so on. Or you can factor out still more behavior and<br />
have intermediate</p>
<p>classes for TwoWheeled and FourWheeled vehicles, with different behaviors for<br />
each (see Figure 2.4).</p>
<p>Figure 2.4 : Two-wheeled and four-wheeled vehicles.</p>
<p>Finally, with a subclass for the two-wheeled engine-powered vehicles, you can<br />
have a class for motorcycles. Alternatively, you could additionally define<br />
scooters and mopeds, both of which are two-wheeled engine-powered vehicles but<br />
have different qualities from motorcycles. Where do qualities such as make or<br />
color come in? Wherever you want them to go-or, more usually, where they fit<br />
most naturally in the class hierarchy. You can define the make and color on<br />
Vehicle, and all the subclasses will have those variables as well. The point to<br />
remember is that you have to define a feature or a behavior only once in the<br />
hierarchy; it&#8217;s automatically reused by each subclass.</p>
<p>How Inheritance Works</p>
<p>How does inheritance work? How is it that instances of one class can<br />
automatically get variables and methods from the classes further up in the<br />
hierarchy?</p>
<p>For instance variables, when you create a new instance of a class, you get a<br />
&#8220;slot&#8221; for each variable defined in the current class and for each variable<br />
defined in all its superclasses. In this way, all the classes combine to form a<br />
template for the current object, and then each object fills in the information<br />
appropriate to its situation. Methods operate similarly: New objects have access<br />
to all the method names of its class and its superclasses, but method<br />
definitions are chosen dynamically when a method is called. That is, if you call<br />
a method on a particular object, Java first checks the object&#8217;s class for the<br />
definition of that method. If it&#8217;s not defined in the object&#8217;s class, it looks<br />
in that class&#8217;s superclass, and so on up the chain until the method definition<br />
is found (see Figure 2.5).</p>
<p>Figure 2.5 : How methods are located.</p>
<p>Things get complicated when a subclass defines a method that has the same<br />
signature (name, number, and type of arguments) as a method defined in a<br />
superclass. In this case, the method definition that is found first (starting at<br />
the bottom and working upward toward the top of the hierarchy) is the one that<br />
is actually executed. Therefore, you can intentionally define a method in a<br />
subclass that has the same signature as a method in a superclass, which then<br />
&#8220;hides&#8221; the superclass&#8217;s method. This is called overriding a method. You&#8217;ll<br />
learn all about methods on Day 7, &#8220;More About Methods.&#8221;</p>
<p>New Term</p>
<p>Overriding a method is creating a method in a subclass that has the same<br />
signature (name, number, and type of arguments) as a method in a superclass.<br />
That new method then hides the superclass&#8217;s method</p>
<p>(see Figure 2.6).</p>
<p>Figure 2.6 : Overriding methods.</p>
<p>Single and Multiple Inheritance</p>
<p>Java&#8217;s form of inheritance, as you learned in the previous sections, is called<br />
single inheritance. Single inheritance means that each Java class can have only<br />
one superclass (although any given superclass can have multiple subclasses).</p>
<p>In other object-oriented programming languages, such as C++, classes can have<br />
more than one superclass, and they inherit combined variables and methods from<br />
all those classes. This is called multiple inheritance. Multiple inheritance can<br />
provide enormous power in terms of being able to create classes that factor just<br />
about all imaginable behavior, but it can also significantly complicate class<br />
definitions and the code to produce them.</p>
<p>Java makes inheritance simpler by being only singly inherited.</p>
<p>Interfaces and Packages</p>
<p>There are two remaining concepts to discuss here: packages and interfaces. Both<br />
are advanced topics for implementing and designing groups of classes and class<br />
behavior. You&#8217;ll learn about both interfaces and packages on Day 16, &#8220;Packages<br />
and Interfaces,&#8221; but they are worth at least introducing here.</p>
<p>Recall that each Java class has only a single superclass, and it inherits<br />
variables and methods from that superclass and all its superclasses. Although<br />
single inheritance makes the relationship between classes and the functionality<br />
those classes implement easy to understand and to design, it can also be<br />
somewhat restrictive-in particular, when you have similar behavior that needs to<br />
be duplicated across different &#8220;branches&#8221; of the class hierarchy. Java solves<br />
this problem of shared behavior by using the concept of interfaces, which<br />
collect</p>
<p>method names into one place and then allow you to add those methods as a group<br />
to the various classes that need them. Note that interfaces contain only method<br />
names and interfaces (arguments, for example), not actual definitions.</p>
<p>Although a single Java class can have only one superclass (due to single<br />
inheritance), that class can also implement any number of interfaces. By<br