08/10/2018. Liceo delle Scienze Applicate. Computer Science. Fourth course

Size: px
Start display at page:

Download "08/10/2018. Liceo delle Scienze Applicate. Computer Science. Fourth course"

Transcription

1 08/10/2018 Liceo delle Scienze Applicate Computer Science Fourth course Topics: HTML CSS JavaScript Setting up a Local Server PHP MySQL and Relational Databases Appendices

2 Thanks to Jeffrey Way for a lot of inspiration Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. Brian W. Kernighan

3 Topics CSS

4 What, if anything, is the Internet? When it comes to the Internet, there is a lot of confusion about words and concepts. It would probably be wise to start with some terminology. The Internet, though a proper name, is not a person: it is introduced with a definite article, and is usually capitalized. The Internet is neither a network nor the network: it is a network of networks 1. Computers directly connected to the Internet are called servers 2. Computers (possibly, our own) connected to Internet servers are called hosts or clients. The World Wide Web (www, or W3) is not the Internet: it is a system of distributed resources 3, stored on computers called Web servers 4. It is one of many services 5 available through the Internet. The content of the W3 is often described in plain text documents, called Web pages. Web pages are identified by their Web address (also called Uniform Resource Locator, or URL). Mnemonic URLs, like are normally easier to remember than the actual numeric ones, like (the official Web site of the NHL, A Web page may contain references to non-textual material (images, sounds, videos, ), or links to other pages 6. These characteristics make it part of a hypertext. A Web site is normally something more than a Web page: it may comprise several Web pages and other material, under a common address. A Web page is usually a document written in HTML (Hypertext MarkUp Language). A HTML document is a plain text, usually written according to a definite set of rules. A Web page is published when it is accessible on a server. A Web browser is a program that can retrieve and display a Web page, following the rules of HTML. Web browsers can also open and display Web pages stored locally (i.e.: on the same computer). The Internet and HTTP are about connectivity The Web and HTML are about content Is HTML a language? HTML is not a programming language: it is a description of the content and appearance of a Web page. The verbal content is written in plain text, while other resources are referred to by their URL. The appearance of text may describe such characteristics as color, spacing, and size; other elements may be described in relation to their page surroundings (background, margins, placement ). Anything regarding appearance is called style. Content, organization, and style are described with annotations called markups. Browsing the Internet A browser must be able to display the content of a Web page, following the rules of HTML. Different browsers, though, are often not consistent: it could be a different rendering of the same page, or some HTML features not supported by all browsers. This imperfect standard is the result of wild development during the initial years of the Web, before the advent of regulating bodies, and may still occasionally haunt Web developers and users. 1 The Internet is usually defined as a networking infrastructure, comprising many interconnected autonomous networks. No one actually owns the Internet, and no single organization controls it in its entirety. There are some governing bodies, but they are voluntarily accepted by all the member networks. 2 Normally, servers belong to ISPs (Internet Service Providers); however, any computer with a publicly recognizable address can be defined as a server. 3 Documents, images, sounds, videos, and other files. 4 The WWW is an information-sharing model (content) built on top of the Internet (infrastructure). 5 Other being, for example, , remote storage, file transfer, and e-commerce. 6 Also called hyperlinks (hot spots which can be activated via a mouse click, a key press, or a screen touch).

5 Give us the tools, and we will finish the job 7 HTML is a static affair: once the content and style of the page has been described, the browser renders it, and little can be changed. Some dynamicity can be provided in the form of hyperlinks: when the user hovers the mouse over one (in the example, an image), the mouse icon transforms into a hand (or some other indicator), an explaining message may appear, and a mouse click instructs the browser to retrieve the corresponding resource. The link can also be in the form of a phrase, a button, or other HTML objects. Being static is an intrinsic limit of HTML, which was developed primarily as a means to deploy text, during the first steps of the W3 (around 1990). Its roots can be found in the control characters for printers that were used in the good old days, when printers had only a few formatting options (bold, underlined, and italic) to enhance text output 8. In HTML, bold can be activated with <b>, italic with <i>, underlined with <u> (and deactivated with </b>, </i>, and </u>, respectively). These descriptors are not encouraged any more, as more advanced style definitions have been introduced. Dynamic Web pages Over the years, a need for interaction has arisen, which has made HTML pages awkward. Many add-ons have been tried, but nowadays the most common implementation of dynamic Web pages is done by adding snippets to Web pages, typically using two languages: JavaScript 9 and PHP 10. The result of this interaction is sometimes called DHTML (Dynamic HTML). Some key concepts: JavaScript is not Java: they are totally different beasts; of course, it may be possible, as some have speculated, that the name JavaScript was chosen to exploit the popularity of Java; JavaScript is used for client-side programming: it can interact with a Web page and its elements; JavaScript does not process the actual page, nor the actual data, stored on the server: it works on copies; PHP is used for server-side programming: PHP pages can process data and files stored on the server; PHP, being a pre-processor, is much harder to master: a page written in PHP must send HTML code to the browser, whereas a JavaScript snippet can be totally independent from HTML code; JavaScript and PHP often work together, under a common roof provided by HTML. One thing we don t need to worry about is the availability of tools for the production of Web pages: there are scores of such programs which are free or open-source. This is undoubtedly one of the advantages of the Web, which has cut down heavily on programming costs. Two very popular (and open source) tools have been used to write the pages for this course: A text editor (Notepad++, obtainable at A Web server engine (actually, there several bundles: ampps, Xampp, EasyPHP, all free). Linking to another page Both are readily available, free of charge. In particular, the Web server bundles have other features for PHP developers (most notably, capabilities for data management). 7 Winston Churchill (February 9, 1941). 8 At least two different formatting programs were called runoff (one, written around 1964, was spelled RUNOFF in capital letters; another, written some years later, was a staple of small computer systems in the 70 s). 9 First developed in 1995 by Brendan Elch with the name Mocha, soon changed to LiveScript. The name JavaScript was adopted after receiving trademark rights from Sun Corporation. 10 PHP stands for PHP Hypertext Preprocessor (with some variations on punctuation and articles), a self-referencing description. According to the PHP official website, its creator, Rasmus Lerdorf, had called his original projext Personal Home Page Tools. The acronym was changed with version 3 of PHP, circa Source:

6 Our first Web page Browsers were originally designed to process text, the first form of Web content. The simplest Web page, actually, can contain just plain text. With any text editor (even Notepad), it is easy to create a text file. Suppose the following is saved as plain.txt: When we open the same file with any browser (File/Open/Browse), we will see exactly the same text, no more, no less. Browsers make assumptions: without any formatting options, the only thing they can display is plain text (a no frills behavior). Clearly, while this can be done, by no way it should: besides making a poor rendering, it misses all the characteristics of hypertexts (images and links, to name just two). With the help of a better editor, it is easy to create a sample HTML document, which will show the use of markups, also called tags. The document is still a text file, but it must be saved as a HTML document (with extension either.htm or.html), or the browser would not recognize (and render) the tags. As our first example, we will introduce a simple, basic HTML document, containing a couple of lines of text, with the main purpose of taking a look at some tags. As it can easily be seen, tags are identified by angle brackets (or chevrons). Some tags are self-contained, such as the two directives (marked with [d]), which contain all the information in the tag itself (respectively, the document type and the character set used for coding). Most tags, though, work in couples, defining a starting and an ending point. For example, the rulebook says that a HTML page comprises two parts, a heading and a body (the heading is for directives and specifications, the body is for content): so, we will see two <html> tags, containing two <head> tags and two <body> tags, where the ending tag is recognizable by a slash character. It must be said that some people take their HTML code very seriously, as the girl in the picture shows. The example also contains our first style tag, which is about emphasis: any text between <i> and </i> will be rendered in italic. Here is the code, accompanied by a brief explanation: HTML <!doctype html> <html> <head> <title>example</title> <meta charset="utf-8"> </head> <body> First line of text <b>second line of text</b> </body> </html> far Meaning document type [d] start of document start of heading appears in the browser title bar info about character coding [d] end of heading start of actual content plain text <>... </> (<b>=bold;</b>=end) end of actual content end of document When we open this file with a browser, the result will offer a couple of small surprises: What happens is that HTML does not provide automatic spacing and branching, so the following apply: A sequence of blanks collapses into a single whitespace (unless otherwise specified: more on this later); A line feed in the HTML code will not be rendered (at least, not automatically). A true space can be inserted with the mnemonic (a little clumsy indeed, coming with ampersand and semicolon: anyway, it stands for non-branching space). A true line feed, on the other hand, needs a tag of its own, <br> (meaning branch or break, depending on whom we refer to).

7 Divide et impera: headers and paragraphs Before proceeding, a piece of advice: DON T DO THIS!!! Browsers make bad assumptions, too: a page will be rendered even if there is confusion in the tag sequence (as the example shows). While this can be done, by no way it should: it is best to maintain good practices. <head> <body> </head> content </body> It is now time for the most significant HTML text elements, plus some very basic formatting. One useful element is the header (not to be mistaken for the <head> section), which is used as a sort of title for the page or parts of it. It can also be very useful in SEO 11, as most search engines look for structure and emphasis. There are 6 categories of headers: <h1> through <h6> (in decreasing order of size), but, in practice, only <h1> (page heading), <h2> (section heading), and, perhaps, <h3>, are actually used, the smaller ones being considered a waste of time. Another common element is the paragraph, which is a handy way of packaging text (and other content): many experts encourage the use of paragraphs, as they consider leaving stray text in the page an example of sloppy coding 12. An example of headers and paragraphs is the following: <h1>my website</h1> <p>the first paragraph</p> <p>the second paragraph</p> Headers and paragraphs are block elements: this means that they are separated from the rest of the page by automatic line breaks. Inline elements only branch when they reach the end of the screen. Some very common style modifiers are used to alter the appearance of text. As previously hinted, some have been along for years: boldface, italic, underlined. Historically, the corresponding tags contain the initial of the styles; over time, though, other tags have been introduced, called semantic tags (that is, they carry their meaning, instead of being just markers). Besides being somewhat clearer in their purpose, the use of these tags is encouraged because they can be interpreted by speaking programs for the blind. As the older tags are still widely used, though, it is best to know them. Here is a very brief summary: Physical tag Semantic tag Meaning <b> <strong> boldface <i> <em> italic <u> underlined <mark> highlighted The following content does not make much sense (unless one knows about former baseball great George Brett), it is only intended to show some of these tags. As the second line shows, tags can be combined for multiple effects (bold and italic): <h1>quoting George</h1> <p>in the lobby of the <b><i>hotel</i></b> <mark>at midnight</mark></p> <h2>the bottom line</h2> <p><u>who's</u> the <em>pitchers</em> in this <strong>game</strong>?</p> The rendering is forgettable, but it dose show our code in action; yet, one golder rule is that text styles are effective when used sparingly. BEWARE!!! DON T JUMP THE GUN Although these tags can be found in many Web pages, there are other, more effective ways to style a HTML document. More on this later. 11 Search Engine Optimization: it refers to affecting the visibility of a website, usually in order to make it appear among the first results of a Web search. 12 Once again, one can get away with a lot of badly done things in HTML but that is not the way.

8 Lists Lists are widely used, and rightly so, the computer being an organizer of information. They have some unexpected (and useful) possibilities, but for now we will explore only the basics. Don t do like this A list could be described in plain text, but, as we already know, HTML does not automatically render line feeds: what we need is the appropriate tag. The <br> tag may stand for break or branch; older manuals described it as an unconditional branch. Using line breaks to build lists, however, calls for very sloppy code, due to its total lack of customization, and should be avoided at all costs: Commonly used lists First item<br> Second item<br> Third item<br> The most common list is probably the one with no specific item numbering (unordered list). The list itself is introduced with the <ul> tag, and each element with <li> (list item) tag. It takes little imagination to figure out the tag for the numbered (ordered) list, which is <ol>. Items in unordered lists are preceded by a bullet symbol, while in ordered lists they are preceded, quite naturally, by a number. Examples: <ul> <li>mathematics</li> <li>physics</li> <li>computer Science</li> </ul> <ol> <li>mathematics</li> <li>physics</li> <li>computer Science</li> </ol> Definition lists These lists are not very common, but they are encouraged for simple explanations, as well as for semantics 13. Definition lists use three tags: <dl> (definition list), <dt> (definition term), and <dd> (definition description). An example of the suggested usage of definition lists: <dl> <dt>vampire</dt> <dd>mammal of the order Chiroptera</dd> <dd>undead creature who sucks blood</dd> <dd>dishonest accountant</dd> <dt>shark</dt> <dd>fish of the clade Selachimorpha</dd> <dd>aggressive business operator</dd> <dd>nickname of former striker Joseph Jordan</dd> </dl> 13 This is a very hot topic among HTML developers, as many of them are struggling to get some order in the mass of sloppy and unreadable code that pervades the Web.

9 Quotations Given the academic roots of HTML, it comes to no surprise that there are several tags dedicated to quoting. Their styling are only slightly different, and, as it may be suspected, they are classified semantically. Tag Meaning <blockquote> A long quotation (block element, normally indented) <quote> Short inline quotation (not indented) <q> Short inline quotation, enclosed between quotation marks <cite> Inline title of a work, rendered in italic As an example, we will use the very table above, adding a line break after each inline element (that is, all except the first one, <blockquote>): <blockquote> A long quotation (normally indented) </blockquote> <quote> Short inline quotation (not indented) </quote> <br> <q> Short inline quotation, enclosed between quotation marks </q> <br> <cite> Title of a work, rendered in italic </cite> <br> The result of this: As we can see, the quotation marks (or inverted commas, as the British call them) are actually guillemets 14 : Opening guillemet (Alt 174) «Closing guillemet (Alt 175)» Of course, quotation marks can also be inserted directly in the HTML code (single or double: '"). There are other quotation marks available, though the syntax is a little clumsy, as a single symbol is represented by a mnemonic (similar to the non-branching space), which comprises several characters. An incomplete list is the following, where we can see the difference between straight and rounded quotation marks: " " double quotation mark (straight) &apos; ' single quotation mark (straight: apostrophe) double quotation mark (rounded) single quotation mark (rounded) guillemets (angular quotes) single guillemets (angular single quotes) So, the <blockquote> element could be simulated in the following way: «Short inline quotation, enclosed between quotation marks» 14 The name derives from a 16-century French printer named Guillaume Le Bé ( ). In English, they are also called angle quotes or French quotation marks.

10 Attributes Many tags support additional clauses, called attributes 15, which are enclosed in the same angle brackets as the referred element. In the following example, the title attribute specifies the tooltip 16 to be displayed when hovering with the mouse over the element: <cite title="<title> tag example"> Title of a work, rendered in italic </cite> Attributes being a fundamental component of HTML, it may be useful to remember a few things: Attributes come in name="value" pairs, as in the previous example; Lowercase spelling for attribute names is encouraged; Quotation marks can be either double style or single style If the attribute value is a single word or number, quotes can even be omitted. Two attributes can identify elements. Since id is recognized by JavaScript and name is recognized by PHP, it is very common (and wise) to specify the same unique value for both, to avoid confusion: <p id="first" name="first"> All quotation tags support the cite attribute, not to be mistaken for the <cite> tag. It can be used by search engines to get additional information about the quotation, or by Web crawlers 17 to verify source acknowledgement. An example is the following, which is an excerpt from the song Rosetta: <blockquote cite=" Well my little girl is a sweet little girl<br> but she does things make your eyebrows curl.<br> You let her loose on a Friday night<br> you know it's gonna end in a fight.<br> Rosetta drinks her whiskey neat<br> she gets in a fight and she might get beat.<br> So I go round on the Saturday night<br> and ask her if she feels allright.<br> </blockquote> <cite>rosetta (G.Fame, A.Price)</cite> The rendering is a little awkward, as the relative position of the elements is reversed with respect to the norm. One suspects that browser could be a little smarter than this, but we don t need to worry. Everything can be adjusted with a little bit of style (more on this later). This is the default rendering: 15 Attributes provide further information about elements, or styling options. 16 A tooltip is an additional text box, normally used to give a hint about an element. 17 Also called Web spiders, these programs scan the Web for purposes such as Web indexing and Web content retrieval; many use them to look for unauthorized material

11 Images, and more The Web is a multimedia 18 environment: it has brought forth a flurry of different ways to carry information 19, so much so that a Web page without at least some graphics would be considered a relic from the past 20. Images are not actually inserted into Web pages, but linked to them through their URLs. A holding space is created with the <img> tag, which supports, among others, the height and width attributes (in pixels): <img src="mario1.bmp" height="25"> The alt attribute provides a text message to be displayed in place of a missing image, or in case images are disabled on a host browser: <img src="sub/mario1.bmp" alt="missing image"> Most browsers, however, use some broken link icon to signal missing images, such as: One thing that is strongly advised against is a hot link to images in other Web sites; besides being rather impolite, that would make the other people pay for the band, and legal action might follow. <img src=" Embedding audio files is a little trickier, but at long last modern browsers provide for it with this tag: <audio controls autoplay> <source src="five Foot Two.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> Additional <source> tags may link to clips in other formats. The line of text is useful as an error message 21, when the clip cannot be played (as in obsolete browser, or when sound has been disabled). Not all browsers support this tag. There is at least one project providing some useful functions (html5media by Dave Hall, a Web developer from Cambridge, UK). As they are written in JavaScript, they can be included in a Web page with the following link (suggested in the <head> section): <script src=" The <audio> tag supports some attributes, such as: autoplay the clip will start playing as soon as it is loaded (loading the clip could take a little longer than loading the page, so it is likely that there will be a small time gap before the clip starts). controls Audio control (play/pause, volume, etc.) are displayed: this makes sense, as it is very annoying being unable to stop the clip, or to adjust the volume. loop muted The clip will be repeated as soon as it is finished (not advisable, as it can be annoying). Less stupid that it may seem, as the user might prefer to turn on the volume voluntarily; then again, it makes more sense to avoid the autoplay clause. Similar considerations apply to video clips, for example: <video controls autoplay> <source src="hot Stuff.mp4" type="video/mp4"> Your browser does not support the audio element. </video> 18 Originally spelled multi-media, this term refers to a combination of text, audio, images, animations, video, and user interaction. In the 1990s, this expression meant a huge difference from the crude video display which used to be the norm, so there was a rage over it (and possible overuses). Now it is taken for granted. 19 Purists lament that the presence of useless images and videos clogs the Internet for no apparent benefit, except for those who sell expensive networking equipment. 20 There are exceptions, as some developers give preference to faster downloading over fancy graphics. See Jakob Nielsen at: 21 Somebody once wrote: to err is human, to give clear error messages is divine.

12 Links The Web would not be what it is without the capability of linking pages together. A link (or hyperlink) has two ends, called anchors, representing two separate resources, and a direction, as it starts at the source anchor, located in a Web page, and points to the destination anchor. Normally, destination anchors are other Web pages, but any resource can be addressed (images, sound bites, video clip, ) Not surprisingly, links are provided through tags called anchors (<a>...</a>), Before exploring the mechanisms of links, we should add a little complexity to our project, in order to test several situations. We will save two HTML documents in a top-level folder, two more in subfolders, and throw in a couple of images. There is a reason for calling certain pages with the same name index.html (in different folders, of course), as this name can represent the entire folder where it is stored. WARNING!!! The top-level folder is called home folder only for reference: in a local environment any folder will work, while on a remote server it does not even have a name (it is reached via its URL). As is probably known, folders are organized in a tree-like structure (actually, computer trees are upside down), defining a hierarchy of levels. This way, couples of folders can be classified as parent and child (when they are on different, adjoining levels) or as siblings (when children of the same parent). The family analogy does not extend to grandparents and grandchildren, nor beyond: distantly related folders are called ancestors or descendants. No cousins exist, either. Within this infrastructure, it will be possible to make links to a number of resources, for example: The page itself 22 An element in the same page Another page in the same folder or in a different one An element in another page (more on this later) An image (or some audio or video) in any folder, albeit this is this is hardly ever done As an experiment, the following links should be added to the index.html page of the main folder: This is only an example which shows how to insert a <p> visit <a> me </a> <p> link in a page. Nothing actually happens. The href (hypertext reference) attribute <a href="#"> me </a> contains the URL of the link. The symbol # (known as the pound sign), is the symbol for this page. <a href="#" target="_blank"> me </a> The target page will be opened in a new browser tab. We will notice that, as the page is opened (or re-opened), the address line shows something like: file:///c:/web/test.html# or C:\web\test.html# (depending on the browser). After the # symbol representing the same page, supplemental data may be present. The syntax of linking uses these features: The current folder is identified with the symbol. The parent folder is identified with.. Different levels are separated by / (forward slash) 22 This is not as stupid as it may seem: interaction often requires that the same page be loaded again, possibly with some data to process.

13 Addressing other pages The first couple of examples are references to images. This, though possible, is a dead end, as the browser will display it and stop there, without a way to revert to the original page, except by clicking on the back button of the browser: the only use of such a link could be in those rare cases when the need arises to show an image in full resolution. The key is the href attribute, which can contain text and/or images: <a href="mario2.bmp"> image </a> <a href="sub/mario2.bmp"> image in subfolder </a> <a href="sub/mario2.bmp"> <img src="sub/mario2.bmp"> </a> Before listing several possible links, one word of warning: links to folders have different effects when working locally: the browser will not open the index page, but the whole folder, in the same way as it would with resource explorer programs (i.e.: navigating through the file system). For this reason, those examples marked with an asterisk are intended only for reference, as they would work only on published pages (or in a PHP environment, which requires at least a local server). Reference on the home page to itself: *<a href="."> same page </a> Reference to another page (and the corresponding backward link): <a href="about.html"> about me </a> (in index.html) <a href="index.html"> back to home page </a> (in about.html) Reference to another page in a subfolder (and the corresponding backward links): *<a href="sub"> page in subfolder </a> <a href="sub/index.html"> page in subfolder </a> *<a href=".."> back to home page </a> (also: "../") <a href="../index.html"> back to home page </a> Reference to another page in a sibling subfolder (esample: from sub to img, and back): *<a href="../img"> sibling subfolder </a> (sibling folder "img") <a href="../img/index.html"> sibling subfolder </a> <a href="../sub/index.html"> backward link to "sub" </a> Links are treated by browser in a standard way (which can be modified with a little styling): Unvisited links are underlined and blue; Visited links (i.e.: to pages page that has already been accessed) are underlined and purple; Active links (during the time are being clicked upon) are (not always) underlined and red. BEWARE!!! In published Web pages, references must contain the full URL, and sometimes are introduced by the name of the protocol in use (though this is not necessary for http): <a href=" our school </a> <a href=" our school </a> <a href=" reserved </a> Web pages are accessed through two protocols: http (HyperText Transfer Protocol), identified by port number ; https (HTTP over Secure Socket Layer), identified by port number The default protocol is http; other protocols must be included in the URL, as in this (totally fictitious) example of a file transfer site: ftp://not.true.com/games 23 Port numbers are used at ISO-OSI layer 4 (Transfer) to identify the service (remote job entry, mail, file transfer, ). Port 80 belongs to the set of well-known (or standard) ports, which comprises the most common Internet services. 24 Besides using a different (also well-known) port number, https offers encryption and authentication features for security issues, especially important when dealing with corporate or financial data.

14 HTML JavaScript

15 Styles So far, we used just a minimum of styling for our examples. Actually, there is a world of ways to add a personal touch to Web content, as the appearance of any element can be easily changed: the only problem is that there are so many attributes that it is easy to get confused. Styling is usually done with CSS (Cascading Style Sheets 25 ) files, which are written in plain text and stored separately from the HTML documents, following the golden rule: While it is possible to embed style attributes into HTML code, it is a deprecated habit 26, for two good reasons: Style attributes tend to clutter the content, making it difficult to edit the document; Being two different things, it is only wise to keep them distinct. The <link> tag should be included in the <head> section of the document. In this example, the link is to a file saved as style2.css 27 (the choice of names is free, not the extension): <link href="style2.css" rel="stylesheet" type="text/css"> As we could expect, if the CSS file is not available, browsers will use their default settings. It is also possible to link several CSS files, depending on the complexity of the project. To explain the syntax of style specifications, it is best to just start with some examples. The simplest way to proceed is to list element tag names (such as h1 or p), followed by their attributes enclosed between curly braces: this causes all the elements of a certain type to be rendered as specified in the style. For example, we might prefer our headings to be in red, with a wider offset from the left margin of the page than normal; as for paragraphs, we might decide to give them a raised border (ridge). While the first choice can be described as odd (as most page headings are black), the second one is almost insane, as all the paragraphs of the document would be rendered with the same border (while we usually want to restrict the effect to selected elements, as we will see). Content of "style2.css" : h1 p margin-left color border width : 80px; : red; : ridge coral 3px; : 200px; Content of a document linked to "style2.css": <h1>my website</h1> <p>the first paragraph</p> <p>the second paragraph</p> The settings are rather self-explanatory: margin-left width color offset (from left side) dimension text color Of course, there are other similar attributes, such as margin-right or height (more on this later). In fact, the rendering is forgettable, and would be even more horrendous in a page with many paragraphs. 25 The term cascading refers to the fact that all the style documents linked to a HTML document are processed in sequence, making it possible to override previous specifications. 26 Including styling specifications in the HTML code may still be useful, provided it is done sparingly. 27 The.css extension of the file is strongly suggested, so that editors may apply helpful syntax coloring.

16 In another example, which makes more sense, we could adjust the offsets for quotations, so as to make our Rosetta lyrics more readable 28. Some lines contain comments (see more on comments below): blockquote margin-left : 20px; /* lyrics */ cite margin-left : 200px; /* title and authors */ <blockquote cite=" Well my little girl is a sweet little girl<br> but she does things make your eyebrows curl.<br> You let her loose on a Friday night<br> you know it's gonna end in a fight.<br> Rosetta drinks her whiskey neat<br> she gets in a fight and she might get beat.<br> So I go round on the Saturday night<br> and ask her if she feels allright.<br> </blockquote> <cite>rosetta (G.Fame, A.Price)</cite> When paragraphs need some emphasis, it is possible to affect both the foreground and background colors 29 : p border : ridge steelblue 3px; color : firebrick; background-color : lightyellow; <p>highlighted paragraph</p> In CSS, comments are enclosed between a pair of slash/asterisk delimiters (/* and */). There are no singleline comments (as in // or #) and this is unfortunate, as the most common use of comments in CSS is to put aside some settings when trying new ones (in case something needs to be undone): instead of just commenting out an attribute and then proceeding to try the effect, one is required to add both comment delimiters, thus wasting a couple of seconds 30. The following example shows what happens when trying new color combinations: /* Short comment */ /* */ This comment spans several lines p /* color : red; */ color : blue; background-color : yellow; The comment delimiters in HTML are <!-- and -->, which, if possible, is even worse: <!-- <p>this paragraph has been commented out</p> --> 28 This also would make them better. 29 See next page for an exhaustive collection of color names. 30 Which is more than it may seem, as the number of trials, on a day of work, sums up a considerable amount of time.

17 Any colour you like 31 HTML supports some 150 color words, which are summarized in the following table (also in Appendix B): aliceblue darkorange indigo mediumpurple rosybrown antiquewhite darkorchid ivory mediumseagreen royalblue aqua darkred khaki mediumslateblue saddlebrown aquamarine darksalmon lavender mediumspringgreen salmon azure darkseagreen lavenderblush mediumturquoise sandybrown beige darkslateblue lawngreen mediumvioletred seagreen bisque darkslategray lemonchiffon midnightblue seashell black darkslategrey lightblue mintcream sienna blanchedalmond darkturquoise lightcoral mistyrose silver blue darkviolet lightcyan moccasin skyblue blueviolet deeppink lightgoldenrodyellow navajowhite slateblue brown deepskyblue lightgray navy slategray burlywood dimgray lightgrey oldlace slategrey cadetblue dimgrey lightgreen olive snow chartreuse dodgerblue lightpink olivedrab springgreen chocolate firebrick lightsalmon orange steelblue coral floralwhite lightseagreen orangered tan cornflowerblue forestgreen lightskyblue orchid teal cornsilk fuchsia lightslategray palegoldenrod thistle crimson gainsboro lightslategrey palegreen tomato cyan ghostwhite lightsteelblue paleturquoise transparent darkblue gold lightyellow palevioletred turquoise darkcyan goldenrod lime papayawhip violet darkgoldenrod gray limegreen peachpuff wheat darkgray grey linen peru white darkgrey green magenta pink whitesmoke darkgreen greenyellow maroon plum yellow darkkhaki honeydew mediumaquamarine powderblue yellowgreen darkmagenta hotpink mediumblue purple darkolivegreen indianred mediumorchid red Not surprisingly, an element specified as transparent will not be visible (though it will occupy page space). It is also possible to specify colors with their hexadecimal values (two digits for red, two for green, two for blue), or with their decimal values (three integers, ranging from 0 through 255) with the functions rgb() or rgba() 32. Text color, as we have seen, is set through the color attribute. The following, regarding the background color, are (almost) equivalent: q background-color: crimson; q background-color: #dc143c; q background-color: rgb(220,20,60); q background-color: rgba(220,20,60,0.5); Opacity samples (0.2, 0.4, 0.6, 0.8, 1.0), from 31 The Dark Side of the Moon (Pink Floyd, 1973). This explains the British spelling. 32 The function has a fourth parameters, which specifies the so-called alpha opacity of the element. Accepted values for the opacity span from 0 (transparent) to 1 (opaque). There is another, more pervasive, attribute, aptly named opacity. For more on opacity, see:

18 Summary on appearance (colors and borders) Colors and borders determine how elements stand out, so it may be worth stopping for a brief summary. Remember that any element can be styled (<body> or anything else). body color background-color background-color background-image visibility : ccc; : bbb; : rgba(r,g,b,o); : url(zzz); : hidden; See next page for the setting of the background as an image (where the zzz between the parentheses should be an actual image URL, like img/mario11.bmp). In the following examples, the colors used in the settings are explicitly written in the screenshots. Some settings are not very wise, as when text and background colors are too similar. Do NOT write ccc, bbb, zzz, r, g, b, o in the CSS: these are only placeholders for actual values. For colors, use either values (#dc143c) or mnemonics (crimson). Horrendous combinations are also to be avoided. Avoid combinations used mainly in porn sites (red on black) or in poorly designed ones (vomit yellow backgrounds, used in too many sites, amongh which on black..vomit yellow. A very dark background can be used to highlight some sections of the page, but it is not recommended for the whole body, as the overall readability would be very poor, not to mention fatiguing. Some combinations can be obtained by a shrewd use of opacity. Then again, it is hard to see the reason for wasting time with opacity, when a more proper color could be chosen in the first place. For some advice on how not to design Web pages, see, among others, a couple of sites: catb.org/esr/html-hell.html or Transparent backgrounds are used when an element should be mingled with the container, in cases where the differences between the two, though present, are not too extreme. There is a logic for setting the text color as transparent. For one thing, some elements could be on the page only to be used by search engines. A more subtle usage can be the addition of invisible elements to accommodate the quirks of different browsers (which at times can be very frustrating for the developer). Hiding elements can also be done, in a simpler way, by setting the visibility attribute to hidden, while the default value is visible. This way, one disposes with a possible colored background. One last note on spelling: gray and grey, which appear in several color names, are now interchangeable. In the first version of CSS, the only accepted spelling was gray (the preferred American spelling, while grey is used in the UK and in the former British colonies).

19 Web pages sometimes use images in the background. One common technique is to use a small image, which the browser repeats until it covers the entire page. This can also be set with the background-repeat attribute, which has a default value of repeat (and can be separately set horizontally and vertically, with repeat-x and repeat-y). Another possible setting is no-repeat, which forces the browser to use a single occurrence of the image. body background-image : url(mario1.bmp); background-repeat : repeat-x repeat-y; /* also: repeat */ background-position : center; background-attachment : fixed; /* when scrolling */ The image should not be too bright, or it would be nearly impossible to decipher the page, so it is very common to use a watermarked version of some image. Another common option is to use a texture image, which is repeated more or less seamlessly, as in the third and fourth (double gradient) example: Image file no-repeat repeat Double gradient mario1.bmp doublegradient.png mario11.bmp ice.jpg The background-size attribute allows the specification of exact dimensions, but this can be ineffective when the user resizes the browser window. One common practice is to use an image containing a fading effect, then have the browser expand it to the whole page by setting the attribute to cover. The effect is not complete in extreme cases, as when the user shrinks the window to ridiculously small dimensions, but this can be ruled out, since in that case hardly anything would be visible: body background-image background-repeat background-size : url(fade.jpg); : no-repeat; : cover; The background-size attribute settings to specific dimensions (horizontal and vertical, as in 200px 200px or 50% 50%) or to contain, (similar to cover, but restricted to the actual content), are seldom done, as some part of the screen may remain white. BEWARE!!! A fading background is only effective when the page does not overflow the screen (or when it does, but not by much). Very long pages (for example, those which contain long lists of data) are better rendered with a solid (uniform) background, or with a double-gradient repeating image.

20 Special attention has been given to borders, which are commonly used to enhance some elements. The border style can be set in the simplest way (width, style, color, in any order), as follows: img img border border : ridge coral 5px; : solid blue 2px; Incidentally, the second setting is the default for anchor images, changing to purple for visited links. It is possible to be more specific with elementary attributes: border-width # (e.g.: 5px) exact dimension thin medium (the default) thick border-style While none simply does not show a border, 3D effects are the most glamorous: groove, ridge Only the border is affected inset, outset The whole element is affected These effects are rendered by splitting the border in half, each with different colors. It is suggested to avoid excesses (as the 30 pixels below), using values between 4 and 8 pixels. Not quite interesting are the simplest styles: dotted, dashed, solid, double These attributes can even be set by listing the values of the four border sides (respectively: top, right, bottom, left), as in: border-width : 4px 8px 12px 16px; /* t r b l */ Styling borders can reach extreme detail, though it is hard to see any reason to do that: border-top border-top-color border-top-style border-top-width border-right border-right-color border-right-style border-right-width border-bottom border-bottom-color border-bottom-style border-bottom-width There is also an attribute which specifies how to render the angles of an element: border-radius : 10px; border-radius : 5%; border-left border-left-color border-left-style border-left-width When border-radius is set to a value of 50% or more, we obtain a perfect ellipse, which is not advisable, as this may cut off some content (the example is from the ubiquitous Rosetta):

21 Other elements The word paragraph conveys a definite meaning, that of a contiguous and homogenous block of text and related information. Actually, semantics is not a strong point on Web pages, as many developers (especially the rabble) often produce sloppy, quick-and-dirty code, and could not care less about meaning. Yet, there is only to gain in following good design practices: in computer science, most of the time is spent in maintaining code 33, and a little attention to details can drastically cut down debugging time. This said, it only makes sense the presence of a container element with no definite semantic classification, whose main use is to organize a HTML document in several distinct areas. This meaningless container is the <div>, an all-purpose bucket which may contain miscellaneous information, with the ultimate purpose of grouping related content. Most users are indeed frustrated when they try to find out how to interact with a cryptic Web page 34 : a good, logical layout is priceless, and well-designed DIVs may help in getting it done. Outline of a Web page with a logical organization DIVs, like paragraphs and blockquotes, are block containers, as they are normally separated from the rest of the page by line breaks. In order to organize a page in sections, some styling is necessary (more on this later). Of course, DIVs can (and very often will) contain other elements, such as paragraphs, blockquotes, and even other DIVs. And nothing stands against a paragraph containing a DIV, provided the project is clear and simple 35. Another commonly used tag is the span, which is suggested for short passages of text, presumably to add some effects: in this case, a different color and a doubly-sized font. The following example also shows a technique called inline styling, which can be useful at times (but should be used sparingly): <p> </p> <img src="mario1.bmp">mario <span style="color:red; font-size:200%"> likes </span> fish<img src="sushi.gif"> 33 This is one of several 80/20 rules that abound in this trade: this one says that programmers spend roughly 80% of their time revising, upgrading, and correcting their work, and only 20% in producing new material. Clearly, sloppy code takes even more time to decipher, and adds to the less productive part. 34 As most links lead to commercial offers, some speculate that this is done on purpose: there may be a point to here, since confusion has long been used to frustrate and hinder those who do not hold power. 35 KISS stands for Keep It Simple, Stupid.

22 Metrics (size and location) It would be unthinkable to use styling extensively, when all the elements of a certain type are affected by CSS settings. In the next pages, we will see how to style distinct elements of the same type (as in the case of the DIVs of the previous example, or anytime the need arises to differently enhance some elements). But first, it is necessary to consider some metric attributes. Dimensions and distances can be set with several measure units: px Pixels cm Centimeters in Inches % Percentage (relative to the immediate ancestor) em About 2 times the current font size. Widely used, being automatically adaptable pt Points (1pt=1/72 inch) ex, pc Rarely, if at all, used: ex=half the font size; 1pc=12pt The sizing properties of elements are the following: height width max-height max-width min-height min-width Fixed value Fixed value Limits to element dimensions, typically when users resize the browser window One fundamental placement attribute is the position, which can be specified as: static Elements are rendered in order 36 absolute fixed relative Position inside the first positioned ancestor (i.e.: not static) Position in the browser window Position relative to its normal position (static) Other placement attributes (bottom, left, right, top) can only be set when the position is not static. Elements can be separated by adding some room on the page, which can be done with two slightly different attributes, which are often mistaken margin padding Works on the outside, separating from outer elements Works on the inside, moving content away from block edges A very good (visual) explanation of the difference is given at: 36 Following the motto go with the flow (UJBR).

23 The content of very long paragraphs not always fits into the allotted space. This effect is called overflow, and can be regulated with the corresponding attributes, which are listed below: overflow overflow-x overflow-y Specifies how to process content which does not fit in an element s box visible hidden scroll auto (default) overflow is visible, but it may encroach with other content in bordering elements Overflow is clipped, and will not be shown Overflow is clipped, but reachable through scroll bars Same as before, but scroll bars will only appear when needed overflow-x and overflow-y separately regulate the scroll bars; it must be noted, however, that horizontal overflow does not happen with text, which wraps around by default (unless the width of the element is so small that some words do not fit): the effect is usually caused by other elements, such as images. We will use two different overflow settings, with the help of a sheila named Yvonne. In the first example (the default), her picture encroaches on the rest of the page (Other stuff), which is bad. In the second example (which could also be a simpler overflow:auto), the paragraph respects its confines, and the presence of the scroll bars is due to the dimensions of the image, while text is automatically redistributed. P border height width font-size overflow : visible; : solid red 3px; : 210px; : 175px; : 12px; <p> Spectas nos, Philomuse, cum lavamur,<br> et quare mihi tam mutuniati<br> sint leves pueri subinde quaeris.<br> Dicam simpliciter tibi roganti:<br> pedicant, Philomuse, curiosos. <img src=yvonne.jpg> </p> <h3>other stuff</h3> overflow : scroll; One other attribute has some uses in altering the default rendering of some elements, mostly paragraphs: display There is no default value, as it depends on the element (for example, headings and paragraphs display as block, short quotations display as inline): none block inline inline-block The element is not displayed. Takes up the largest width possible, with breaks before and after (the element will be separated in the flow). No breaks before or after. Block behavior, with no breaks; paragraphs will be restricted to their actual content, and not to the width of the entire page, as they would by default).

24 IDs and classes Inline styling, although it can help in some situations, especially in JavaScript or PHP programming, is not the best solution, as it clutters the HTML with styling specifications: the way to distinguish elements is by the use of IDs and classes. An element possessing an ID can be addressed (and styled) directly, while classes can group elements together in categories, so that styling affects only those elements, leaving the rest alone. Besides, different elements (for example, <p> and <span>) may share the same settings. The rule of thumb is to use IDs when an element is only one of a kind, and classes when more elements share the same feature. One way to circumvent this rule is to assign the same ID to more than one element, but, although it can be done, by no means it should. Additionally, when interactive pages are in use, it is essential that input elements have distinct IDs and names 37. Let us consider the following example: <span id=s1>a span with id "s1"</span><br> <span class=coral>this span is class "coral"</span><br><br><br><br> <div class=green>this is a <span class=coral>span of class "coral"</span> <br><br>inside a class "green" div</div> The CSS syntax has slightly different formats: instead of listing just the tag name, IDs are prefixed by a pound sign (#), and class names by a dot (.) 38 : #s1.coral.green border color position top left : 4px ridge lime; : red; : fixed; : 50px; : 180px; height : 10%; border : 6px ridge pink; color : navy; background-color : coral; padding : 5px; border : 5px ridge gold; color : greenyellow; background-color : green; padding : 5%; width : 500px; height : 50px; Elements with a fixed position may overlap with others, so this is not the best of choices. Positioning is better done with percentages; some use tables, which at least offer some organization of the screen real estate 39 (more on tables later). 37 Names are especially useful in PHP, IDs in JavaScript: a simple and useful rule is to assign an element the same ID and name, keeping them unique throughout the page. This greatly helps in dynamic Web pages and data processing. 38 The pound sign stands for this page, while the dot symbol is used for classes in OOP languages, which bear some resemblances with CSS classes. C++ is the reference for OOP (Object-Oriented Programming) languages. 39 This expression refers to land property management: it is used in programming because space on the screen is often scarce, and therefore described as a costly item.

25 An element with an ID can also be referred directly in a link. This could be useful in very long documents, where a specific point can be reached without the need to visually find it. The following HTML code uses very high, almost empty DIVs, just to separate three paragraphs more than enough not to fit into the same screen. It is presumed that, in a normal page, those spaces would contain useful information: <p id="toppage"> <!-- top section --> <a href="#halfpage">down to half page</a><br> <a href="#bottompage">down to bottom of page</a><br> </p> <div style="height:500px">div 1</div> <div style="height:500px">div 2</div> <div style="height:500px">div 3</div> <p id="halfpage"> <!-- middle section --> <a href="#toppage">up to top of page</a><br> <a href="#bottompage">down to bottom of page</a><br> </p> <div style="height:500px">div 4</div> <div style="height:500px">div 5</div> <div style="height:500px">div 6</div> <p id="bottompage"> <!-- bottom section --> <a href="#toppage">up to top of page</a><br> <a href="#halfpage">up to half page</a><br> </p> <div style="height:500px">div 7</div> <div style="height:500px">div 8</div> <div style="height:500px">div 9</div> The pound sign, # (also called number sign or hash mark 40 ) is normally a reference to the same page. When addressing an element of another page, it works as a separator, identifying an element on that page 41, as in the following example: <a href="index.html#halfpage">half page of index.html</a><br> The browser will try to position the linked element at the top of the screen. If that were not possible, it would at least try its best to make it visible. Some considerations on the use of internal links: Multiple IDs are allowed, reporting no errors, but this is understandably a poor choice. Links to repeated IDs point to the first element such addressed. There are exceptions (most notably, radio buttons: more on this later). Web pages should always contain references to their main components, so that the user is not lost in an excessively long page (which is never recommended, but sometimes necessary). As we all know, it is quite frustrating to scroll up and down in search of that particularly interesting section. This practice bears at least some resemblance to the technique called breadcrumbs navigation, where trace is kept of previous navigation, allowing users to retrace their steps The term hash, derived from the French hacher (to cut), actually indicates a dish of diced meat and potatoes, similar to the Swedish pyttipanna. Probably recalling the action of cutting, hash marks are short lines used to mark locations on sports fields. The term pound sign is commonly used in the USA to indicate numbers (as in: we re #1), and also one special key on telephones; number sign is used in Canada. The Italian term cancelletto (small fence) is quite forgettable. Even more forgettable is the dreaded term hashtag, which is such only when referred to social networks. 41 Clearly, the programmer should know about the existence of the referred element: of course, this is usually done in the same Web site, which is presumably under control and well known. 42 The expression recalls the trail of breadcrumbs in the Hansel and Gretel fairytale.

26 Summary on metrics This summary will sometimes use inline styling. Though it may not be the best practice, it is often seen around, so some examples will not be useless. What s more, some PHP solutions are actually simpler with this setting, one more reason for demonstrating it. When directly positioning elements, the common practice is to set the top and left attributes. For a change, these examples use bottom and right. Still, the second example shows the preference for left, which overrides right when, for some inexplicable reason, both are present (the same applies for top over bottom). The image shows an hypothetical bottom part of a browser window. <img src=mario3.bmp style='position:fixed; bottom:20px; right:20px;'> <img src=sushi.gif style='position:fixed; bottom:80px; left:20px; right:20px;'> When sizing images, setting one dimension adjusts the other accordingly; setting both dimensions should be done with care, respecting the original proportions. For example, the image of the example is 34 by 34 pixels, and resizing it to a rectangular shape does not yield a proper result: <img src=mario1.bmp style='width:50px;'> <img src=mario1.bmp> <img src=mario1.bmp style='width:20px; height:20px'> <img src=mario1.bmp style='width:50px; height:20px'> In this case, a thin border has been added in order to show the padding effect: <img src=mario2.bmp style='padding:20px; border:solid 1px red'> Finally, another uncommon setting combination: the margin is relative to the right side of the browser window, and the size is expressed in centimeters: <p style='margin-right:2cm; border:ridge 4px coral'>...</p>

27 The basics of typography Web pages should be easy to read, and attractive to the user 43. This makes Web design a serious business; and while an image is worth a thousand words, text styling should require a great deal of care, because most users need written information. The most common attributes affect only block (or inline-block) elements. This is one of the reasons why the use paragraphs is encouraged. All the settings will affect elements belonging to a class called <sample>, which will contain the ubiquitous Rosetta lyrics. <p class=sample> well my little girl is a sweet little girl<br> but she does things make your eyebrows curl.<br> You let her loose on a Friday night<br> you know it's gonna end in a fight.<br> </p> As already noted, the only change in HTML code is the class attribute, as all actual settings are in CSS. The most common text alteration regards the font size, done through the aptly named corresponding attribute. It is also possible to set the spacing between characters or between words, but this is rarely done, as the font-size attribute usually suffices. The display setting is not really necessary for paragraphs, but it can be thrown in as a good measure, to force block behavior on some elements which could need the same settings (typically, spans). The heading p.sample specifies that the class setting is restricted to paragraphs (so that, for example, a span declared as class=sample will not be affected by this styling). As it may be inferred, letter-spacing separates letters, and word-spacing separates words. p.sample display : inline-block; /* also: block */ letter-spacing : 2px; word-spacing : 10px; font-size : 12pt; The quality of the rendering is doubtful: A negative letter-spacing setting can be really horrible (besides totally unreadable, if the value is too large). This is easily seen with -3 (in this and in the following example, the font size has been set to 8pt): On the other hand, words cannot overlap in the same way. A negative value of the word-spacing attribute, even as ridiculous as -200, only results in consecutive words:settings (typically, spans). 43 One estimate places the attention span around 30 seconds: after that, new visitors who don t find their way will probably move to another page.

28 Text styling The following attributes affect the distribution of text: text-align left, center, right, justify These settings correspond with the alignment provided by most word processing programs. vertical-align Specifies the vertical alignment of text: baseline Aligns with the normal flow of the parent element # (e.g.: -10px) Raises (or lowers, if negative) an element % The value is a percent on the normal height of the line top Aligns the top with the top of the tallest element on the line bottom Aligns the bottom with the lowest element on the line middle Text is stretched so that each line has the same width text-indent This affects only the first character of the block letter-spacing Separation between letters word-spacing Separation between words white-space normal, nowrap, pre, pre-line, pre-wrap normal Whitespace sequences collapse into one (the default) nowrap Text will not wrap until a <br> tag is encountered pre Whitespace is preserved: this disposes with the need of the mnemonic. pre-line Whitespace is NOT preserved (surprisingly), and text will wrap automatically pre-wrap Whitespace is preserved, and text will wrap automatically The pre-line setting is somewhat unclear, as it does not preserve whitespace, which the pre word would induce to think. The following attributes affect the appearance of text: text-transform uppercase, lowercase, capitalize (as in Capitalize) Capitalize transform every word: the first letter in uppercase, the rest in lowercase. font-style Possible values: normal and italic (or oblique, which has the same effect). font-variant Possible values: normal and small-caps. font-weight normal, bold, bolder, lighter Curiously, there is a range of numeric values which only work on hundreds: 100, 200, 300, 400, 500, 600, 700, 800, 900 (in ascending order of thickness). font-size Besides the numeric settings (with any value), there are some semantic ones: small, medium, large, x-large, xx-large text-decoration These two values are used regularly, typically to alter the appearance of links: none, underline overline is used in certain Asian languages, or in geometry (for a segment ) AB line-through is used to indicate a change of mind A Capitalized Rosetta with a text-indent of 20 pixels would look like this:

29 Choosing the typeface 44 It is very common to list specific typefaces to be used, but this could produce unexpected results on clients where the corresponding fonts are not installed. For this reason, typefaces can be (and usually are) specified in stacks, where several of them are listed, along with a generic description of their category. The browser visits the list from left to right, using the first corresponding font that is installed on the computer; where no exact match is found, it searches the best font which suits the category. This is probably the reason why the attribute is called font-family. There are several suggested stacks, each for one of the main categories of typefaces. The traditional classification is by width (wide/narrow), serifs 45 (serif/sans serif), and pitch (monospace/proportional). Other categories (cursive, fantasy) may be used, but not all browser support them effectively. The most common typeface settings are as follows (only the first example is complete with braces). Note the quotation marks required for names with multiple words, such as "Times New Roman": Wide sans-serif Narrow sans-serif Wide serif Narrow serif Monospace.sample font-family : Verdana, Geneva, sans-serif; Helvetica, Arial, Tahoma, sans-serif; Georgia, Utopia, Charter, serif; Times, "Times New Roman", serif; Consolas, Courier, "Courier New", "Lucida Console", monospace; The designers of these fonts deserve a citation: Verdana Matther Carter, Tom Rickner Geneva Kris Holmes, Susan Kare Helvetica Edouard Hoffmann, Max Miedlinger Arial Robin Nicholas, Patricia Saunders Tahoma Matthew Carter Georgia Matther Carter, Tom Rickner Utopia Robert Slimbach Charter Matthew Carter Times Stanley Morison, Walter Tracy Times New Roman Starling Burgess, Victor Lardent, Stanley Morison Consolas Lucas de Groot Courier, Courier New Howard Kettler Lucida Console 46 Charles Bigelow, Kris Holmes Monospace typefaces (also called fixed-pitch) are commonly used in program snippets and data processing lists (where items placed in the same column should match digit for digit). Consider, for example, a typical sales list. It is easy to notice that the rendering is very poor with a proportional font: Corbel Consolas ,111, ,744, ,008, ,051, Typeface refers to the overall design of a set of characters. Technically, a font is one of the variants of a typeface. For example, News Gothic Light and News Gothic Bold are fonts, whereas the overall design is the News Gothic typeface. 45 A serif (grazia in Italian) is a small line placed perpendicularly at the end of a character stroke. It is assumed that serifs were resting places for chisels, in the times when inscriptions were usually carved in stone. 46 This is the font used in the classic BSOD (Blue Screen Of Death), the dreaded error page in some version of a popular operating system.

30 Any font you like NOTE: this paragraph, included for the sake of completeness, can be skipped without harm. Web pages can be enriched with any possible font (of course, the font should be cleared for use by the rightful owners), but the technique is a little tricky. The problem is that different browsers support different font formats, so that the effect can be guaranteed only by placing several versions of the font file. Since most fonts are distributed as ttf, it is necessary to resort to some generator to obtain other the most common formats. One free such service is available at: Once connected to that page, it is possible to specify a ttf file, then activate download your kit : after some processing, a ZIP file will be available, containing several font formats (ttf, eot, svg, and woff), and even some examples (a HTML document and a CSS) on how to activate them. Well done, Squirrels. In the following example, a fancy (and hard to read) free font named annone has been used. After downloading the.ttf file and sending it to fontsquirrel, four font files were obtained: annone.ttf, annone.eot, annone.svg, and annone.woff. As usual, both a CSS and a HTML document are involved. The src attribute in entry is a bit complicated, but necessary for all formats to be available, and for some browser nuances to be taken into account. In cases like this, all the versions of a one single font stands for a whole font-family. In the document, no provisions are necessary: the CSS declarations suffice, so there is no change in the HTML code (except for possible class declarations). h2 font-family : font-family : 'annone'; src src font-weight : normal; font-style : normal; : url('annone.eot'); : url('annone.eot?#iefix') format('embedded-opentype'), url('annone.ttf') format('truetype'), url('annone.woff') format('woff'), url('annone.svg#annone') format('svg'); <h2>rosetta rendered with the ANNONE font</h2> After setting the <h2> tag with the new font, the header "Rosetta rendered with the Annone font" responds accordingly, in a number of common browsers. Given the font, the result is barely readable, but it should give the idea:

31 Pseudo classes One very common feature of Web pages is polymorphism 47 : elements can change their appearance, depending on certain situations. The most common occurrence happens when the user moves the mouse over an element, leaving the pointer there for some time: this action is called hovering. We have already seen that the title shows a small window (also called tooltip) which appears when hovering on an element. This, however, is not a style property, being an extra object that appears independently from action on the element itself (except mouse hovering): actual dynamic styling affects the appearance of elements. The act of hovering can alter the style of an element, through one feature belonging to what are called pseudo-classes. Originally intended for anchors only, the historical stack of pseudo-classes (CSS1) comprised four of them, which are still widely used to change text appearance and color of links. This is not surprising, as links hare always been the one somehow dynamic feature of Web pages. It is advisable that all links share the same settings, so as not to be confusing for the user. In such cases, one global setting could be the following: a:link text-decoration : none; color : peru; background-color : wheat; a:visited color : yellow; background-color : red; a:hover color : yellow; background-color : black; a:active color : blue; background-color : yellow; The text-decoration settings makes links appear with no underlining. The color settings could be a way of attracting the attention of the user. This setting is usually done to override the default purple color of visited links, which is disliked by many. This example shows how to exaggerate the appearance of a link, presumably to alert users that they are about to activate something significant. This setting is probably the least useful, since a link is active only when the mouse button is actually being clicked (including the whole time that it is held down, which is normally very brief). With so little time in this state, the action is hardly noticed. Four faces of a link When only certain links need to be enhanced, it is also possible to set classes of elements, with the usual class declaration (in this case, the setting applies only to <a> elements of certain classes): a.new:link... /* CSS */ a.new:visited... a.new:hover... a.new:active... <a class=new href=#>custom link</a> <!-- HTML --> 47 This is not the polymorphism of OOP objects: the term only refers to the possibility for various styles.

32 New additions Nowadays, pseudo classes can also be used with other elements. CSS2 has added a number of them, allowing a great deal of control on dynamic styling. The following example is intentionally exaggerated, but it can give the idea:.sample:hover color background text-transform font-size transition : white; : lightgray; : uppercase; : 25px; :.2s;.sample:first-letter font-size : 200%; font-style : oblique; color : dodgerblue;.sample:first-line color.sample:before content color background-color.sample:after content : crimson; : ":;-xyz"; : brown; : yellow; : url(sushi.gif); It is doubtful that anybody would want the font to vary on hovering, as this would be confusing for the user. Normally, only colors would be affected. One curious attribute is the transition time it takes the element to reach the final appearance: it can be fun, though not too useful, to watch the morphing with a ridiculously long interval (say, 20 seconds; note that moving the cursor off the element would stop the transition). This setting defines the style for the first letter (or digit) of a block elements (normally, p or div), including any other characters preceding it. For example, in a paragraph beginning with :x, the style would also apply to the punctuation mark (although the effect would be questionable). The same applies for the rest of the first line (thus excluding the first letter). These settings are not affected by the ones in the hover pseudo-class. The last two settings allow the definition of specific content to be inserted either before or after the affected elements. They do not appear to be very useful, unless when some image is used to signal certain situations. The before selector influences the first-letter effect: when a literal is used, its first letter will use the firstletter settings; strangely, when an image is used, the first-letter settings are disabled. This example shows how to refer to an image (if no folder reference is present, it should be in the same folder as the HTML document). Of course, for those elements which do not have the block behavior by default, it is necessary a block (or inline-block) setting of the display attribute. (normally, about the only elements which could be used in this way are SPANs). The following images are the two rendering of a paragraph, before and after hovering: <p class=sample> God must love stupid people. He has so many!!! </p>

33 Curiosities In some cases, we might want to center an image inside its container, as in the image below. There are some suggested solutions, but the safest one appears to be a real kludge 48. After setting position to absolute and margin to auto, the key is assigning 0 to all the coordinates, so as to confuse the browser, which will try to satisfy all the conditions by placing the image in the safest position, in the middle of the container. The CSS and HTML snippets are shown:.middle border position margin left top right bottom : solid red 1px; : absolute; : auto; : 0px; : 0px; : 0px; : 0px; <div class=...> <img id=fish class=middle src=img/sushi.gif></img> </div> There are many cursor settings available when hovering over any element; these work both in a pseudoclass and in a common style declaration. This is an example with an id setting (the crosshair is normally used to help precision pointing): #newcursor /* also: #newcursor:hover */ cursor : crosshair; A complete list of cursor shapes (most of which should be familiar to those who use spreadsheets and word processors) can be found in any instructional Web site. Some significant cursors are summarized in the following table. There is also the possibility of using a custom image, which, for some reason, only works when part of a list of cursor settings ending with auto (which should only be a last resort, but, apparently, is something more). default / auto cell hand / pointer crosshair text not-allowed url cursor : auto; cursor : cell; cursor : hand; cursor : crosshair; cursor : text; cursor : not-allowed; cursor : url(sushi.gif), auto; 48 An improvised, usually crude, tool or solution. The origins of this term are uncertain: some cite the Scots kludgie (common toilet), others the German klug (clever).

34 Floats In this example, we will use classes and containers to organize a simple HTML document with CSS. The final shape of the page will follow the outline in the image. The result will be a reduced version of the layout shown some pages above. The project calls for three containers, one of which is a wrapper containing the other two. Appropriately, it will be of class wrap. The two remaining containers will split the remainder of the page: one is a meaningful container called <aside>; the other is another DIV of class content. As the name implies, the <aside> container will occupy one side of the page; as is customary in public Web sites, it will also contain some links (included only to give the idea: they will lead nowhere). The HTML code is quite simple: <div class=wrap> <h1>main header</h1> <div class=content> <h2>rosetta</h2> Well my little girl is a sweet little girl<br> but she does things make your eyebrows curl.<br> You let her loose on a Friday night<br> you know it's gonna end in a fight.<br> Rosetta drinks her whiskey neat<br> she gets in a fight and she might get beat.<br> So I go round on the Saturday night<br> and ask her if she feels allright.<br> </div> <aside> <ul> </ul> </aside> </div> <li><a href="#">home</a></li> <li><a href="#">about</a></li> <li><a href="#">contact</a></li> Without styles, the result is not very encouraging, as the browser follows the normal HTML flow:

35 With a little CSS, the page assumes the desired shape:.wrap.wrap h1 background-color : lightsalmon; min-width : 600px; width : 80%; margin : auto; overflow : auto; padding-left : 20px;.content background-color : lightcyan; width : 80%; float : right; overflow : auto;.content, aside height : 200px; aside background-color : palegreen; float : left; width : 20%; aside ul list-style : none; The min-width attribute ensures that the DIV will not be shrinkable under a certain width. The width/margin combination forces the DIV not to occupy the whole page, leaving some margin from both sides (thus centering it). The most mysterious setting is overflow:auto: its purpose is to force the contained DIVs to stick to the colored background (courtesy Jeffrey Way). This setting applies only to h1 headers in a class wrap container. Other h1 headers will not be affected (which is good). It leaves some space to the left of the header. The combined width of this DIV and of the aside element covers the whole container (100%). In this class, the overflow:auto setting is different from the previous one: its purpose here is to allow scrolling the content when it exceeds the DIV boundaries. Since the height of the wrap container is not fixed, the main DIV will adapt to the contained elements, unless the whole page overflows. This is a combined format for more than one element, used to group several settings under a single entry. In this case, the space after the comma is necessary. The secondary DIVs (80%+20%) should fill up the whole primary container. While a combined width of less than 100% will only force the main DIV to supply the missing space, exceeding 100% will force the two DIVs on different heights. The FLOAT attribute specifies on which side each will stay. This setting is marginal to this topic. It just shows how to get rid of the bullet symbols in the unordered list. It is interesting to note that setting this attribute to decimal mimics an ordered list There are quite a few other settings, some of which could turn out to be useful, sooner or later: lower-alpha, lower-greek, lower-latin, lower-roman (with the corresponding upper variants), armenian, hebrew, katakana For example: alpha (or latin) style: a, b, c ; greek: α, β, γ ; roman: i, ii, iii, iv.

36 Tables The most common representation of data in electronic processing is through rectangular tables. The example shows data regarding some American League pitchers 50 : CAPTION Pitching statistics HEADERS PLAYER TEAM GP IP ERA Hisashi Twakuma SEA ROWS Felix Hernandez SEA (RECORDS) Bartolo Colon OAK Hiroki Kuroda NYY Chris Sale CHW COLUMNS (FIELDS) ORDER This style conforms to the relational 51 model of databases 52. Tables are typically shown with this format, where the various parts have precise meanings, and an associated tag: TERM MEANING TAG Table The whole element <table> Caption General information about the data <caption> Row Exactly one row (except for the caption) <tr> Headers Column description (normally at the top of each column) <th> Data The content <td> Order One column which sets the row order n/a (PHP) Rows and columns, in database jargon, are called records and fields: a record is a collection of data, related to the same entity; a field is a homogeneous group of data, one for each record. The term record refers to the fact that all its data are readable (and writable) in the same operation. BEWARE!!! Sometimes, the term database is mistakenly used to indicate just one table. While this could be true (with a very limited set of data), it is generally inaccurate. HTML tables are not that interesting in themselves: they should be populated with PHP. Just for an example: <table class=pitching> <caption>pitching statistics</caption> <tr> <th>player</th> <th>team</th> <th>gp</th> <th>ip</th> <th>era</th> </tr> <tr> <td>hisashi Twakuma</td> <td>sea</td> <td>18</td> <td>121.1</td> <td class=order>2.60</td> </tr> </table> WARNING 2 This is only part of the table. WARNING 2 The only element that needs further specifications is the cell with a different background (class=order). All the actual settings should be done in the CSS. 50 From: some day in The term relational refers to Cartesian products of sets, also commonly represented in rectangular form. The same model is applied in spreadsheets. 52 A database is a collection of data, with possible links between them, and tools to investigate and process them. The term table is quite common in databases parlance, as it is the most used layout for data.

37 What is really interesting is the styling. As the table belongs to a specific class (pitching), it is possible to declare only its associated components (as in the lines written in blue), without affecting components of other <table>, whether declared as classes or not 53. Elements with the same styling can be grouped, to save multiple declarations: this is shown where several elements have similar borders (second example, lines written in green)..pitching border-collapse : collapse; border-bottom : ridge 3px springgreen;.pitching caption,. pitching td,. pitching th border-left : ridge 3px springgreen; border-top : ridge 3px springgreen; border-right : ridge 3px springgreen;.pitching caption color : darkgreen; background-color : palegoldenrod; font-size : 16pt; padding : 10px;.pitching th color : purple; background-color : lightgoldenrodyellow; font-size : 12pt; padding : 3px;.pitching.order /* The blank space is required */ background-color : palegreen; color : sienna; font-weight : bold; Some considerations apply: The default attribute is separate. (where each cell has its own border). collapse means that there is a single separator between cells (with no gaps). All the borders could also be described with the group attribute border, but that would leave an unpleasantly thick margin between caption and data. This declarations applies only to the caption element Table headings require their style, and some padding. This style applies only to those cells declared as.order, which feature a pale green background. Note that this class only works as an element of class.pitching. The best part is that each table can be customized; considering the possible amount of code, it only makes sense that styling is done separately, or the HTML code would be a totally unreadable mess; As previously said, tables are never hard-coded in HTML documents, as the data are gathered via some PHP snippets: still, when building a table that way, it must be coded properly, so it is necessary to know the syntax well; The same table, formatted and saved with a word processing program, would require over 1400 lines of HTML code; the result would be totally unmanageable, unless one recurred to the same program, a very unrealistic assumptions, as it would not work when gathering data automatically; Some styling is almost a necessity, since the default tables are very plain, as this example shows: 53 Avoiding collateral damage to different, unrelated elements is one of the tenets of computer programming.

38 Forms Interactive Web pages allow the user to type and process data. While data processing is done mostly in PHP (and sometimes in JavaScript), data input is done exclusively in HTML elements called forms. The word form has several meanings: in administration, it refers to a document with blank spaces for the insertion of information. In computer science, forms are the electronic equivalent of such documents, containing labels (printed information), fill-in spaces (input elements, normally called boxes or input boxes), and other elements which allow for interaction. The battle with the Italian tax return form (modulo unico) The dreaded 1040 form, the American equivalent Electronic form Interactive elements in a HTML form are called controls. There are several ones available, as follows: Label TextBox Password TextArea CheckBox Radio (radio button) Select (ListBox) Button Submit (submit button) Reset (reset button) Hidden More of an accompanying text, it can be used to access a control The most common control, where users type a short text or a number Special text box where input is hidden Larger area for typing free text (as a comment or a letter) Two-state box, typical for yes/no situations Multiple-choice structure of mutually exclusive answers Another multiple-choice structure, in pull-down form Normally used to provide additional, miscellaneous actions This button allows the user to send the data to a server for processing This button clears all the fields in the form. The value is not shown, but can be sent to a receiving page (more on this later). Text input elements (textboxes, textareas) can be filled with expected data (to save the user keyboard time, using the value attribute) or with a short hint (describing what should be typed, using the placeholder attribute), which disappears as the user starts typing. Radio buttons, checkboxes, and listboxes require other settings (more on this later). <input type=textbox value="user"> <input type=textbox placeholder="type user name here"> The following images are typical forms we frequently encounter on the Web: one is a typical login form, the other a fictitious application form for a criminal organization:

39 Sending data to the server All the elements of a form must be enclosed in a <form> container, and, except for the <label> element, are introduced with an <input> tag. Labels, besides containing a brief prompt to the user, can be clicked upon to give focus 54 to the associated <input> elements, one feature which can help with hard-to-reach elements, like check boxes and radio buttons. Forms normally contain a <submit> element, a button which sends the data to another page through the server. The page name is specified in the action attribute of the form (#, as already seen, indicates the current page). One typical login form could be as follows: <form action=#> <label for=name>user name</label> <input type=textbox id=name name=name placeholder=user><br><br> <label for=pw>password </label> <input type=password id=pw name=pw placeholder=password><br><br> <input type=submit id=sub value="login"> </form> Some considerations apply: The element type is specified with the type attribute; Only elements with a name can be used by a receiving PHP page, while JavaScript uses the id attribute to process the sending page (for example, giving focus to certain elements): the simplest choice is to set both attributes to the same value; Password elements should not be given a value, so as to avoid showing them in plain text 55 ; The placeholder attribute normally contains a short hint on the expected input. Another thing that ought to be corrected is how the receiving page (in our example, the same page) obtains the submitted data: by default, the data are attached to the URL, after a? sign, and are separated from one another by an ampersand (&). Once again, you don t want a password to be shown coram populo like this: file:///c:/web/test2.html?name=user&pw=password# The same string could be automatically scanned by any malicious page, where it can be addressed in JavaScript as window.location.href, looking for information beyond the question mark sign (scripts will be treated in the following chapters). For this reason, most forms are usually associated with a method which specifies not to send the data along with the URL in plain text 56 ; this behavior is called post, as opposed to the default (get): <form action=# method=post> <form action=# method=get> <!-- the default (seldom, if ever, used) --> The effect of the post method on the receiving page is more secure: file:///c:/web/test2.html# The values are normally processed with PHP scripts. The same holds for hidden data, which can be used for additional information, not accessible by the user, as in this example: <input type=hidden name=operation value="operation 1"> Hidden elements are sometimes called cargo, since they are just along for the ride. They are commonly used to specify more details to receiving pages which have different processing options. Of course, the receiving page of the previous example should contain control statements referring to the value of something 57 called operation, or the whole issue would be moot. 54 One element has focus when it is the object of direct keyboard action. Text elements show a blinking cursor inside them; other elements can be highlighted in various ways, like different colors or borders. 55 Passwords are given values when developing an application locally, to save time for debugging purposes; the security advice holds for published pages. 56 Exactly why this method should be the default is unclear: presumably, this is a relic of times past, when security was not an issue. 57 Not surprisingly, this something will be a PHP variable.

40 Input elements: a closer look The application form for a fictitious criminal organization contains all the common form controls, coupled with the corresponding labels. The final image is a summary of the look of the resulting form. <label for="text">your name</label> 1 Textbox <input type=textbox id=text name=text> 2 Checkbox <label for="check">own gun?</label> <input type=checkbox id="check" name="check" checked> Checkboxes are used for true/false situations. The checked attribute, understandably, fills the box with the check symbol (ticked, as the Brits say). 3 Select (Listbox) <label for="sel">main occupation</label> <select name="sel" id="sel"> <option value=1 selected>hitman</option> <option value=2>robber</option> <option value=3>killer</option> <option value=4>arsonist</option> </select> Selects are normally used for limited choices. The selected attribute selects the corresponding item. It is possible to allow multiple selections with the attribute multiple="multiple". 4 Textarea <label for="area">additional info</label><br> <textarea id=area name=area rows=5 cols=30></textarea> Textareas are used for large bodies of text, and provide scrolling handles. 5 Radio Button <label for=sex>gender </label> <label for="male">male </label> <input type=radio name="sex" id="male" value="male"> <label for="female">female</label> <input type=radio name="sex" id="female" value="female"> Radio buttons are tricky: they do not belong to a container (unlike listboxes), but are identified with the same name (this makes them mutually exclusive). In order to be recognized by scripts, they may have different IDs. If the id is the same, the associated buttons form an array. 6 Submit button <label for="sbm">click to send request</label> <input type="submit" id=sbm value="send"> As previously mentioned, a submit button is almost necessary, although any form could be submitted by other means in JavaScript. 7 Reset button <label for="clr">click to reset values </label> <input type="reset" id=clr value="clear"> Clearing your controls can be useful, but sometimes annoying, as some data could be retained for further action. 8 Button <label for="btn">click</label> <input type="button" id=btn value="button"> Generic input buttons have little use by themselves, unless coupled with some JavaScript code BEWARE!!! HTML has another, more advanced button tag couple: <button>...</button> Unfortunately, this element does not work properly in some browsers, so it is still better to use the classic tag: <input type=button...>

41 Want to contact us? Most commercial, or otherwise public, websites contain links for sending to the webmaster or other staff members 58. One possibility is loading a form with a pseudo-url which actually invokes a mail client. This option, though, does not provide a means to insert dynamic content directly into the mail message. The simplest action indicates only the recipient (or more than one, separated by commas): <form action="mailto:mail@domain.xx"> <form action="mailto:mail@domain.xx,mail2@domain.xx"> Accessories 59 can be added, following a question mark (note that, unlike the recipient, additional addresses are introduced with an equal sign): <form action="mailto:mail@domain.xx?cc=mail2@domain.xx"> <form action="mailto:mail@domain.xx?bcc=mail2@domain.xx"> <form action="mailto:mail@domain.xx?subject=some stuff"> <form action="mailto:mail@domain.xx?body=body of the message"> Any number of accessories can be added (following the order: cc, bcc, subject, body), separating them with ampersands: <form action="mailto:mail@domain.xx?cc=mail2@domain.xx&subject=hot stuff"> It is even possible (though rare), to leave the recipient box empty: <form action="mailto:?subject=some stuff"> Line feeds (ASCII code: 10; HEX: A) can be added in the %hex format: <form action="mailto:mail@domain.xx?body=first line%0asecond line"> However, considering that a form submit button is a single element, it is more flexible to use anchors, which make it possible to differentiate between contacts. The syntax is quite similar as we can see in the examples. Anchors have the additional advantage of allowing images to be used as links. Often, those images look like envelopes or mailboxes. <a href="mailto:mail@domain.xx">contact us</a> <a href="mailto:mail@domain.xx"><img src=mail.jpg><br>contact us</a> The second example combines images and text, thus making the link more pleasant to watch. Anchors also allow dynamic content to be inserted into the message: for example, one form could contain a textarea where the user types the message body, which is sent to the mail client along with the request. This technique, however, requires some JavaScript tricks. 58 Some organizations, though, are particularly apt at hindering user requests, and contact information are sparse, when not outright misleading. 59 cc (=carbon copy), bcc (=blind carbon copy, invisible to the other recipients), subject (a short description of the message), and body (the actual message).

42 The best is yet to be 60 To wrap things up, refer to Appendix A for a summary of the most common HTML attributes, and to Appendix B for a summary of HTML color names. And now for something completely different 61. So far, we have covered how Web pages are described, which, as already specified, is a static affair, with some exceprions regarding pseudo-classes and forms. This corresponds to little more than the initial stage of the Web, when low speed forced the use of text-based pages with little dynamicity, e-commerce was still science fiction, and images were a rarity 62. Over time, graphics (first in the form of images, then with various animations) was added, often overdoing it, at the expenses of bandwidth: for a while, it looked like every advance in traffic management was canceled by adding unnecessary frills to Web pages. But that s another story (refer to Appendix C for an expert s opinion on the matter). But what s far more interesting is how Web pages have been morphed into interactive environments, and that could not have happened without some programming (and, of course, years of experimenting). In the following chapters, we will try to shed some light on some of the stuff that has transformed the Web into what it is now. The first tool to be analyzed will be JavaScript, a programming language that can operate on a Web page once it has been downloaded from a server, altering its content according to user action or some other event. It will not operate on the server, though, and we can guess that s why they call it a client-side language 63. Messing with servers is a job for bigger guns like PHP or ASP (which are called, not surprisingly, serverside languages). e 60 Robert Browning ( ). 61 Monty Python (around 1970). 62 Those were the days of film photography, and digital cameras were, at best, experimental. 63 I guess that s why they call it the blues ( Too Low for Zero, Elton John, 1983).

43 CSS Local Server

44 What, if anything, is a script? A script is a program (usually a small one) written to complement other applications, adding new functionalities or automating some procedures 64. Not surprisingly, scripts are written in scripting languages. Scripts should be as unobtrusive and fast as possible, therefore they are designed to work "on-the-fly", through a process called interpretation (known to Python users), where each statement is translated and immediately executed, without explicit compile, link, and load steps involving the whole program (and quite familiar to C/C++ users). Of course, the host application does check the source code for errors, so some overhead is added to the actual execution time; but, overall, the whole process is lighter and faster, even when the same code is interpreted repeatedly 65. This is particularly required, albeit for slightly different reasons, for scripts attached to operating systems and online applications. A scripting language normally has a simpler syntax than its compiled counterparts, so it should be easy to use and easy to learn, since it does not need to exploit all the features of the host application. There are several applications of scripts, such as parts of operating systems and gaming environments; arguably, the most common is the implementation of dynamic Web pages, which can be affected by scripts embedded into HTML code. And while a different style or rendering can be activated with CSS, the same does not apply to more complex tasks, such as altering the content of elements, or having the page respond to user interaction. Under HTML, there are two kinds of scripts: Client-side scripts affect the data contained in a browser window. They work on a copy of the Web page: although the displayed page can be altered, this is only done on the browser, without affecting the actual page stored on the server. Server-side scripts have direct access to the server file system, and, what s more, they have data processing capabilities, which allow them to also affect data stored on the server 66. This part of the course concentrates on JavaScript, arguably the most popular client-side scripting language. JavaScript is not Java. Java is a full-fledged programming language used to build huge and powerful applications, and as such it has a complex, and hard to learn, structure. JavaScript is a simpler tool, used in Web pages, and, as such, it is embedded in most browsers, thus originating the so-called DHTML (Dynamic HTML), which extends the static structure of HTML documents. JavaScript is truly interactive, in that it can affect the page elements at runtime: in contrast, a server-side language such as PHP works as a pre-processor, sending complete HTML documents to the browser (thus adding the further complication of a wicked timing mechanism). During the years JavaScript has been greatly expanded with a number of functionalities, some quite advanced (such as OOP features). However, data processing applications use only a handful of them, which are activated through a mechanism called event trapping 67. By intercepting user action (mainly mouse clicks on links and buttons, and sometimes keyboard pressing or timers), scripts can: Change the style and the content of HTML elements (mostly in forms); Assign focus to specific form elements; Automatically submit forms (thus activating selected Web pages). Once again, JavaScript being client-side, it cannot affect the actual pages: this is left to PHP. Still, its dynamicity is irreplaceable in adding interactivity to Web applications. 64 It is not part of the application, although it uses some of its functionalities. 65 In fact, the redundant processing of statements is one of the drawbacks of interpreted languages. Compiled programs execute faster because they are already translated in machine language. In this respect, the limited size of scripts helps: huge scripts clog the processor with excessive work, and should be avoided. 66 Of course, servers have security measures: user can only access their designated file systems and databases. Cracking or stealing data is a crime, with various degrees of seriousness. 67 Simply put, events happen. Typically, there are three categories of events: keyboard actions, mouse actions, and timers going off. Browsers are event-driven programs, i.e.: they can detect events and react accordingly (a process sometimes called event trapping). The loading of a Web page is an event, too, and as such it can be intercepted.

45 JavaScript ABC All scripts are executed by a browser, so the first step is to open the one of choice. With some browsers, the quickest way of executing a script does not even require the presence of a HTML document: in the case of an immediate calculation, it is possible to just write the formula in the URL line, prefixed by "javascript:", and press Enter. The result will show up in a blank page. Of course, this should only be restricted to a few examples: proceeding in the same fashion for more complex statements would be just a waste of time. The following examples cover the most common types of data: numeric, logical, and string. They will also introduce some peculiarities of the language. One is the management of mathematical errors (to be precise, calculations which are not even defined, as in examples 3 and 4): while most languages would abort the program, JavaScript makes some assumptions (mathematically wrong, yet not devoid of logic). Another is that, unlike strongly typed languages (such as C/C++), JavaScript freely mixes dishomogeneous data (examples 7, 8, and 9): Expression Result Notes 1 javascript:2+5 7 Basic arithmetic operation JavaScript has several function libraries (actually 2 javascript:math.pow(2,4) 16 objects). One, aptly called Math, is reserved for mathematical operations, such as raising a number to a power (with the same syntax as in C/C++). Mathematically speaking, this assumption is quite 3 javascript:7/0 Infinity incorrect 68, but it gives the idea (since dividing by small quantities yields large values). Another curious (but mathematically sound) result, NaN meaning Not a Number. This value does not 4 javascript:0/0 NaN stop scripts, but all calculations including NaN will yield NaN. Other NaN results are the square root and the logarithm of a negative number, and the inverse sine and cosine of a number larger than 1. 5 javascript:"a"+'b' ab Both the common string delimiters (single quote, double quote) are supported, even in the same expression. Of course, the terminating delimiter of each single string must match the starting one. 6 javascript:(2==2) true Logical values are supported. 7 javascript:(2==2)+3 4 When mixed with numeric values, logical values are converted into numbers (1=true; 0=false).. 8 javascript:"a"+2+3 a23 The presence of one string value casts all numeric data to string, as well. 9 javascript:(2==3)+"h"+2 falseh2 The above also holds when logical values are present. One last example is the popup message, mainly used for debugging purposes, presumably to trace partial script results. The argument of the function is shown in the middle of a dialog window. The following examples shows the syntax and the rendering: normally, the argument would be a calculation, a variable name, or a combination of variables and values (the second variation shown actually uses a couple of variables), with or without the final semicolon: javascript:alert(5+4) javascript:a=5;b=4;alert(a+b) 68 Some even go so far as stating that dividing by zero yields infinity as an actual rule of calculus. This, of course, is total nonsense, but the error persists, sort of a scientific urban legend.

46 True scripts Clearly, these examples just show that browsers do interpret JavaScript commands. Actual scripts should be embedded in regular HTML documents, which is done by enclosing them between a pair of tags not surprisingly, <script> and </script>. JavaScript being very similar to C/C++ 69, many of its statements, including comments, will look familiar. The following example, useless as it may be, would work perfectly in a C program, semicolons and all: <script> if ( x > 0 ) x = 2 * x; // inline comment a = 0; else /* free comment (also multi-line) */ a = b * c; for ( i=1; i<=10; i++) c/=10; </script> The simplest scripts are made of stray statements, which are processed following the normal flow of the page. They can actually build parts of the page itself, using the document.write() function, whose argument (a HTML string) is processed by the browser and rendered accordingly. The following example (a complete <body>) mixes HTML and JavaScript statements. Specifically, the string plugged into the script write statement is processed as HTML, so it should include formatting tags, if needed. <body> <h1>javascript example</h1> First line written with HTML<br> <script> document.write('second line written with js<br>'); </script> Third line written with HTML<br> Fourth line written with HTML<br> <h2>end of page</h2> </body> The result (in the image to the right) is nothing spectacular, but it should give the idea. A note on punctuation The semicolon (;) is not always necessary, as in most cases the interpreter will usually supply the missing sign; sometimes, even a comma will do. But this only works for simple sequences, not in more complex situations, especially when conditional statements are present: a misplaced or missing semicolon could alter whole blocks of code, so the loose syntax of JavaScript can be a disadvantage. Just be careful. Of course, the data fed to the browser should be syntactically correct, or the results would be unpredictable 70. For example, if we made a HTML mistake on the branch tag of the JavaScript statement (<br instead of <br>), the HTML line immediately following (Third line...) would not show in the bowser window. Normal rendering would only resume after scanning a closed angular brace, which in this example should remain at the end of Third line: in that case, the Fourth line would follow the Second, and something would be lost. Detecting the problem, though, would be made difficult by the error being at same distance from the effect: so the only suggestion is to be careful when writing our scripts, since finding errors can be really tricky. And the worst is yet to be. 69 At least, the syntax is almost the same: it s the engine underneath that is totally different. These details, however, hardly affect the standard user, who does not need a thorough knowledge of the inner operations. 70 This is not totally true, as the browser just follows the rules of HTML. The real problem is the slightly different behavior of the various browsers.

47 Bits and pieces We can try another experiment, involving variables and input. The simplest form if input is done through the prompt statement; with that in mind, the following script can be easily understood by anybody who has some knowledge of computer programming: <body> <script> var v; // declaration (not necessary) v = prompt('key in a number', 22); // input value document.write(v+'<br>'); // write result to screen </script> </body> Such a crude interaction, however, is almost never used, as data entry is usually done in HTML forms. One thing that is very different from other languages is the declaration of variables, where the simpler syntax of JavaScript can be seen in action. For one thing, the only keyword is var, as the data type depends on the value are stored into the variable; furthermore, the declaration is not even necessary, as the interpreter can flawlessly add unknown variables to the symbol table. There is considerable debate on where is best to put the <script> tags. One common credence used to be that scripts could only work if written in the <head> element, but, whatever its origin, that turned out to be false. That limitation actually applies to CSS settings. Still, it is not a bad idea to write some scripts in the <head> element, as this is a good place for links to external files (some of which may be JavaScript libraries). Some maintain that the best choice is either at the end of the <body> element, or even after the closing </html> tag 71. Whatever the preferences, one thing agreed upon by Web developers is to choose one place which is clearly separated from the HTML code, and avoid, where possible, mixing scripts and HTML. In any case, it would be a very shoddy practice to interact with the document before the <body> element. Placing scripts in the <head> element (even if it somehow managed to work) is to be avoided at all costs: <head> <script> var v; v = prompt('key in a number', 22); document.write(v+'<br>'); </script> </head> <body> After all, some scripts would not even give the desired effect, if executed too early. This color setting would be overridden when the document <body> loaded (which would take place after the script): <head> <script>document.body.style.background='rosybrown';</script> </head> <body> </body> Quite contrary, the following will have the desired effect (horrible as the background may be); <body> <script>document.body.style.background='rosybrown';</script> </body> 71 After all, stray scripts work even if they follow the </html> tag, something which defies logic.

48 A real-life example: JavaScript functions The examples hitherto shown can be useful, but they are quite limited; moreover, mixing JavaScript code with the rest of the page is quite likery to add confusion to the project. The only way to build a complex, event-driven application is by logically grouping script statements in functions (also called modules). JavaScript, being a scripting language, also fits perfectly into the modular programming paradigm, which calls for short modules, one for each single problem. Typically, what is done is linking an event (mouse, keyboard, timer, page load) to a JavaScript function, which executes when the event is intercepted. Extremely short scripts can even be embedded in links, but they don t always work by the book: the best choice remains to activate a function containing the statements. This also enhances clarity, since scripts are more easily identified when separated from HTML code 72. The next example shows how to alter the style of a paragraph. The corresponding function can be called from either an anchor or an input button. In anchors, the function call is placed in the href clause; in buttons, it is placed in the onclick event declaration, which is a clause of the <input> tag. In order to be recognizable by JavaScript, an element of a Web page must have an id. The access mechanism is a statement 73 with a self-explanatory name (getelementbyid, namely: given the id, track down the corresponding element). In JavaScript, page elements are objects: this means that it is necessary to use the OOP syntax in addressing them and their features. getelementbyid is a method of a universal container, aptly called document, which comprises all the elements of the page. The content of the element corresponds to the innerhtml property, and follows the HTML syntax (including any correctly written tag). The style (the JavaScript one, that is) is itself an object, as it contains several settings, which make it a more complex structure. This example, a whole page, contains the two activations of the script (href and onclick), and also (for the sake of completeness) a direct link to a popup window, just to show that it is possible: <html> <head> </head> <body> <p id=x style='width:100px; height:100px; background-color:red'>paragraph</p> <a href='javascript:changecolors()'>change</a> <input type=button onclick='changecolors()' value='change'> <input type=button onclick='alert("hi here");' value='test'> </body> </html> <script> function changecolors() document.getelementbyid('x').innerhtml='new style'; document.getelementbyid('x').style.color='white'; document.getelementbyid('x').style.background='blue'; </script> Meeting innerhtml As the name implies, this property is pure HTML, and can include any combination of text and tags, without restriction, as in: innerhtml='<h1>new style</h1><span style="color:red">red<br>text</span>'. As in other instances, though, the HTML syntax sould be correct. BEWARE!!! There is a trap to be avoided, which originates because JavaScript has a nasty habit of accepting duplicate names without flinching. Of course, the interpreter does make an assumption, discarding all but the last occurrence of such a function. In any case, we don t want to risk any function to override another, so it is only wise to keep a list of function names, so as to avoid duplicating them. 72 It is also possible to build libraries of functions, further cleaning up the HTML document. 73 More precisely, a method (in OOP parlance) of the main container (the document itself). The paragraph before and after the cure

49 More examples With a few changes, the preceding script can be made more general. After all, flexibility is one of the requirements of a programming language. Different links could activate the same action, but with different arguments. The following example shows how useful it is to have two different string separators, as the single quotes become part of the string enclosed in double quotes. And, since we are here, the function will also set a bold font for the DIV. function changecolors( id, foreground, background) document.getelementbyid(id).innerhtml='new style'; document.getelementbyid(id).style.color=foreground; document.getelementbyid(id).style.background=background; document.getelementbyid(id).style.fontweight='bold'; <a href="javascript:changecolors('x','white','blue')">w/b</a> <input type=button onclick="changecolors('x','red','yellow')" value='r/y'> The original style Different results We can now play a little game, just to show an OOP feature of JavaScript. An object (in this case, a button object), rather than an id, is passed to a script, which can change its properties at will. In the example, the button caption is changed alternatively from on to off. True to OOP tradition, the button transfers itself to the function through the keyword this: function switcher(x) // 'x' stands for the button if (x.value == 'on') x.value = 'off'; else x.value = 'on'; Note: the name switch cannot be used, since it is a reserved word of the JavaScript language. <input type=button onclick='switcher(this);' value='on'> The two faces of the button One event which is often overlooked is the loading of the page itself. The practice is not very frequent, but it is possible to automatically execute a script the moment the page is loaded, with a setting of the <body> tag: BEWARE!!! The following considerations apply: <body onload="alert('this is the load event');"> The javascript: prefix is required in the href link, and optional in the onclick event (this shows that the default scripting language is JavaScript). Object properties should not be mistaken with JavaScript variables. In the third line of the changecolors function, the background property of the style object is totally different from the script variable with the same name. Browsers can tell them apart, but it is important not to fall into any such traps when writing code. Function parameters follow the loose type definition of JavaScript: it is the responsibility of the programmer to make sure that the values are of the correct type. The language, on the other hand, has several built-in functions which can verify the type of the value of a variable or an expression.

50 Errors, errors everywhere Locating fatal errors in JavaScript code is as tricky as the handling of semicolons, possibly even more so. Errors are very pervasive, and, what s more, developers are left with few, if any, clues about what is happening. Since errors happen, this inconvenience confirms the necessity to keep scripts short, so as to reduce the debugging time. The following considerations apply: JavaScript programming errors are not easily tracked, since the error trapping mechanism is very poor: the interpreter just does not execute incorrect statements, to the extent that the entire function containing an error is never even activated. Even if syntactically correct, references to undefined elements of the page, or calls to unknown functions, cause the script to abort, skipping any remaining lines (even correct ones). One collateral effect of programming errors is that they affect the whole <script> block where it is located, to the extent that any function in the same block will never be activated. When one link does not work properly, there is no way to know if there is a syntax error (either in the link or in the function) or if a problem has occurred in the first line of the function. Nor to be taken lightly is the handling of the <script> tags. Failing to specify the closing tag results in a general error on all the functions of the block. In the following example, function wrong() of the first <script> block contains a syntax error. Function correct(), which does not contain errors, will not be activated when the corresponding event happens; the same applies for all the functions in the same block (written in red). By contrast, functions in the second block (written in blue), provided they are error-free, are not affected, and work properly. <script> // first block function wrong() document..getelementbyid('x').innerhtml='new style'; function correct() // but wrong anyway alert('this function is correct'); </script> <script> // second block... </script> It is necessary to proceed step by step. First of all, we can replace the whole content of the called function with a popup message, then try to activate the link: if the message appears, it means that the activation syntax is correct and the problem is in some statements of the function; if it does not, there must be a syntax error, but where? In the activation statement or in the function? To solve this dilemma, one useful trick is to include the suspect function (still in the reduced version, containing only the popup message) in a <script> block by itself, so as not to be affected by other scripts: if it does not work, chances are that the activating syntax is wrong 74. <script> function suspect() alert('if we are here, the link is correct'); </script> 74 Note that this does not clear the actual script yet, as, in this stage, it has been replaced by a safer one.

51 Once the message appears as expected (which means that the programmer has been able to solve an error in the link), the actual script can be added to the function. For the first trial, it is best to leave the popup at the beginning. If it fails to appear, then there is a syntax error in the script, which must be located. One trick is to add the script statements one at a time, testing the function each time (the others can be hidden as comments between a /*...*/ pair or, one at a time, with //): when the failure occurs, the last line added is almost surely the culprit. During this process, it is also possible to check individual lines for references to undefined elements. Chances are that some runtime errors could be recognized and corrected in this phase. If syntax errors have been cleared, but the function still aborts, the hunt can start for the offending line, and, once again, proceeding step-by-step appears to be the only option. Placing popup messages before and after each line makes it possible to track the culprit, which is the line immediately after the last message seen. The following example, which reprises a previous exercise, refers to an incorrect id in the second style setting. Of course, no element named wrong should be defined in the page, or the error would not occur. Sure enough, the last popup window to be seen is the one with the message 2, targeting the following line as the wrong one. While we still have no indications about the actual error, at least we can examine the statement with some confidence, knowing that something is wrong with it, presumably a mistaken reference. function changecolors( id, foreground, background) alert('1'); document.getelementbyid(id).innerhtml='new style'; alert('2'); document.getelementbyid('wrong').style.color=foreground; alert('3'); document.getelementbyid(id).style.background=background; </script> The debugging process could go on several times, depending on how many errors the programmer has been able to produce. The technique just described is sometimes called binary search debugging, and has been developed over decades of research on how to locate programming errors. It also has an academic backing, as well as a fancier name, having been defined Wolf fence algorithm by Edward J. Gauss (University of Alaska, Anchorage) in a famous article, published in the CACM (Communications of the ACM 75 ), volume 25, issue 11, Nov The author, somewhat tongue-in-cheek, describes how to solve the problem of locating a wolf in Alaska, knowing that: it is the only wolf in the state, it howls very loudly, and it does not move. First step: build a fence down the middle of Alaska, wait for the wolf to howl, then determine which side of the fence it is on. Second step; repeat the process on the selected side only, building another fence across it. Repeat at will. Sooner or later, we get to a point where we can see and trap the wolf. Of course, we need a lot of fence. And, what s worse, not all errors behave the same way. Steven Winikoff (Concordia University, Montreal, Canada) lists some other types 76 : foxes, which never howl; coyotes, which howl loudly until you get near them, then become silent;...and worst of all, cheshire cats, which intermittently appear and disappear, and imitate other animals when they decide to be visible. 75 Association for Computing Machinery, arguably the largest computing society in the world. Its magazine, the CACM, is one of the most prestigious publications in the trade, and also one of the oldest, having been established in The list of its contributors is a honor roll of the computing world. 76 For this and other comments, see

52 Building the page Scripts can add programming capabilities to HTML, which is notoriously a description language, good for placing individual elements on Web pages, but little else. A typical example is when the need arises to build long tables with very similar elements: in this case the loop mechanism can greatly reduce the amount of coding. Of course, the image shown to the right is a very short example, with little meaning, but it should at least give an idea of what a well-placed script can do 77. It should be noted that, in this case, scripts must be placed inside the <body> of the page, since its statements take the place of actual HTML code. One other very important thing is that, in order to obtain the necessary flexibility, JavaScript variables must mix with HTML 78 : in this case, it greatly helps that JavaScript is stringfriendly, easily turning numbers into bits of the document. The first version of the example only assigns the data to the table: it does not deal with colors. <body> <table> <script> n = parseint( prompt( "number of rows", 4)); for(i=1;i<=n;i++) document.write('<tr>'); for(j=1;j<=n;j++) document.write('<td>' + (10*(i-1)+j) + '</td>'); // mix document.write('</tr>'); </script> </table> Being picky To activate the choice of colors, we need two CSS classes and a related condition in the script. The assignment used for variable x is called inline if (iif), and is a compact form which groups all the elements of a conditional statement into one line. The extended is shown in the inset. td.a background-color : lightgray; td.b background-color : lightsalmon;... x = ((i+j)%2==0? 'a' : 'b'); document.write('<td class=' + x + '>' + (10*(i-1)+j) + '</td>'); Inline styling also works, but there is the risk of becoming a little cumbersome with too much detail: '<td style="background-color:' + ((i+j)%2==0? 'lightgray' : 'lightsalmon') + '">' Nothing limits the amount of JavaScript that can be inserted into the document. Of course, it should not affect readability, so it is not advisable to script the most important elements (for example, the <body> tag). In the case of the <table> tag of this example, there are no such restrictions, being mainly a matter of choice.... document.write('<body>'); // Going too far... document.write('<table>'); // Acceptable... The prompt statement is not a very elegant solution: it has been used to add some variability to the checkerboard. if ((i+j)%2 == 0) x = 'a'; else x = 'b'; 77 PHP provides a better mechanism for building tables, but the concept is the same. 78 In this case, language mixing is not a choice: it is the only feasible solution.

53 Changing the page The document.write statement should only be used when building a page; when used in an event, it erases the content of the page last, as the example shows. <input type=button onclick='test();' value='write'>... function test() document.write('disaster'); The test event builds a totally new page, erasing the previous content completely. Clearly, the only way we have of affecting the elements is giving them an id attribute, then calling them up with an event. The next exercise will be changing the background color of any given <td> of the checkerboard. First, let us see how to assign the id, by slightly altering the table building loop: document.write('<td id="' + i + '-' + j + '"...>' +... How does this work? By simulating the corresponding HTML code (shown here for a 2x2 table): <td id="1-1"...>1</td> <td id="1-2"...>2</td> <td id="2-1"...>11</td> <td id="2-2"...>12</td> Then we may build another table, containing a series of links to affect each <td>: document.write('<td><a href=javascript:change(' + i + ',' + j + ') >'...); And the corresponding simulated HTML: <a href="javascript:change(1,1);"...>1</a> <a href="javascript:change(1,2);"...>2</a> <a href="javascript:change(2,1);"...>11</a> <a href="javascript:change(2,2);"...>12</a> The two faces of the page The id attributes have been chosen so as to associate each element with its coordinates in the table. The script shown here features a couple of things. The first function disposes of the need to call each time the document.getelementbyid method, which is rather cumbersome to write (clearly, the name of a function called get is speedier). As for the action on the elements of the checkerboard, we can see how to do it by changing the classname attribute. This would be valid if we had used classes in the table; of course, it would still be possible to modify the style.background attribute, as in preceding examples. function get(x) return document.getelementbyid(x) function change(i,j) c = get(i+'-'+j).classname; if (c=='a') get(i+'-'+j).classname = 'b'; else get(i+'-'+j).classname = 'a'; The table after some tinkering

54 Interacting with pages The ability to unchain events and to affect the page greatly adds to HTML interactivity, which is limited to <submit> and <reset> buttons (and, to some extent, to the :hover pseudo-class). Now it is time to sum up the minimum amount of elements for the most basic JavaScript interaction: Textboxes, which contain input data, and are accessed through their id property; as in most input elements, their content is stored in a property called value (i.e.: the content of a textbox with id box1 can be inspected with box1.value); Input buttons, linked to events through their onclick clause (alternatively, anchors can also be used); DIVs, where output data can be shown by resetting the innerhtml property. JavaScript, activated via an event, accesses input data from textboxes with the getelementbyid method, process them in the normal programming language fashion (using structured, modular programming with an eye on C/C++), then store the results into DIVs, again with getelementbyid. Building an output string is made easier by the loose combination of string and numeric data. Any formatting (normally line feeds and styles) must follow the HTML rules, so some care is needed when preparing output strings, so as not to foul the results with misplaced or mistyped tags. Again, script brevity (and clarity) greatly helps, as Steven Winikoff aptly comments: In the end, programming style is about writing code that's easy to read. Easy to read means easier to modify....but it also means code that's more likely to be correct in the first place. Good style can and should become a habit! Our next examples will add a touch of arithmetic to our scripts, so as to see more complex stuff. First, we will process two numeric data, giving an answer after a brief calculation. The associated HTML and JavaScript elements are written in the same color. One thing to keep in mind is that textbox values are always of type string, and so must be converted into numeric data: this can be done with the parseint function, which returns an integer value (for decimal values, there is another function, called parsefloat). As there is no guarantee that the conversion is successful, the result should be checked with the isnan(x) function, which verifies is the argument is indeed a finite number (or rather, the contrary: since it works on a reversed logic, checking for a number requires the result to be negated, i.e.:!isnan(x)). Here are the basic elements of the exercise. Note that textboxes have preset values, a common practice used to speed up input for debugging purposes: once the functions work properly, preset values are removed. <input type=textbox id=box1 value=17 style='width:30px'> <input type=textbox id=box2 value=4 style='width:30px'> <input type=button onclick='test()' value='check' title='click to verify'> <div id="out" style="width: 300px; height: 100px; border:ridge peru"></div> function test() var n, d; n = parseint( get('box1').value); d = parseint( get('box2').value); if (! isnan(n) && n > 0 &&! isnan(d) && d > 0 ) if ( n % d == 0 ) get('out').innerhtml = n + ' is a multiple of ' + d; else get('out').innerhtml = n + ' is not a multiple of ' + d; else get('out').innerhtml = 'Invalid input';

55 By the book The last example has a serious design flaw, since it mixes input/output and data processing statements in a way that could generate confusion in the project and in the scripts therein. Interaction is one thing, and data processing is another. In the next example, a more complex arithmetical problem will require an independent function, totally detached from the dialogue with the Web page. The event script will act as a buffer between HTML and the js functions associated to the actusl problem. The problem is to verify if a given number is prime. For a twist, we will add a common input support, consisting of two buttons which modify the input box value, one by +1 and the other by -1: the whole concoction (textbox and buttons) is sometimes called a spinner control (since it allows the user to spin through integer values). Once again, only the elements involved in the interaction are listed: <input type=textbox id=box value=17 style='width:30px'> <input type=button onclick='test()' value='check' title='click to verify'> <input type=button onclick='spin("box",+1);' value='+1' title='add 1'> <input type=button onclick='spin("box",-1);' value='-1' title='subtract 1'> <div id="out" style="width:300px; height:100px; border:ridge peru"></div>... function test() var n; n = parseint( get('box').value); if (! isnan(n) && n > 0 ) if ( prime(n) ) get('out').innerhtml = n + ' is prime'; else get('out').innerhtml = n + ' is not prime'; else get('out').innerhtml = 'invalid input'; function prime(n) var i,c; c=0; for ( i=2; i<=n/2; i++) if ( n % i == 0 ) c++; if (c==0 && n>1) return 1; else return 0; function spin(o,n) var x; x = parseint(get(o).value); get(o).value = x + n; BONUS: a different, subtler version: The spinner effect could be obtained with direct scripts, although this is discouraged. But since it may happen to find something similar around the Web, here is one way to alter the box (both ways): <input type=button onclick='get("box").value++;' value='+1'> <input type=button onclick='get("box").value--;' value='-1'> function prime(n) var i; i=2; while( i<=n/2 && n%i!=0 ) i++; return (i>n/2 && n>1); Enhancements: Faster search loop exit (in most cases) Direct evaluation of the return condition.

56 The prime function is likely to be used in innumerable problems on numbers (mainly integers). In previous studies, several useful functions have been stored into a Python library, to be attached to any program with the import directive (or a C/C++ library requiring the #include directive). The JavaScript equivalent is a file saved with the.js extension (as in: functions.js), and a directive in the HTML document. The library should only contain JavaScript code. Some of the functions deal with the digits of a number; some deal with prime numbers. Besides numeric functions, it should also include the spin function, which will be used extensively. This is how the library should look: function digits(n) // Finds the number of digits of "n" var c,x; c=0; x = Math.floor(Math.abs(n)); while( x > 0 ) // Demolition c++; // Count x=math.floor(x/10); return c; function digit(n,p) // Returns digit of "n" in position "p" (1=units) var i,x,z; z = Math.floor(Math.abs(n)); for( i=1; i<=p; i++) x=z%10; z=math.floor(z/10); return x; function sumdigits(n) // Sums the digits of "n" var i,s; s=0; for ( i=1; i<=digits(n); i++ ) s+= digit(n,i); return s; function prime(n) // Is "n" prime? var d; d = 2; while ( d <= n / 2 && n % d!= 0 ) d++; return ( d > n / 2 && n > 1 ); function nextprime(n) // Find next prime number (>=n) while (! prime(n) ) n++; return n; function spin(o,n) // Event for spin button var x; x = parseint(get(o).value); get(o).value = x + n;

57 The directive containing the link to the library could be in the <head> element, so that the library can be available at any moment (including the onload event). The <script> tags refer to the file name: <head> <script src="functions.js"></script> </head> The <body> will contain interaction elements (boxes, buttons, and DIVs). In this example, three numeric problems are shown, all dealing with the number written by the user in the textbox with id 'box': Verify if a number is prime (using the prime function in the library) Verify if a number is a Harshad number (using the sumdigits function in the library) Verify if a number is a Gapful number (using the digits and digit functions in the library) <input type=textbox id=box value=1729 style='width:50px'> <input type=button onclick='spin("box",+1);' value='+1' title='add 1'> <input type=button onclick='spin("box",-1);' value='-1' title='subtract 1'> <div id="out" style="width:300px; height:100px; border:ridge peru"></div> <!-- These three buttons link to different solutions --> <input type=button onclick='test(1)' value='next prime' title='next prime'> <input type=button onclick='test(2)' value='harshad' title='is it a Harshad number?'> <input type=button onclick='test(3)' value='gapful' title='is it a Gapful number?'> </body> </html> <script> function Harshad(n) // Solution 2 return (n%sumdigits(n)==0); function Gapful(n) // Solution 3 g = digit(n,digits(n))*10+digit(n,1); return (n%g==0); function test(i) // This is the wrapper function // Parameter "i" depends on which button was clicked var n,z; n = parseint( get('box').value); if (i==1) // First button (the function is in the library) z = 'next prime: ' + nextprime(n); else </script> if (i==2) // Second button z = 'Harshad? ' + Harshad(n); else if (i==3) // Third button z = 'Gapful? ' + Gapful(n); if (! isnan(n) && n > 0 ) out.innerhtml = z; else out.innerhtml = 'invalid input'; The example shows how different input buttons can call a wrapper function with different values of the argument. A wrapper is a function whose only purpose is to call other functions. In this and other similar situations, the wrapper function test is also the interface with the Web page, acting as a bridge between HTML elements and numeric solutions. The wrapper is the only place where HTML and JavaScript meet. The numeric solutions should never be concerned with HTML code.

58 This example shows how to modify given elements of a page. It is the simulation of an elevator, where the lone passenger (Mario the penguin) can be transported to any floor by the click of a button. The field of action can be depicted with a <table> with one floor per row: in the simplified view each row has two <td> elements, one for the floor button (an <input> element) and one for the passenger (an <img> element). Two images suffice: one contains the passenger (Mario.bmp), while the other is a blank white raster of the same size (nomario.bmp) for the empty floors. Each button is associated to an event: for the sake of simplicity, the corresponding function is only one, and the variability is provided by the argument (corresponding to the floor where the elevator cab is sent). The cells containing the images must have an id clause, or JavaScript would not be able to reach them. If the table were built relying too much on HTML, it would be quite cumbersome: <table> <tr> <td><input type=button onclick="move(9)" value=9></td> <td id=td9><img src= "nomario.bmp"></td> <td><input type=button onclick="move(8)" value=8></td> <td id=td8><img src= "nomario.bmp"></td>... <td><input type=button onclick="move(1)" value=1></td> <td id=td1><img src= "mario.bmp"></td> </table> With a careful use of a loop index, the table can be constructed quite simply, by mixing the JavaScript variable with the fixed part of the HTML code. A state variable 79 is added, to keep track of the position of the elevator cab (at the start of the game, the cab is at the first, or ground, floor). mario = 1; // state variable; initial value: floor 1 for(i=9;i>=1;i--) document.write('<tr>'); document.write('<td><input type=button '); document.write('onclick="move(' + i + ');" value=' + i + '>'); document.write('<td id=td' + i + '>'); if (i==mario) document.write('<img src=mario.bmp>'); // passenger else document.write('<img src=nomario.bmp>'); // empty floor document.write('</td>'); document.write('</tr>'); The event should clear the starting floor image and make the passenger appear at the desired floor. We can also introduce a new function to avoid repeating document.getelementbyid throughout the scripts, substituting it with a call to said function, and greatly shortening the references. function get(id) return document.getelementbyid(id); function move(i) get('td'+mario).innerhtml = '<img src=nomario.bmp>' // disappear from floor get('td'+i).innerhtml = '<img src=mario.bmp>' // reach new floor mario = i; // modify state variable 79 In systems theory, a state variable is any data which corresponds to a given state of a system (which is the object to be studied). In the case of the elevator, the floor where the cabin is.

59 Timers and new windows With the following examples, we will see how to activate a timer (which is one of the events that JavaScript can intercept), with the added bonus of learning how to open a new browser window. A new window can be opened, not surprisingly, with a method named window.open, which usually takes three optional arguments: URL, mode, and specifications. window.open([url],[mode],[specifications]); A blank URL opens a blank page. The opening mode has two possible values: _blank (a new tab the default) _self (the current page will be replaced) The specifications are in a comma-separated list which can include the metrics (in pixels), and other options regarding the appearance of the page (menubars, scrollbars, toolbar, titlebar): height=pixels left=pixels top=pixels width=pixels menubar=yes no status=yes no titlebar=yes no toolbar=yes no These two statements are equivalent, and will open the referred page in a new tab: window.open(" window.open(" Explicitly opening a new URL in the same window (with the "_self" clause) requires some care, and should only be done with a controlled event. If the script were automatic, the new page would load every time we accessed the page (even if we tried to use the back button, we would bounce to the new page), and the whole situation would be quite illogical. window.open(" // use with care With placement clauses, the page will open in a new browser window: window.open(" If we needed to process the new window after it is opened, we should use a handle 80 to ensure further access to the corresponding resource, in the following fashion: newwindow = window.open("","","width=200,height=100,top=200,left=150"); newwindow.document.write("<p>this is the new window'</p>"); newwindow.opener.document.write("<p>this is the original window'</p>"); newwwindow.opener is, not surprisingly, the original window 80 Handle is a commonly used name for a variable containing a reference to a resource.

60 Our first example of a timed event will delete the new window from view. Timers are activated with the settimeout statement, which contains the name of a function and the time of activation (in milliseconds). After the assigned interval, function disappear will just close the window previously opened, referring to the newwindow variable. newwindow = window.open("","","width=200,height=100,top=200,left=150"); newwindow.document.write("<p>this window will disappear in 4 seconds'</p>"); settimeout("disappear()",4000); function disappear() newwindow.close(); The timeout function can also be written inline (this is suggested only with a short statement): settimeout(function()newwindow.close();,4000); A recurring timer can be se with another function, named setinterval, and cleared (not surprisingly) with clearinterval. The following example activates a simple digital clock in a DIV with an id of txt. The deactivation is done with a button click, which refers to the variable linked to the interval. interval = setinterval("thetime()", 1000); function thetime() today = new Date(); h = today.gethours(); m = today.getminutes(); s = today.getseconds(); // add a zero in front of numbers<10 m = zeropad(m); s = zeropad(s); document.getelementbyid("txt").innerhtml = h+":"+m+":"+s; function zeropad(i) return (i<10? "0"+i : i); <input type=button onclick="clearinterval(interval);" value="stop timer"> Bouncing around the Internet, it may happen to see intervals activated with settimeout (not the best method), by placing another settimeout call at the end of the timed function. In such cases, deactivation requires a cleartimeout statement, provided the settimeout function has been referenced to a variable. Activation and reactivation: thetime(); function thetime()... h = settimeout("thetime()", 1000); This technique is very crude, and is only shown because some developers still use it. For deactivation, we should place this script somewhere (presumably, associated to a condition in the function itself: cleartimeout(h);

61 Strings We have already met JavaScript strings, which are a staple of the language. In fact, it is hard to imagine writing meaningful DHTML code without them. A string is a sequence of characters, normally used to store text (which may be names, addresses, car plates, messages, or the entire Divine Comedy). The following is a string constant, commonly called a literal: "Here's your crowbar and your centrebit" String variables usually get their value from input elements, so it is very common to find statements like: var address, zip; address = boxaddress.value; zip = boxzip.value;... Some key concepts: Strings can be classified as alphabetic (letters only), numeric 81 (digits only), alphanumeric (any combination of letters, digits, special characters). JavaScript has two string delimiters, single and double quotes (' and "); of course, a string initiated with one separator must be terminated with the same one. Having two delimiters helps when a string contains a quotation, as in: alert("press 'OK'"); Each string has its length 82 (for example, "abcde".length returns 5); The first character of a string is in position ZERO (like in C/C++); The last character of string is in the position defined by the string length minus 1 (counting zero as the first position): for example, the last character of a string variable named a is in position a.length-1; A blank space occupies one position, just like any other character; Leading and trailing spaces are integral parts of the string (they may not appear in Web pages, but only because HTML does not render them); The same consideration apply to sequences of two or more spaces; A string with length ZERO is called an empty, or null, string; it is not easy to spot in a script, being initialized with '' or "" (NO spaces in between); "" is not " ", if only for their different lengths; A JavaScript string is immutable, i.e. it cannot be modified: it can, however, be replaced by a new expression, possibly involving the previous value (e.g.: a=a+"x";); A string can be visualized as an array of characters; and while in C/C++ this is exactly how strings are stored, in JavaScript the two structures are analogous (but not quite identical: ignoring the differences could lead to incorrect assumptions and consequent programming errors). By far, the most common string operation is the sum of one or more strings (as in "blue " + "dress"). The other common operations are: Deleting part of a string ( They could not hit an elephant becomes They hit an elephant ) Inserting a string into another ( I will go there becomes I will never go there ) Replacing 83 a substring with another ( I like cod becomes I ate cod ); Searching for substrings ( employ is a substring of unemployment, zipper is not). The symbol of the blank space 81 A numeric string is not a number, even if may look like one. 82 Since strings are objects, their length is called a property; some functions associated to strings are called methods and carry parentheses. The rules of OOP syntax also apply, so that properties and methods are prefixed by a dot operator, as in x.length (numeric property of a string) or in x.touppercase() (a method that returns the value of the string in capital letters). 83 Note that this can be seen as a combination of a deletion with an insertion.

62 Arithmetic on the G string? As we have already seen, JavaScript has a preference for strings, as the following example shows: alert("4"+"2"); // result: 42 (string concatenation) alert("4"+3); // result: 43 (the number is cast to "string") JavaScript numeric strings may have one really quirky behavior, as they can actually be used in calculations. Consider the following snippet: alert("4"*"2"); // result: 8 (the strings are cast to "number") Surprisingly, the result is 8. Yet, it would be foolish to resort to this sort of tricks: first of all, sums would fail, as "4"+"2" yields "42" (fail, that is, from an arithmetic point of view: we should expect the sum of two strings to be a string); second, and most important, we should use numbers when numbers are required. parseint, parsefloat These functions (as already seen in the numeric examples) convert string values into numbers: parseint is used for integer values, parsefloat for decimal values. The name of the latter derives from the floatingpoint arithmetic of computer numbers, but does not correspond to the single-precision float type of C/C++: all JavaScript numbers belong to a double-precision Number type 84. So-called integer values are only such for the absence of decimal digits. Actually, the verb parse refers to the syntactical analysis of written symbols, which is carried out according to the rules of a given grammar 85 : in choosing the names for these functions, the concept has been stretched a little bit, to include the actual value conversion. The two functions examine the parameter string in similar ways, accepting all the numeric characters until the string ends or a non-numeric character is met (whichever comes first). Numeric characters include the "+" and "-" signs (provided there is only one of them, and at the beginning of the string), and the decimal point (only for the parsefloat function, and only the first one: a second point stops the parsing, just like any non-numeric character). Clearly, the processing of the decimal point is what sets apart the two functions. Here are some examples of the two functions in action. An asterisk indicates where the parsing operation has been interrupted by a non-numeric character. It may be a little surprise that null and empty strings force the result to NaN. Numeric output parseint("12") 12 parsefloat("12") 12 parseint("87y") * 87 parsefloat("87y") 87 * parseint("730y3") * 730 parsefloat("730y3") 730 * parseint("-12.5") * -12 parsefloat("-12.5") parseint("6 4") 6 parsefloat("6 4") 6 parseint("6-4") 6 parsefloat("7.8.9") 7.8 * parseint("") NaN parsefloat("") NaN parseint(" ") NaN parsefloat(" ") NaN As is already known, JavaScript can cast numbers to strings without specific commands. However, the script may make assumptions which do not fit a specific application. For this reason, there are a couple of methods which can format a custom numeric string (note that numeric constants require parentheses, as the interpreter would mistake the dot operator for a decimal point): (145).toFixed(2) (42).toString() 42 (145.78).toFixed(1) (42).toString(2) The tostring method can code numbers in any base between 2 and may seem a curious choice, but there is a logic: it includes z as a digit, so it is the highest base that includes only alphanumeric symbols (10 numeric digits + 26 letters = 36 symbols). 84 Single precision numbers have 8 significant digits; double-precision ones have 15. They also store larger values. 85 Parsers are those parts of compilers and interpreters that scan statements to check their formal correctness.

63 Operations on strings The most common string methods are the following (shown on a fictitious string s): s.charat(i) extracts the character in the i th position s.touppercase() returns the content of "s", with all letters in UPPERCASE s.tolowercase() just the same, only in lowercase s.slice(i,j) extracts a substring of "s" between the i th and j th positions 86 s.indexof(t,[i]) returns the position of substring "t" in "s", (i=starting position) s.lastindexof(...) searches from the end of the string towards the beginning At the bottom of the page, a brief summary is included. Before examining that, since the behavior of these methods is sometimes different from their counterparts in other languages, we should consider some peculiarities of JavaScript string handling. charat As already said, strings are immutable, so this method can only extract one of the characters of the string. alert( s.charat(i)); // CORRECT s.charat(i) = "z"; // HUGE MISTAKE!!! (d-t) cannot do it touppercase, tolowercase Of course, these methods do not modify the string, either: they return a string with the same general content of the source string, processed accordingly. If we need to modify the original string, it is necessary to store the modified string back to the variable, with the usual assignation operator: slice indexof s = s.touppercase(); x = s.slice(i,j) The final position (the 2 nd argument: j) is not extracted. If the final position is omitted, all remaining character will be extracted If i is not smaller than j, a null string is returned If the second argument is missing (which is the default), the search starts from the beginning of the string; When present, the second argument specifies from which position to start the search; Unsuccessful searches return -1 (some languages return 0, which would be inadequate in JavaScript, as it is an actual string position). Sample values Method calls Results s "We sail the ocean blue" i 8 j 20 t "ocean" u "sea" v "e" s.charat(i) "t" s.touppercase() "WE SAIL THE OCEAN BLUE" s.tolowercase() "we sail the ocean blue" s.slice(i,j) "the ocean bl" s.indexof(t) 12 s.indexof(t,j) -1 s.indexof(v) 1 s.indexof(v,j) 21 s.lastindexof(v) 21 s.lastindexof(v,j) The i th position is included, the j th position is excluded. So "We sail the ocean blue".slice(12,16) returns "ocea", not "ocean" (position 12: "o", position 16: "n").

64 BONUS: the show() and column() methods With JavaScript, it is possible to extend intrinsic objects such as String, Number, Array, and so on. This means that it is possible to write new String methods which become available for any string, and are called in the same OOP fashion as the predefined ones. Two such examples are a couple of methods, written (with JavaScript code and CSS styling) for a scenic display of strings, called show and column: s.show(div) s.column(div) displays the string (with positions and length) in a DIV a similar display, only VERTICAL Normally, the argument of the method will be the id attribute of a <div> element of the <body>. Just like all the other JavaScript methods, the methods can be sent 87 to either string constants or variables. The following examples show two possible renderings (the "S" by the length stands for String): "We sail the ocean blue".show("div1"); s="abc"; s.column("div2"); Once again, this method is not part of the JavaScript String object: it is a custom 88 method. It can be (and actually is) stored in a function library, to be included into the current page with a <script> tag; the same applies to the CSS file (with a <link> tag), so that the <head> element could end up as follows: <script src="show.js"> </script> <link href="show.css" rel="stylesheet" type="text/css"> Of course, the method would only work if a valid DIV (either the object itself or its ID) is supplied in the call statement, and the supporting files (js library and CSS) are present in the same folder. Without a valid DIV, or without the js library, the interpreter would abort the script. The absence of the CSS would be a less serious offense, as the method would work anyway, but without the styling effects: This is a brief, but complete example of the method, along with three possible calls: <html> <head> <script src="show.js"> </script> <link href="show.css" rel="stylesheet" type="text/css"> </head> <body> <div id=out1></div> <div id=out2></div> <div id=out3></div> <script> "sample 1".show("out1"); ("sample 2").column(out2); a = "sample 3"; a.show(out3); </script> NOTE The method is written in such a way as to properly work with two ways of selecting the target DIV: the DIV id (as in the first line of the script) the DIV object (as in the second and fourth NOTE: the js code of the method, although nothing special, could be a little advanced for this course. In a later chapter, we will study how to write simpler custom methods. 87 This is the term, in OOP jargon, for the calling of a method. 88 Custom refers to any extension of built-in features.

65 Solved problems Alternating uppercase and lowercase letters This example is totally useless in the real world, but it is used show compound functions, i.e.: the result of one function is fed into another function. The functions are executed in a left-to-right mode, with two (and possibly more) dot operators in sequence. Sometimes, for the sake of clarity, partial results can be included into parentheses, as is shown in one of the lines: function alternating(s) // input: donkey; output: DoNkEy var i,t; t = ""; for( i=0; i<s.length; i++) if ( i%2 == 0) t+= s.charat(i).tolowercase(); else t+= (s.charat(i)).touppercase(); return t; Reversing a string The reversed string problem, yet another useless in itself, can set an example of char-by-char processing. The problem can be solved with a reverse loop, which extracts one character at a time, appending it to a new string (of course, the result will be in reverse order). The new string must be initialized to a null string, just as a counters and sum variables are set to zero at the beginning of the corresponding process. This way, sums of numbers and sums of string truly become analogous 89 operations. function reverse(s) // input: watch; output: hctaw var i,t; t = ""; for( i=s.length-1; i>=0; i--) t+= s.charat(i); return t; Building a proper name function sum(n) var i,t; t = 0; for( i=n; i>=1; i--) t+= i; return t; Proper names (first letter in uppercase, the rest of the word in lowercase) are actually used in applications. This example, besides being taken from real life, shows the slice method called without the terminating position (which causes the extraction to include the remainder of the string): function proper(s) // input: donkey; output: Donkey return s.charat(0).touppercase() + s.slice(1).tolowercase(); As already specified, JavaScript strings are immutable: they can be modified only by reassigning a value in the calling program, possibly combining multiple calls in the same statement. We can track the sequence of value changes in the following snippet: s = "abcdef"; s = proper(s); s = reverse(s); s = reverse(proper(s)); // original value // now "Abcdef" // now "fedcba" // proper before reverse (capital F); now "abcdef" Note that the calling order matters, as proper(reverse(s)) would yield "Abcdef", with a capital "A". 89 In science, analogous phenomena are those who can be studied with similar methods. For example, the zero value and the null string "" are the neutral elements of the respective sums.

66 Character or substring substitution/deletion One very common error is to mistake JavaScript strings for arrays, using the charat method like a general identifier for a character. While the assumption works when reading the value, or storing it into a variable, by no means it is valid for character substitution. The following is just plain wrong: s.charat(i) = s.charat(i).tolowercase(); // HUGE MISTAKE!!! (d-t) s[i] = s[i].tolowercase(); // JUST WON T WORK This is wrong because functions cannot be to the left of an assignment operator, i.e.: functions cannot be assigned values. What they do is calculate values, which cannot be changed, since they do not have an entry in the symbol table. Substitutions can only be done by dividing the string into 3 parts, discarding the one in the middle and keeping what is before and after it 90. The string can then be reassigned by combining the first part, the new substring, and the third part. This is how the preceding statement should be written: s = s.slice(0,i) + s.charat(i).tolowercase() + s.slice(i+1); This works when substituting one character. Changing a substring of any other length will presumably not use the charat function, nor call the second slice with the same expression, but the resulting statement will be similar: s = s.slice(0,i) + something + s.slice(j); Of course, i should be smaller than j, or there would be some substring overlapping, and nothing would be deleted. For example, the following snippet would actually duplicate part of the string: s = "We sail the ocean blue"; alert( s.slice(0,8) + "-" + s.slice(2)); The result of this attempt is "We sail sail the ocean blue". Similar considerations apply when deleting parts of a string (only, without a new substring in the middle). String normalization This operation is sometimes called purging, as it erases redundant blank spaces, three kinds of which exist: leading (" xyz"), trailing ("xyz "), and multiple ("x y z"). Leading spaces can disrupt the alphabetical order of strings, since their ASCII code is 32, smaller than any other character 91 ; trailing spaces are the least dangerous, but they still could generate spurious data; multiple spaces can disrupt single-character searches. In any guise, redundant spaces are unwanted material. The aptly named trim() method deletes leading and trailing spaces, which disposes with the need to examine either end of the string. Multiple spaces can be dealt with by locating double spaces 92, then looping through the search, removing one space per step: at the end, any sequence of any number of spaces is reduced to a singleton (after all, there can be only one 93 ). The following function returns the purged copy of its parameter s. The call to function space makes the script more readable: the expression space(2) identifies the object of the search, whereas the corresponding string literal " " could be easily misread. The function is also reusable in any other application. function purge(s) var c; s = s.trim(); c = space(2); while( (i=s.indexof(c))>=0 ) s = s.slice(0,i) + s.slice(i+1); return s; function space(n) var s; s = ""; for( i=1; i<=n; i++) s+=" "; return s; 90 When operating at either end of the string, one of the remaining parts could be a null string. 91 ASCII codes from 0 through 31, called control characters, are used mostly in communications. 92 By means of a substring search, since they could be anywhere in the string. 93 Highlander (1986),

67 Extending the String object JavaScript allows objects to be enhanced with new methods. Any string function, for example, can be added to the String object with a few changes: String.prototype.proper = function() return this.charat(0).touppercase() + this.slice(1).tolowercase(); String.prototype.reverse = function() var i,t; t = ""; for( i=this.length-1; i>=0; i--) t+= this.charat(i); return t; The new methods can (actually, it must) be called in OOP fashion thus allowing to write the sample snippet of the Solved problems section like this (note that compound methods read differently from compound functions, the former being executed left-to-right, and the latter right-to-left ): s = "abcdef"; // original value s = s.proper(); // new: "Abcdef" s = s.reverse(); // new: "fedcba" s = s.proper().reverse(); // proper before reverse; new: "abcdef" Using methods has one additional advantage, in that it disposes with checking parameter types. In regular functions this should be done to avoid runtime errors caused by using an operator on the wrong type of operand. In the previous examples, this has not been done, for the sake of simplicity: in the real world, before using string methods such as charat or touppercase, we should proceed with caution, providing a safe exit in the case of a wrong call. This is how a function should be written: function proper(s) if ( arguments.length < 1 typeof(s)!="string" ) return ""; else return s.charat(0).touppercase() + s.slice(1).tolowercase(); The script checks two conditions: At least one parameter should exist: the expression arguments, known as a collection 94, refers to all the arguments specified in a calling statement, and, quite understandably, arguments.length evaluates its length; The first (and presumably the only) parameter should be a string: this can be verified with the typeof function, which returns the type of any expression as s string 95. When any of these conditions is not met, the function returns a null string. Note that the presence of more than one argument has no effect of the script. When the new function is written as a method of the String object, it is assumed that it will be sent to strings only, and the initial test can be safely omitted. Safely, that is, to a point, as it is still possible to send a method to an object of the wrong type, as in (87).proper() (which would abort the script), but any programmer who did that would soon be out of a job. NOTE: the same considerations apply to the extension of any other JavaScript object (more on this later). 94 JavaScript collection are actually arrays (e.g.: the first argument of a function call is arguments[0]). References to missing arguments return a value of undefined. 95 This function is necessary in a loosely typed language like JavaScript. In strongly typed languages such as C/C++, the compiler detects assignment mismatches and denies the building of the corresponding machine code.

68 Searching for words Words are those parts of a string which are enclosed between consecutive two blank characters. That s where a normalized string is needed: unwanted spaces may generate empty words, possibly fouling the processing (and the reconstruction) of the whole phrase. Let s consider the string "We sail the ocean blue". Suppose that, with the indexof() method, we have managed to set "i" to 2 and "j" to 7: s.slice(i+1,j) extracts the word "sail", which can be processed as desired. The same applies for any such pair of indexes, as shown here: A single loop will suffice for the indexes to proceed along the string, provided that the search for each new blank started from the last position reached. Having "i" chase "j" is not a great deal; the situation, however, is not quite as clear at the boundaries of the phrase (that is, the first word and the last). The first word can easily be identified by setting the initial value of "i" to -1. The real problem is at the end, when "i" is 17 and "j" becomes -1, which is the result of the unsuccessful search for another blank. One simple solution is to attach a blank space at the end of the string, thus ending up with the correct value of 22 for the forward index "j". It may sound silly to go through the trouble of normalizing the string, then adding a redundant space of the same sort as the ones we have struggled to delete. The point is that the trailing space is not of the same sort after all, being a totally different beast: besides being placed there for the purpose of coping with a search result which disrupts the algorithm, the extra space is temporary 96, being added only for the duration of the function, quietly disappearing at the end of the process. The skeleton for this procedure is the following: function words(s) c = space(1); s+= c; i = -1; j = s.indexof(c); while ( j >= 0 ) word = s.slice(i+1,j); BEWARE!!! The function does not specify what to do with each word. This is left as an exercise.... // Processing the single word i = j; // "i" reaches the "j th " position j = s.indexof(c,j+1); // Search for the next blank A much simpler solution, however, is to transfer each word of the string to an element of an array: the processing can then be done individually, visiting the array with a basic loop, also disposing with the need for a slack space. JavaScript has built-in functions for both string-to-array and array-to-string transfers. Aptly named split() and join(), they require to be specified a separator character (a good candidate is the blank space, provided the string is purged). The general outline of the solution is as follows: a = s.split(" "); // Store the words into array "a"... // Process the array s = a.join(" "); // Reconstruct the sentence from array "a" But first we need to know a bit about arrays. This will be the topic of the next chapter. 96 Normally, the space is called a slack data, in that it is used, then discarded without further effects.

69 Arrays Arrays should be known from previous courses. JavaScript arrays are no exception to the general rule, being collections of data, identified by their position (also called index). But, as most things in this language, arrays are also JavaScript objects; as such, they also have properties and methods, and they can be extended by adding new components to the general Array object. An example of array could be a list of the temperatures of one week: 25,30,28,34,32,35,36 Arrays can be declared in several ways: a = new Array(); // Empty b = []; // Empty (recommended for execution speed) c = new Array(4); // Four elements, none of which defined d = [1,5,3,2]; // Direct value assignment Some considerations apply: The first element of a JavaScript array is in position zero (like C/C++ arrays); Unlike C/C++ arrays, JavaScript arrays are elastic (i.e.: their length can vary, as elements can be added or deleted); The length of an array is a property (like the length in strings); The last element of array a is in the position a.length-1 (length minus one, due to the presence of the element in position zero). The default value for unassigned array elements is undefined (as in array b of the second example); JavaScript arrays are linear (or mono-dimensional); with some tricks, it is possible to mimic matrices (multi-dimensional arrays, with any number of dimensions), including the familiar syntax a[i][j]; matrices, however, are outside the scope of this course, as their use in Web applications is limited. Some of the most common methods for assigning and extracting values are listed below: d.push(...); // Append at the end of the array (sequence) d.unshift(...); // Insert at the beginning (sequence) d.pop() // Remove last element d.shift() // Remove first element d.splice(p,n); // Remove n elements starting at position p d.splice(p,n,[...]); // Remove, then insert (sequence) d.reverse() // Flips the array d.sort() // Sort elements (default: ascending order) d.slice(p,n); // Copy n elements starting at position p The pop and shift methods are limited to just one element. The push, unshift and splice support any number of elements (example of a sequence: 31,92,55,32,9,33). The following sequence of calls shows the methods in action. At each step, the new elements are written in green; the elements written in red are those which the following method would remove from the array: d.push(21); 21 d.push(31,32,33); 21,31,32,33 d.unshift(41); 41,21,31,32,33 d.unshift(51,52,53); 51,52,53,41,21,31,32,33 d.pop(); 51,52,53,41,21,31,32 d.shift(); 52,53,41,21,31,32 d.splice(3,4); 52,53,41 d.splice(1,1,61,62,63); 52,61,62,63,41 d.reverse(); 41,63,62,61,52 d.sort(); 41,52,61,62,63 target = d.slice(1,3) 52,62,62 (new array)

70 Arrays gone wild JavaScript arrays really are strange beasts, and some of their characteristics are not matched in any other programming language. I m not that kind Following the loose typing conventions of JavaScript, arrays can have dishomogeneous elements. Sometimes this turns out to be useful, especially in data processing applications. For example, let s consider the pitchers statistics of game 6 of the 1991 World Series: Atlanta Braves IP H R ER BB SO Avery Stanton Pena Leibrandt (L) Minnesota Twins IP H R ER BB SO Erickson Guthrie Willis Aguilera (W) Each pitcher 97 can be associated an array of data, listing two alphabetic strings (name, decision) and six numbers (innings pitched, hits, runs, earned runs, bases on balls, and strikeouts). For example, the box lines for Leibrandt and Willis could be assigned with these statements: a = new Array("Leibrandt", "L", 0, 1, 1, 1, 0, 0); b = ["Willis", "", 2.2, 1, 0, 0, 0, 1]; Any data you like Truly, there are no limits as to what can be stored into an array: numbers, strings, links, boolean values, dates, other objects, other arrays, even (on a more advanced level) functions. Actually, one method for obtaining matrices is setting up arrays of arrays: in mathematical problems, some care must be taken to ensure that all the rows have the same length, but in other applications anything could go. a = [["x","y","z"],[1,2,3],[14,"zzz",false]]; b = [23,"xyz",[1,2,3],14]; c = [23,new Array(),"<img src='mario1.bmp'>",[1,2,3],14]; Extensions The position of array elements, normally (and quite obviously), is an integer value. But there is more to it than meets the eye, as JavaScript allows for the use of string indexes, which at first may look baffling: a["x"] = 2; a["y"] = 5; Items assigned to string-indexed positions (normally called keys) do not appear in the usual output statements (document.write, alert), as these use only numbered position. This is because we are not stretching the array: what we are doing is extending the object a with new properties that show up only when directly referenced. In fact, the same can be done with the classic OOP notation, with the dot operator, just like this: a.z = "1800, 5th Avenue"; // Usual OOP notation As a matter of fact, js property qualifiers can be really anything: boolean values, dates, arrays, you name it. Why anybody would use them is unclear, but here are some (useless, but still legit) examples: a[false] = 2; // Boolean index a[new Date()] = 2; // Date index (today s date) a[[1,2]] = 2; // Array index 97 In theory, the whole table could be stored into a two-dimensional array, including headers; in the real world, however, a Web application would generate a HTML table, row by row, using a linear array.

71 Scenic display for array (or was it for strings?) It is common, especially during debugging, to display or write the content of arrays. Normally, this is not too difficult, as the elements are clearly visible. a = [4.5,2.1,3.6,6,5,11.54]; alert(a); document.write( a+"<br>"); Both statement produce a comma-separated strings comprising all the elements of the array, where the only reading problem is telling the decimal points from the commas: 4.5,2.1,3.6,6,5,11.54 Empty arrays are more puzzling, as nothing at all appears, either in the dialog box or on the screen, but this can still be deciphered easily. Wild arrays, on the other hand, can be difficult to decipher, when displayed with the basic tools. For example, with arrays of arrays it is impossible to know which commas are used for which (the main array or any of its elements): DECLARATION [15,"xyz",[1,2,3],14] [23,"xyz","<img src='mario1.bmp'>",[1,2,3],14] RENDITION 15,xyz,1,2,3,14 23,xyz,<img src='mario1.bmp'>,1,2,3,14 The write method for the second array goes as far as producing the actual image: This is where the loose typing of JavaScript and the analogy 98 between strings and arrays come in handy. Considering that their atomic components are addressed in the same way (a[i]), it is possible to use the same scenic display scripts written for strings, adding them to the Array object as well. And, this may be a surprise, it is not even required to rewrite the scripts. This only requires one statement per each method: Array.prototype.show = String.prototype.show; Array.prototype.column = String.prototype.column; Besides showing clearly the content, these scenic methods do not fail when they find an image link (not because of special merits: indeed, the same applies for any script which visits an array by looping through the regular numeric positions). Four examples are shown (arrays a, b, c, d, from left to right), with the length of the array signaled by an A, to distinguish it from the string symbol S: a = [23,"xyz",[1,2,3],14]; b = [4.5,2.1,3.6,6,5,11.54]; c = new Array(); d = [23,"xyz","<img src='mario1.bmp'>",[1,2,3],14]; a.show( div1); b.show( div2); c.column( div3); d.column( div4); 98 The analogy stands because of the length property and the access to elements through a numeric index (x[i]).

72 Solved problems JavaScript built-in functions cover most of the routine array operations, such as sorting, flipping, and extracting. This frees the programmer from the burden of writing and testing the corresponding scripts. The following examples, though of little intrinsic value, will be used to introduce some useful features of the language. Flip part of an array Given an array, find two random positions p and q, ensuring that p<q, then flip the part of the array which lies between the two positions. Example: a = [0,1,2,3,4,5,6,7,8,9]; p=3; q=6; // result: 0,1,2,6,5,4,3,7,8,9 We will tackle the numeric part first, showing how to deal with random numbers. The JavaScript tool is the random function of the Math object, a collection of mathematical functions 99. Unlike its C/C++ counterpart, the JavaScript random 100 generator returns a number between 0 (included) and 1 (excluded): to get an integer number it is necessary to multiply the result by some amplification factor, then take the integer part of the new result. An amplification factor of a.length yielding a number between 0 (inclusive) and a.length (exclusive), and the flooring function reduces it to a position of array a 101. The last statement of the script is a delightful JavaScript secret: a quirky, but clever way of swapping the values of two variables. p = Math.floor(Math.random()*a.length); q = Math.floor(Math.random()*a.length); if (p>q) [p,q]=[q,p]; First, we will work on a copy of array a, just to show one of the quirks of the slice method: when called without arguments, it copies the entire content of the array. This is the only way of copying an array to another without structure sharing 102. c = a.slice(); There rest of the solution, with a flip loop, is elementary: while (p<q) [c[p],c[q]]=[c[q],c[p]]; p++; q--; BEWARE!!! c=a would effectively make c one and the same with array a, assigning it the same address. WARNING: a swap function would not work in JavaScript, which always passes arguments by value. The following is not allowed: function swap(&a,&b)... But if we wanted to use array methods so badly, we could use a more convoluted algorithm, splicing array a into three parts, assigning the section to be flipped and the final one to slack properties of a itself (respectively: part 2, called a.flip, and part 3, called a.tail), which will be reduced to the heading section (part 1), as shown in the image, where p=3 and q=6. After flipping the middle section, the concat method will be used to reattach the slack structures to array a. a.tail = a.splice(q+1,a.length); // Part 3 (a.tail) a.flip = a.splice(p,q+1-p); // Parts 1 (a) and 2 (a.flip) a.flip.reverse(); // Reverse a.flip a = a.concat(a.flip,a.tail); // Repack, then reassign 99 Many of these (exponential, logarithmic, trigonometric) are hardly used. 100 Actually, a pseudo-random generator, since it follows an algorithm: for practical purposes this makes no difference. 101 This corresponds to the common technique, used in those languages where the random number generates an integer value, of taking the modulo of the result by an integer divisor n: the final result is still an integer between 0 and n. 102 This is a side effect of certain memory allocations, and causes two or more data structures to overlap same storage positions. A few times this can help, but normally it is to be avoided.

73 Find the smallest element, using a comparison function A couple of other methods of the Math object, min and max, can sometimes be useful in comparisons. They return, respectively, the minimum and maximum value among a list of values, as in: min1 = Math.min(41,63); // result: 41 min2 = Math.min(41,63,4,5,116); // result: 4 max1 = Math.max(41,63); // result: 63 max2 = Math.max(41,63,4,5,116); // result: 116 The lists can be of any length. 103 One way of picking the smallest element of an array could be: x = Infinity; for(i=0; i<a.length; i++) x = Math.min(x,a[i]); Find the smallest element with a vengeance, or The curious sort() method Array sorting looks like an easy task, until one tries to process numbers with different orders of magnitude (that is, when the number of digits differ). In such cases, JavaScript preference for strings shows up, since this is how the array elements are treated: a = [41,63,62,561,52]; // a.sort: 41,52,561,62, is considered smaller than 62, resulting from the comparison 5<6. This is somewhat weird. There is a way out of this unique situation, but it is very awkward, looking more like a kludge 104 than something real. In fact, the trick is to supply the sort method with the actual function to be used for sorting (like most other JavaScript things, functions are objects): a = [41,63,62,561,52]; a.sort( function(a,b) return a-b;); // Ascending: 41,52,62,63,561 a.sort( function(a,b) return b-a;); // Descending: 561,63,62,52,41 BEWARE!!! do not mistake array a for the parameter of the sort function: the former is an actual object, the latter is only a placeholder in the function definition. A most peculiar way 105 to pick the smallest value of an array is: alert( a.sort( function(a,b) return a-b;)[0]); Array object extensions As already noted, the methods and are limited to one element. If we want to add the capability for multiple actions, it is necessary to redefine them. How to do this should not be a secret any more. In these examples, we see JavaScript handling default parameter values with the useful typeof function: Array.prototype.pop = function(n) if( typeof(n)!='number') n=1; // default for(i=1;i<=n;i++) this.splice(a.length-1,1); Array.prototype.unshift = function(n) if( typeof(n)!='number') n=1; // default for(i=1;i<=n;i++) this.splice(0,1); BEWARE!!! Redefinitions cannot refer to the same method they are overriding. This would be like sawing the branch you re sitting on. Fortunately, we have the powerful splice method to rely on. 103 There actually is a limit, which is elements (2 16 ), but it is doubtful that anybody could exceed that in a script. 104 In science and technology, the term refers to a quick-and-dirty, inelegant, clumsy solution to a problem. The word has Germanic roots, and it is obscure how it came to this meaning, especially since klug means clever in German. 105 From Space Oddity (D.Bowie, 1972).

74 Strings and arrays It looks like array methods cover most of the normal operations. Yet, there was one thing that was left pending at the end of the chapter on strings: a simpler way to process words than wandering in search for blank spaces. Now it is time to close the gap, and analyze it a little closer. The problem can be summarized as: 1 transfer the words of a sentence to an array 2 process the words separately 3 repack the array into a single string. Steps 1 and 3, being somewhat intuitive, were already outlined, using the blank space as separator 106. The solutions can be completed with scripts that process the strings, as in the following examples, the effect of which is shown in the images below: s = "We sail the ocean blue"); a = s.split(" "); for (i=0;i<a.length;i++) a[i] = a[i].reverse(); // Reverse EACH WORD s = a.join(" "); t = "go with the flow"; b = t.split(" "); for (i=0;i<a.length;i++) b[i] = b[i].proper(); // Capitalize EACH WORD t = b.join(" "); Omitting the separator would not separate substrings, generating an array with only one element, equal to the string. Exactly why anybody would do this is unclear, as it would only transfer the problem to another variable (we might as well process the string itself): s = "Ich kann nicht anders"; a = s.split(); One curious separator is the null string, which transfers one character per element in the target array. This could turn out to be useful when some array methods are needed (reverse, to name one), or when a character might be replaced with a string of a different length (even with a null character, which would effectively delete the position when repacking the array). The following examples show nothing that could not be obtained with normal string operations, but they should give the idea. Actual problems would analyze the characters, and take the appropriate actions, with far more complicated processes. Normal array visit with character check Deleting some characters Substituting with longer expression z = "hammock"; a = z.split(""); for (i=0; i<a.length; i++) if ( a[i]=="m" ) a[i]="d"; u = "princess"; a = u.split(""); a[6] = null; u = a.join(""); v = "curb"; a = v.split(""); a[3] = "se"; v = a.join(""); Before hammock Before princess Before curb After haddock After princes After curse 106 This leaves unresolved the problem of punctuation signs, but that is outside the object of the course.

75 JavaScript in action It is time to have JavaScript animate HTML documents. In a very simple way, we will create a handful of pages, linked together with JavaScript links, and capable of sending data across the system. Just to give the idea, out small project will comprise three pages: page 1 will be the default one, so it will take the name index.html; the other ones will send some data around. All the pages will show the same menu (this calls for a function to show it). But first, we will do some work on the menu styling. HTML menus are usually unordered lists (<ul></ul>). These objects are, by default, rendered vertically, with bullet marks at the beginning of the individual elements, which are underlined: in many academic Web sites and in most tutorials, the styling is often left to the default, since most of these pages are no-frills manuals, consisting of lists of items and sub-items. We might want to create a more lively setting, like the one on the right, where items are enhanced when hovering over them (as with item Three in the example): Typical rendering of manuals A little bit of flash The default settings to override are the following, along with the element affected.: Line feeds display : inline; li Colors color : olive; a Underlined anchors text-decoration : none; a Hovering color background-color : white; : green; a:hover The HTML code for the new menu sets only need the class attribute: all the styling is in the CSS. <ul class=menu> <li><a href="javascript:alert('one')">one</a></li> <li><a href="javascript:alert('two')">two</a></li> <li><a href="javascript:alert('three')">three</a></li> </ul> <ul> <li><a href="javascript:alert('one')">one</a></li>... </ul>.menu li font-size display.menu li a color text-decoration padding-left padding-right.menu li a:hover color background-color : 20px; : inline; : olive; : none; : 10px; : 10px; : white; : green; BEWARE!!! To avoid side effects, the settings are done on elements belonging to a container of class menu. This way, other list elements and anchors retain their default behavior, or may get still other settings. If, on the other hand, we really wanted all the <li> and their related <a> elements to be affected, the settings would require the general li and li a tag names, as in: li instead of.menu li li a instead of.menu li a li a:hover instead of.menu li a:hover Or, to affect all <a> elements regardless of inheritance: a a:hover

76 More flash A more scenic menu can be obtained with some background tricks. One common technique is to use gradient 107 backgrounds to add some depth to the over-imposed text, with alternate backgrounds to make hovering more evident. Gradient images are available for download in a myriad of Web site; alternate backgrounds can be obtained by flipping the normal one, an easy operation with any image management software. In the example, two bitmaps are used: fade_cyan_down for normal display, and fade_cyan_up for hovering (shown on the right). Again, the selection is on menu item Three. Gradient images in a graphics program(left) and in a browser rendering (right) A somewhat flashier menu.menu background-color border display.menu ul margin padding list-style.menu ul li font-size display.menu ul li a color text-decoration padding-left padding-right background-image background-repeat.menu ul li a:hover color background-image : wheat; : 5px ridge dodgerblue; : inline-block; : 0px; : 10px; : none; : 16px; : inline; : blue; : none; : 10px; : 10px; : url(fade_cyan_down.bmp); : repeat-x; : black; : url(fade_cyan_up.bmp); background-repeat : repeat-x;... <div class=menu> <ul> <li><a href="javascript:alert('one')">one</a></li> <li><a href="javascript:alert('two')">two</a></li> <li><a href="javascript:alert('three')">three</a></li> </ul> </div> Consideration 1 margin:0px limits the empty space around the menu. Consideration 2 Class menu has been moved one step up, to the <div> level, for purely scenic purposes, to obtain a wider area which could contain the menu and other stuff, all neatly packaged into a bordered zone. Explanations and suggestions could be written in a secondary <div>, also contained in the main one. Consideration 3 The bitmaps are only 1 bit wide, but, thanks to the repeat-x attribute, they manage to cover the whole width of the <li> element. 107 In several sciences, a gradient is, simply put, a zone of progressive change.

77 Going vertical As anticipated in the previous page, the menu could be packaged in a different way, with additional info. The following example will add some text to the menu, also showing how to obtain a vertical organization, so as to float the whole <div> to one side of the browser window. This could be done, for example, when the list of choices is very long (not fitting in a horizontal setting), or in data processing application, to use as high a display as possible. Styling and HTML follow, with some comments on the additional settings, of which there is only a handful. The ellipses (...) indicate the same setting as in the previous example..menu... width.menu ul... text-align : 120px; : center;.menu ul li... padding : 4px;.menu ul li a... display : block;.menu ul li a:hover... /* (no variations needed) */.below font-size : 15px; text-align : center; padding : 10px; color : brown; background-color : ivory;.menu float : bottom;... <div class=menu> <ul> <li><a href="javascript:alert('one')">one</a></li> <li><a href="javascript:alert('two')">two</a></li> <li><a href="javascript:alert('three')">three</a></li> </ul> <div class=below> Choose your action by clicking on the corresponding choice </div> </div> ul li a Additional settings The width attribute limits the <div> to a reduced space in the left margin of the page The text-align attribute centers the menu items. It is not really necessary, being more a matter of preferences. The padding attribute slightly distances the list elements vertically. The block setting stacks the anchors vertically, with the same width..below Vertical menu This <div> floats to the lower side of the main container, allowing for some internal padding. It may contain suggestions, prompts, or other info.

78 Linking some pages Now it is time to put HTML, CSS, and JavaScript together, to build our first elementary project. The application will use a main page (index.html) and a couple of pages with forms, to show how to activate, and send data to, other Web pages, analyzing some among the various possibilities. This is not meant to be an exhaustive study, neither of Web design, nor of data processing: the former is outside the scope of the course, the latter is left to the section on PHP. So the following considerations apply; The design is suited for a small screen, as in netbooks and tablets; The menu is of the vertical variety; The main <div> of the previous example is extended with another one, only above the menu; The pages will collect and send a number of data to the main page One of the pages is written in a very basic way; the other is a little more sophisticated; Data are sent to the main page, which will not process them (this is left to the PHP course). The example will focus on the same fictitious criminal organization used in the HTML course, and the exact same data form 108. The main menu (and the whole of the main page) will have the familiar look of the previous example. Since we will be exploring the methods for sending data between pages (GET and POST), only two menu items are needed, one for each method: The page is quite simple: <html> <head> <title>crime & co.</title> <link href="menu.css" rel="stylesheet" type="text/css"> </head> <body> <div class=menu> <p class="above">crime & co.</p> <!-- The only true "new entry" --> <ul> <li><a href="form1.html">post form</a></li> <li><a href="form2.html">get form</a></li> </ul> <div class=below> Choose action </div> </div> </body> </html> 108 This is meant as a joke; yet, there have been rumors, in the past, about organized crime as being one of the first businesses to go computerized. This is very probably nothing more than an urban legend.

79 Form #1 The example has been chosen to deal with the most common <input> elements: textbox checkbox radio select textarea submit button reset button Actual data entry is done through the first five elements; the two buttons operate on the entire form 109. A snapshot of the desired effect is shown to the right. The first thing to be optimized is the menu, which we might want to appear in each page of the application. Since the duplication of code is one of the cardinal sins in computer programming, the best solution is to use a function, which is written only once, then called whenever needed. For most these functions the usual choice is PHP, but a JavaScript function can at least give the idea. First, we need to write a function to display all the menu elements, then store it into a JavaScript library (we might call it, for example, functions.js). Class "above" is for the upper part of the framed <div>: function menu() document.write('<div class=menu>'); document.write('<p class=above">crime & co.</p>'); document.write('<ul>'); document.write('<li><a href="form1.html">post form</a></li>'); document.write('<li><a href="form2.html">get form</a></li>'); document.write('</ul>'); document.write('<div class=below>'); document.write('choose action'); document.write('</div>'); document.write('</div>'); Then, we will include the library with a <script> element, and call the function during page loading, before anything else: <head>... <script src="functions.js"> </script>... </head> <body> <script> menu(); </script>... </body> 109 For custom actions we will resort to input buttons. More on this later.

80 The form elements have already been analyzed in the HTML course, so we will just add a custom <div> to float the form to the right and set a background color:.data background-color : silver; padding : 10px; float : right;... <div class=data> <form action="index.html" id=form1 method="post"> <label for="text">your name</label> <input class=testo type=textbox id=text name=text><br><br> <label for="check">own gun?</label> <input type="checkbox" id="check" name="check" checked><br><br> <label for=sex>gender </label> <span class=notsospecial> <label for="male">male </label> <input type="radio" name="sex" id="male" value="male"><br> <label for="female">female</label> <input type="radio" name="sex" id="female" value="female"><br> </span> <br><br> <label for="sel">main occupation</label> <select class=testo name="sel" id="sel"> <option value=1>hitman</option> <option value=2>robber</option> <option value=3>killer</option> <option value=4>arsonist</option> <option value=5>pusher</ption> </select> <br><br> <label for="area">additional info</label><br> <textarea class=testo id=area name=area rows=5 cols=30></textarea> <br><br> <label for="sbm">send data</label> <input type="submit" id=sbm value="send"> <label for="clr">reset data</label> <input type="reset" id=clr value="clear"> </form> </div> There are a couple of things to be taken care of in the next example: We might prefer the option group to have no selection, unless we decide otherwise. The fixed <option> elements do not sit well in actual applications; it could work for those obvious choices as male/female or similar ones, but needs to be more dynamic. Once again, the language for these sort of things is PHP, but the next example (Form #2) will at least give the idea. Submitting the form to the server activates the main page, along with our input data. Once again, no processing will be done yet: for now, an analysis of the parameters is needed, because of some annoying features of HTML. Of course, this can, for now, only done with the get method, where the parameters are displayed in plain text on the URL line. With this page (which uses the post method), no data is visible, so, after submitting, we end up with one of these URL lines (depending on the browser): file:///d:/web/application/index.html D:\web\application\index.html

81 Form #2 In this example we will take care of the things left pending, adding a bonus JavaScript feature. No selected options This is easily solved by inserting a phantom <option> element with a blank message and the selected attribute on, like so: <select class=testo name="sel" id="sel"> <option value=0 selected> </option>... /* other options */ </select> Options in a function A basic loop through an array of strings will do the job: <select class=testo name="sel" id="sel"> <option value=0 selected> </option> <script> a = ['Hitman','Robber','Killer','Arsonist','Pusher']; for(i=0; i<a.length; i++) document.write('<option value='+(i+1)+'>'+a[i]+'</option>'); </script> </select> The <option> text array is a little out of sync with the <select> values, because of the phantom element: so we have (i+1) and a[i] in the same statement. For the sake of symmetry, we could place another phantom value at the beginning of the array and start the loop from 1. Data sent to the server When we submit the data from form2.html, because of the get method, it is possible to see the call arguments in the URL line of the receiving page (index.html): file:///d:/web/application/index.html?text=a&check=on&sex=male&sel=4&area= file:///d:/web/application/index.html?text=a&sel=0&area= Text elements have no problems: if we wrote just an a in the textbox and left the textarea empty, we could still find them in the page parameters (of course, there would be an empty = sign after the textarea name). The <select> element is also processed correctly, with the value associated to the option chosen (in the first example, it was the fourth option; in the second example, the default choice of 0 was left untouched). Checkboxes and radio buttons, however, have a quirky behavior: when they are left unselected, they do not even appear on the parameter list. This means that the only means that the receiving page has to process those values is to test whether they are undefined or not. There are no if(check==off), nor if(sex==null), nor anything like that. BONUS: assigning focus When a form is loaded, we might want its first element to receive focus, to avoid selecting it with a mouse click. We could use the syntax from either example (provided the names mentioned are unique): <script> get('form1').text.focus(); </script> <script> get('text').focus(); </script> Once again, this is only an example: the language of choice should be PHP. On the other hand, with PHP it is possible to build JavaScript arrays on the fly. The first script would be necessary if another form contained an element with an id set to text. There is a twist, however: in the HTML document, this script must appear after the form, when the interpreter has already met an object with the id attribute set to form1 or text. If the script were positioned before the form, it would abort (as known, beginning from the line following the error).

82 The hidden form trick There is a subtler way to submit a form and its data to a Web page. The trick is to use invisible input elements (i.e.: hidden), submitting the form through an event, be it an input button or an anchor. We need a few additions: A form containing hidden fields. This will result in wasted space on the page, so it is best to leave it at the end. An element unchaining the event. Both a button and an anchor will be added, with the same effect: which one to put in an actual application depends on preferences. The function activated by the event, which will act as a substitute to the submit button. The form is submitted with the get method, just to show the values in the receiving page. From the point of view of the application, we need to add an item to the general menu, affecting all the pages involved; the new page (form3.html) will only need something to unchain a sample event: The new menu The new interaction The <div> for the button and the anchor has been obtained by tweaking the <data> class with an inline styling. Actually, the only inherited attribute of significance is the background color. It is not the best practice, but it is something commonly found on the Internet. <body>... <div class=data style="float:left; margin-top:50px; margin-left:10px; text-align:center"> <span style="color:red;">send hidden data<br><br></span> <input type=button onclick="send();" value="send"> <a href="javascript:send();">send</a> </div>... <form action="index.html" id=form1 name=form1 method="get"> <input type=hidden id=h1 name=h1> <input type=hidden id=h2 name=h2> </form>... </body> <script> function send() get('h1').value = 'oneword'; get('h2').value = 'two words'; get('form1').submit(); </script> When the form is submitted with either event, this is the URL line of the receiving page, showing the two arguments sent along to the server (the blank space in "two words" is rendered with a + sign): file:///d:/web/application/index.html?h1=oneword&h2=two+words One of the hidden fields is set to a compound string, just to see what happens when blank spaces are sent. As is the norm in JavaScript, all data are strings.

83 You re gonna need a bigger boat! Roy Scheider Jaws (1975) JavaScript PHP

84 A walk on the server side As anticipated in previous courses, PHP is a server-side scripting language. As such, its capabilities are much stronger than those of client-side languages: server-side scripts have direct access to the resources of Web servers (at least, those who grant it), and, what s more, they have data processing capabilities, which allow them to affect data through Web applications. But there s a lot more, due to the fact that all these activities take place through the Internet, with all the related problems of data synchronization: for PHP programmers, the real difference is in the working of the internal engine. PHP is a pre-processor, which prepares and sends complete HTML code to the browser (and hence to servers). For this reason, it has a somewhat wicked logic, as data must be accessed before building the page. Dynamicity is still ensured by HTML and JavaScript elements; yet, the changes brought by those actions are limited to the browser window, until some PHP mechanism updates the actual data on the server. PHP has some quite advanced functionalities (such as OOP features). This part of the course, however, will focus on the most basic, which is to access the server file system. By adding yet another management language (SQL 110 ), it will be possible to view data through a database logic, and process them accordingly. But before then, the inner workings of PHP must be firmly grasped. In order to use PHP, a Web page must be saved as.php (as in index.php or about.php). PHP scripts are embedded in such a page by enclosing them between a pair of delimiters (<?php and?>), which, unlike JavaScript (<script>... </script>) identify a single tag. This is one of the details that show how the logical infrastructure of the Web was built piecemeal, with separate, distinct contributes. PHP syntax being very similar to C/C++, many of its statements, including comments, will look familiar. There is a twist, however, as most PHP code would not compile in C, because, in a most peculiar way, PHP variable names require a mandatory dollar sign ($) prefix 111. Also, there are no variable declaration directives 112. So PHP code has a slightly different feel 113, as shown in following example: <?php if ( $x > 0 ) $x = 2 * $x; // inline comment $a = 0; else /* free comment (also multiline) */ $a = $b * $c; for ( $i=1; $i<=10; $i++) $c/=10;?> As in JavaScript, both stray statements and functions are allowed. PHP is also loosely typed, though it has somewhat stronger type checking mechanisms. Here is an example of a function: function prime($n) $i=2; while( $i<=$n/2 && $n%$i!=0 ) $i++; if ($i>$n/2 && $n>1) return 1; else return 0; BEWARE!!! PHP variables are not declared. The one exception refers to the scope (visibility) of the variables. 110 Structured Query Language. The version chosen for this course is MySQL (which is both free and widely used). 111 This may ring a bell to programmers of old versions of BASIC, where a dollar sign postfix was the one and only way of declaring a string variable (e.g.: x$). 112 Actually, there is one, but it only specifies the variable scope, not its type, nor its existence. 113 This way, though, PHP variables will not easily be mistaken for database field names or function calls, so there may be a logic to it.

85 The environment PHP developers need much more than just a browser, as their applications work over the Internet. So, just to get started, we need to access a Web server: arguably, the most popular among open-source HTTP servers is Apache (from the Apache Software Foundation). Then, after learning the basics of the language, we will need data processing capabilities: again, we will resort to the popular choice among open-source Web developers, which is MySQL, a relational database management system 114. This software, however, is impractical to use for data maintenance: the definition and the organization of MySQL databases can be done much more easily with an administrative tool, such as the very popular PHPMyAdmin. The three components can be found in the respective Web sites: Installing separately all the programs, though, can be a little annoying, especially for the uninitiated. But the real problem is not in the software itself. The fact is that it would be almost impossible to write and test our programs in direct contact with a server: development time could increase dramatically, due to the latency of the Internet infrastructure, as every page would require to be uploaded to the server before being examined in detail. Fortunately, there is a global solution to both of these problems, setting up a personal (i.e.: local) Web server. The whole Web environment can be simulated locally, on any computer, with a software bundle, called AMPPS, which smoothly combines and coordinates all the aforementioned programs. Good alternative (also cross-platform) are a couple of packages, XAMPP and EasyPHP. Under GNU/Linux, there is plenty of local server bundles, one of which is called LAMP (standing for Linux Apache MySQL PHP), covered in many Web sites. On other systems, another program described as similar to EasyPhp is called MAMP. The following pages contain overviews of the setup procedures for most of these bundles. It must be noted, however, that any solution developed locally should be, sooner or later, uploaded and tested on an actual Web server for the final test: what s more, the test should be done with different browser, to check that the respective idiosyncrasies do not affect the outcome of the application. For reference and download, some choices are the following: AMPPS XAMPP EasyPHP LAMP MAMP ampps xampp easyphp lamp MAMP 114 DBMS (DataBase Management System) is the historical acronym for specialized data processing software. The relational model, pioneered by the renowned masters Edgar Codd and Chris Date, is the most widely used, having superseded other data organization schemes. The concepts behind relational databases are quite advanced, so they will be studied only in the basic details.

86 AMPPS installation and setup After obtaining the AMPPS setup file, the installation is quite straightforward. When following the defaults, keep in mind that all files should be contained in subfolders of the installation folder. This is under Program Files, or the regional variant, such as Programmi (x86) for Italy. In order to simplify access, a shorter path to the installation may be chosen, such as c:\ampps (a better solution for the uninitiated, but also for experts). The control panel for AMPPS is quite simple. This course uses only the ones in plain sight: Apache (the local Web server), and MySQL (the database engine): The notification area (lower right) there should contain the local Web folder and messages for the successful initialization of the main components of the bundle: C:/Ampps Apache Started MySql Started (or any other choice) The control panel has a couple of useful icons, one (world) for browsing the local host, one (home) for accessing the most common administrative tasks: (AMPPS HOME, green arrow) offers a convenient way to access most operations, albeit the only one of common use will be the phpmyadmin database tool (more on which later): As is always the case, do not store the Web pages in the desktop: it is a poor choice, leading to almost certain errors. The pages should be contained in the default subfolder, or in one of its subfolders c:\ampps\www (subfolder example: c:\ampps\www\testsite) Access is done through the keyword localhost (subfolders included), as in: localhost corresponds to c:\ampps\www

87 XAMPP installation and setup After obtaining the XAMPP setup file, the installation is quite straightforward. For some reason, XAMPP does not like blank spaces: folder and file names should not contain any. The installation folder, for example, should not be Program Files (which is the usual choice, but it contains spaces). The best choice is following the default, which is c:\xampp. The XAMPP control panel is quite simple to negotiate. This course uses only the first two components: Apache Local Web server phpmyadmin Data administration (activated via the Admin button to the right of MySQL). On the first run of the program, everything is deactivated, and the two must be started with the corresponding Start buttons: After this activation, and on subsequent runs, the program shows up with everything in working order: As is always the case, do not store the Web pages in the desktop: it is a poor choice, leading to almost certain errors. The pages should be contained in the default subfolder, or in one of its subfolders: c:\xampp\htdocs (subfolder example: c:\xampp\htdocs\testsite) Access is done through the keyword localhost (subfolders included), as in: As we will see, EasyPHP is more flexible in folder management, in that it allows accessing any local folder by assigning it an alias, which is not restricted to the subfolders of htdocs or www. It does have its fair share of problems, which include the following: Some.dll files may be missing (requiring download and installation); The interface could show up in French; On newer operating systems, items might be displayed in a confusing way. So, things could be made smoother by using either AMPPS or XAMPP. Well-known problems In some situation, the Apache module will abort. The most common solution is modifying its first two config files. The proven remedies are, respectively: httpd.conf Replace 80 with 8080 in two lines, which should become, respectively: Listen 8080 ServerName localhost:8080 httpd-ssl.conf Disable the 443 port in one line (not far from the top), which should become: #Listen 443 localhost corresponds to c:\xampp\htdocs

88 EasyPHP installation and setup The setup program is a classic wizard, which leads through the usual installation steps (installation language, license agreement, destination folder). Everything can be left to the default values. At the end of the procedure, EasyPHP will be added to the program list, with its easily recognizable icon (a lower-case block e with a red dot) When we start it, we can see from the splash screen 115 that EasyPHP is not the actual software: what it does is to act as a launchpad for the activation of the two actual engines (Apache and MySQL). Once we see the green traffic lights, our computer is ready to simulate a complete Web environment. If, for any reason, one of the servers should be stopped (showing a red traffic light), it could be resumed by clicking on the corresponding button, then choosing Start. What we need right now is the Web engine (Apache), which is capable of translating PHP code into HTML. The database engine (MySQL) will be used later. All the administrative tools (including PHPMyAdmin) are not visible in the splash screen, but they can be activated with a right-click menu on the active EasyPHP icon (choosing Administration). As it happens, the very first thing to do is activating the administration page for some housekeeping, that is, telling Apache where to find the local pages. 115 A splash screen is an image that appears while a program is loading; the term is also used to describe an introductory page or window.

89 Setting up the local folders in EasyPHP The administration page is mainly used to associate local folders to each simulated Web site: this is done in the section labeled LOCAL FILES. The other relevant feature, though not to be used right now, is the open button for PhpMyAdmin (both features are outlined in red, and marked by an arrow). Each local folder is identified by an alias: of course, right after the installation the list will be empty. Aliases can be added (clicking the grey link add an alias, immediately to the right of the label LOCAL FILES) or deleted (clicking on the cross to the far right of the corresponding grey line), but, surprisingly enough, they cannot be edited: changing an alias requires deleting it, then setting up a new one. The dialog box for a new alias is quite simple. Step 1 (Create a directory) may already have been done; here, the alias name (2) is linked to the specified folder (3) after the user clicks on the Save link: Once in the list, the alias functions as a link to the corresponding folder. If the folder contains a page named index.html or index.php, it will be activated automatically, as in actual Web sites (if both are present, preference is given to the html page). If not, the new page will show the content of the folder, with links on every page or subfolder present.

90 MAMP installation and setup Browse to the following URL: Go to the download section at the top of the web page, then download the latest version of the software (in this case, as shown in the window below, it was MAMP 3.0.5) Unfortunately the download takes several minutes (at least half an hour) since the file is huge (245 MB). When the download is complete, Setup will automatically start: After clicking on Continue, two folders will be installed: MAMP and MAMP PRO. Do not move MAMP out of the Applications folder or rename it. Along with MAMP, several other packages will be installed, among which MYSQL PRO (a database management system) and MYSQL WORKBENCH. Do not use MAMP PRO, which is not free software. Follow the instructions; when the downloading is complete a closing message will appear: For those who would like more help, there s a page in Italian:

91 PHP and MAMP When the software is launched, a window like the following will show up: As mentioned before, just use MAMP and not MAMPPRO. In the application folder there will be two subfolders called, respectively, MAMP and MAMPPRO: Before launching the server, write a legit PHP document (for example, with TextWrangler for Mac) and save it in the HTDOCS folder (a subfolder of MAMP). PHP pages must be stored in the htdocs folder, or they will not work It s almost done: go to preferences Launch Open on startup replace the one written with the path of the file created before. Launch the server, the corresponding web page will be automatically open in a new tab. YOU CAN CHANGE ANYTHING ON THE DOCUMENT, REFRESH THE WEB PAGE AND THE CHANGES BROUGHT ABOUT WILL BE SHOWN: you don t need to stop and restart the server every time. In some cases, the local server address could be modified to localhost:8888, instead of just localhost.

92 PHP: Hypertext Preprocessor formerly: Personal Home Page Local Server MySQL

93 Accessing the local host Being server-side means carrying a heavier burden than those light client-side scripts. PHP processes a whole document, stored on a Web server (Apache or whatever), before sending any code to the browser. As we will see, this implies going through a parsing of the entire PHP page, which is then translated to pure HTML/JavaScript. The other implication is that, when working locally (i.e.: on our own computer), the pages must be stored in the local Web folder, or one of its subfolders 116. They also must be opened when the local server is active, as the browser works, by default, only on the client side. In fact, when we open a PHP page locally, a standard IP address on the URL line shows that we are linked to the local host: site/thispage.php site/thispage.php The keyword localhost is quite straightforward. It resolves to the numeric IP address (or ::1 in IP version 6), referred to as the loopback address, This address cannot be assigned, either as public or private, and corresponds to the computer in use, simulating an actual server. Besides being used to Web page testing (as in our case), it can be used for debugging purposes, to check if the computer is working on all levels of the ISO-OSI protocol stack. In some cases, slight variations could be needed, such as: localhost:8080//... (when port 80 is detected as busy) localhost:8888//... (in some other cases, and on Mac systems) But these considerations hardly make any difference for the actual Web pages, since the local server works just like an actual one. The huge difference, from the programmer s point of view, is in how a PHP page is put together: whereas JavaScript functions work on elements already known to the browser, here a whole page must be built before being sent to the browser for rendering. Of course, we still can add some clientside scripts, which will be sent to the browser along with the rest of the page. The first experiment that we can make is to write a minimal page, displaying one of the classic welcome messages, then save it as a PHP file (for example, test.php: note that the.php extension is mandatory). Any of the following could give the idea: <?php echo 'hi there';?> or <?php echo "hi there";?> The echo statement is the PHP way of displaying a string on the Web page. PHP code being embedded in HTML, anything outside the script, if present, should adhere to the rules of HTML. For this example, though, we do not need any HTML, as the browser will just display the message between the quotation marks, which can be either single or double, like in JavaScript 117. NOTE When more than one statement are present, the semicolon (;) is necessary, or the pre-processor would give an error message (and rather unclear, at that). The syntax of PHP is loose, but not to that point. A waste of time There is another, almost equivalent, command: <?php print 'hi there';?> print is hardly used for the following reasons: being a function, it spends some time in returning a value, so it is slower than echo; while echo accepts any number of comma-separated arguments, print accepts only one. The examples show the difference between the two, as well as how these statements work with or without parentheses (except when echo takes an argument list): echo "one 2 three 4<br>"; // single parameter echo "one ", 2, ' three ', 4, '<br>'; // list (ONLY WITHOUT PARENTHESES) print(" singleton <br>"); // always a single argument print " singleton <br>"; // with or without parentheses $x = print "We sail the ocean blue"; // returning a value 116 In this course, we will not use actual servers, for obvious security reasons. 117 Yet, unlike JavaScript or other programming languages, which quotation mark is used can make a huge difference. More on that later.

94 Under the hood The action of sending strings to the browser through a PHP script can, of course, be accomplished by building a regular HTML document, with all the tags in place (provided the filename extension is still PHP). But here we discover the trick of the pre-processor. When we visualize the source code from the browser window, we see that what PHP actually does is to prepare the HTML code line by line, adding the result of its echo statements to the normal flow of the page. PHP CODE <html> <head> </head> <body> <?php echo 'hi there';?> </body> </html> WHAT S IN THE PAGE <html> <head> </head> <body> hi there </body> </html> We could go to the extreme of echoing the whole page, even using PHP variables to store the content of the message, and nothing would change. By the way, remember that variable names have a dollar sign prefix: PHP CODE <?php echo '<html>'; echo '<head>'; echo '</head>'; echo '<body>'; $a = 'hi there'; echo $a; echo '</body>'; echo '</html>';?> WHAT S IN THE PAGE <html> <head> </head> <body> hi there </body> </html> (just the same as in the previous case) What happens, basically, is that PHP scripts, be they stray statements or function calls, must leave their trace as HTML code written on the page. Simply put, this language is a producer of HTML code, much in the same way as JavaScript does with its document.write statement. If this question were asked in the JavaScript course, there would be no definitive answer, only some suggestions. In PHP, there are no doubts, because script output (echo) builds HTML code (after all, PHP is a pre-processor), so that whatever is sent as output through the echo command becomes part of the Web page. This means that, while PHP functions can (and should) be stored in libraries, at least some scripts will end up in the heat of the battle, where the corresponding HTML code is to be placed. The implications of this behavior are quite straightforward: echo output should adhere to the HTML syntax; there will invariably be stray PHP statements somewhere, or PHP functions would never have a chance to be put into action 118 ; the place for PHP code is wherever needed in the normal flow of the page. PHP is neither event-driven nor interactive in itself. It is the resulting DHTML code that allows for that. NOTE As we will see, the very way PHP builds Web pages is the reason for its wicked data processing mechanism. But more on this later. FINAL ADVICE The golden rule is still: keep as much PHP as possible away from HTML. 118 Functions quietly sit, waiting to be called. But while JavaScript functions can answer to events happening on the page, PHP functions can only be activated through other PHP statements. PHP is not dynamic.

95 When PHP met JavaScript, and the secret of the quotes PHP was not designed for interactivity: after all, its purpose is to pre-process and build HTML documents. In those cases where results just need to be shown (mainly for debugging purposes), old hand JavaScript can help. For literal messages, or those involving only HTML elements, there is not even need for PHP, as JavaScript could suffice. So, in the following snippet, the two PHP statements below are just another version of the first DHTML line, and bear little significance, except for showing the difference between quotation marks: <script>alert("hi there");</script>; <!-- in HTML code --> <?php echo "<script>alert('hi there');</script>"; // needs time for expansion echo '<script>alert("hi there");</script>'; // faster?> The literal delimited with single quotes translates faster than the other. The reason is that double quotes are a little more demanding, as they allow a mechanism called macro expansion 119, which, to put it simply, is to store part of the echo string into a variable. This is shown in the following snippet, as opposed to a more traditional sequence of strings. We will also introduce the most peculiar symbol for string concatenation, which, quite surprisingly, is not a plus sign, but a dot (.) operator: $x = 87; echo "the value is: $x<br>"; echo 'the value is: '. $i. '<br>'; So, fixed strings are best processed with single quotes, and macro expansion can be used whenever they make a variable expression simpler. For example, echoing a HTML list could be done in several ways, some of which really horrible. Of course, even the good method is not really so, as it should involve an array of choices, to be visited with a basic loop. But here we only need to get to the idea; more on arrays later. /* */ /* */ Not too bad echo '<ul>'; echo "<li>$var1</li>"; echo "<li>$var2</li>"; echo "<li>$var3</li>"; echo '</ul>'; From bad to worse choices (violating the KISS principle). echo "<ul><li>$var1</li><li>$var2</li><li>$var3</li></ul>"; $x = '<ul>'."<li>$var1</li>"."<li>$var2</li>"."<li>$var3</li>".'</ul>'; echo $x; PHP has some flexibility, when it comes to automatic casting. We can mix strings with boolean or numeric values, but the dot operator must be separated with spaces, lest it be confused with a decimal point: $a = '2'. true; // string (also: '2'.true; '2'. true;) $a = '2'. 4; // string (also: '2'. 4; wrong: '2'.4) $a = 2. 4; // string (wrong: 2. 4; 2.4) The assignments written in red will not be accepted, singling out the number as the offending item. The resulting page will contain a message similar to the following: Parse error: syntax error, unexpected '4' (T_DNUMBER)... String concatenation with the. operator Should require an array (or: '.4') The rest of the message indicates the name of the page where the error was detected. A more complete list of error messages will be found in the next section. 119 Sometimes called macro substitution.

96 Errors, errors everywhere Locating fatal errors in PHP is not as problematic as in JavaScript: after all, the page is processed in advance, so the parser has all the time to check the PHP code. Of course, the same does not apply to the rest of the HTML/JavaScript code, which is left to the browser, with all the inconveniences of the case: such errors as wrong tags or incorrect JavaScript statements must be located and trapped, either using a wolf-fence algorithm or by careful examination of the related code. Let us consider the following snippet, where a loop verifies which numbers between 1 and 10 are prime, by calling a function already analyzed, with the obvious name of prime. The results are on the right. for ($i=1; $i<=10; $i++) echo $i. ' ('. prime($i). ')<br>'; function prime($n) $i=2; while( $i<=$n/2 && $n%$i!=0 ) $i++; if ($i>$n/2 && $n>1) return 1; else return 0; This example works just fine, but we should not ask too much to the macro substitution, which only expands the variables present in the doubly-quoted string. Function calls, if present, would be impossible to decipher. The following line, though not causing a fatal error, would not produce the desired outcome: echo "$i (prime($i))<br>"; // results in a sequence of lines like: 2 (prime(2)) So, in these cases, we should stick to the concatenation operator, as shown in the first snippet. The following examples are a collection of errors and warnings 120. As short as the snippet is, it is possible to mistype in so many of ways that it will be hard to remember all the possible error messages: most of them, anyway, are clear enough that it is not difficult to locate the cause of the error. For each example, there is a brief description of the error, the corresponding line (or lines), and the error message, where xxx stands for the name of the PHP document and yyy for the line where the error is detected. As is C/C++, sometimes the detection of the error happens in a following line, especially with missing punctuation: in those cases, error trapping needs a little backtracking. This is not meant to be a complete list; still, it should cover the most common errors. Missing $ in variable name (in a condition) for ($i=1; i<=10; $i++) Notice: Use of undefined constant i - assumed ' i ' in xxx on line yyy Missing $ variable name (in a function call) echo... prime(i); Notice: Use of undefined constant i - assumed 'i' in xxx on line yyy Missing $ in variable name: "i" instead of "$i" for (i=1; $i<=10; $i++) Parse error: syntax error, unexpected '=', expecting ';' in xxx on line yyy loop parenthesis not closed for ($i=1; $i<=10; $i++??? Parse error: syntax error, unexpected '', expecting ')' in xxx on line yyy (the first statement after the error) Nothing between the loop and the function for ($i=1; i<=10; $i++) function prime($n) Parse error: syntax error, unexpected T_STRING, expecting '(' in xxx on line yyy (the first statement after the error) 120 Warnings do not cause the parser to abort the page, but they can result in misprints. 1 (0) 2 (1) 3 (1) 4 (0) 5 (1) 6 (0) 7 (1) 8 (0) 9 (0) 10 (0)

97 Loop brace not opened (only closed) for ($i=1; i<=10; $i++) echo... Parse error: syntax error, unexpected '' in xxx on line yyy As in other languages, it is not mandatory to use a compound statement : so the parser signals the line of the unmatched closing brace as the source of the error. wrong keyword (no parentheses) Parse error: syntax error, unexpected T_VARIABLE in xxx on line yyy cho... // instead of echo wrong operator $i+) // instead of $i++ $i+++; // stand-alone Parse error: syntax error, unexpected ')' in xxx on line yyy In the second example will be ';', Could also be '', or a variable, depending on the following line. Call to wrong or UNKNOWN FUNCTION retun(...) // instead of return (in the function) Fatal error: Call to undefined function retun() in xxx on line yyy MISSING ARGUMENT IN FUNCTION CALL... prime()... Warning: Missing argument 1 for prime(), called in xxx on line yyy and defined in xxx on line yyy (R) Note: there no problem with extra arguments. unclosed ) in function call echo... prime($i???... Parse error: syntax error, unexpected ';' in xxx on line yyy MISSING SEMICOLON AT THE END OF A STATEMENT echo... [no ; here] Parse error: syntax error, unexpected '', expecting ',' or ';' in xxx on line yyy Parse error: syntax error, unexpected T_ECHO, expecting ',' or ';' in xxx on line yyy Usually, line yyy is the first statement after the error (excluding comments). So the message may vary: it depends on what the statement is. In the first case, a closing brace was encountered; in the second, an echo statement. Missing concatenation sign echo $i ')<br>'; Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in xxx on line yyy Missing opening quote echo $i. )<br>'; Parse error: syntax error, unexpected ')' in xxx on line yyy This is not difficult, as the first offending sign is promptly identified. Missing closing quote echo $i. ')<br>;??? Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in xxx on line yyy This error is tricky because the string constant is considered terminated at the first quotation sign encountered, which could easily be in a correct statement, as in echo 'hello'; In that case, it is the closing quotation sign of the CORRECT statement to be considered incorrect. But then again, a good text editor would show the errors with syntax coloring. Last, but by no means least, is the worst parse error to backtrack: Loop brace not closed for ($i=1; i<=10; $i++) echo... function prime($n) Parse error: syntax error, unexpected $end in xxx on line yyy This error is particularly tricky because it is usually refers to the last line of the document, and there are no clues as to where the closed brace was forgotten.

98 Further considerations The repeated error As a curiosity, we might note how non-fatal errors and warnings become part of the HTML code of the actual page, and so they get mixed with those parts which PHP processes successfully; furthermore, their HTML syntax take into account those part of the messages to be rendered in boldface. In the case of a variable name without the dollar sign prefix, the error is reported for each step of the loop: <b>notice</b>:use of undefined constant i-assumed 'i' in <b> </b> on line <b> </b><br> 1 () <b>notice</b>:use of undefined constant i-assumed 'i' in <b> </b> on line <b> </b><br> 2 () <b>notice</b>:use of undefined constant i-assumed 'i' in <b> </b> on line <b> </b><br> 3 ()... Common errors in JavaScript activation Another simple snippet activates JavaScript, but there are a couple more common errors to observe: echo "<script>alert('hi there');</script>"; No parentheses in echoing a script echo <script>alert("hi");</script> Parse error: syntax error, unexpected '<' in xxx on line yyy Same quotation marks inside a string echo "<script>alert("hi");</script>"; Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in xxx on line yyy Negotiating through missing items The only really cryptic error messages at least give a hint on what is missing: Parse error: syntax error, unexpected T_..., expecting ',' or ';' in xxx on line yyy We have seen several examples of what could be in place of the unexpected : T_VARIABLE T_ECHO T_STRING T_CONSTANT_ENCAPSED_STRING T_DNUMBER But it is probably useless to learn them all: with a bit of practice, and considering what was expected 121, the missing item is normally easy to spot. Missing keywords The behavior of PHP is not uniform in the case of a missing keyword, due to the structure of the statement involved. In some cases the parser detects an error, but, after syntax has been cleared, the resulting HTML code depends on assumptions. For example: missing function keyword in the function header: intercepted as a syntax error by the parser missing for or while: intercepted as a syntax error by the parser missing return keyword in the function: forces a return null missing echo keyword in a normal display: no HTML action Uno alla volta, per carità PHP only reports the first error it encounters; however, this is hardly an inconvenience, as it does not leave too much space for distractions. After all, there will be only one (we can correct only one error at a time). 121 Actually, it would be more precise to say what could be expected, since the parser, which after all is only a syntax checker, is making assumptions on what could follow.

99 Give us the tools, and we will finish the job 122 PHP has some debugging tools (not many, to tell the truth, unless one resorts to some specialized environment). In this section there is a brief summary of some useful features of the language. Echoing variables By far, the most used debugging technique involves displaying the content of variables. There are at least three such functions, with slightly different behaviors: $a = 185; $b = 'xyz'; var_dump($a); // int(185) var_dump($b); // string(3) "xyz" var_dump($a,$b); // int(185) string(3) "xyz" var_export($a); // 185 var_export($b); // 'xyz' print_r($a); // 185 print_r($b); // xyz The most useful of the three is probably var_dump(), which shows the variable type in front of the value, and has the added advantage of supporting multiple arguments. The only advantage of the other functions is that the output string can be returned for subsequent processing instead of being echoed, as in: $z = var_export($a); Actually, the same thing could be obtained with var_dump, but in a horrible way (not suggested): ob_start(); // Activate something called "object buffering" var_dump($array); $out = ob_get_clean(); // Deactivate and assign to a variable Magic constants When errors occur, it may be useful to know where, to help implement a wolf-fence algorithm. This can be done by checking some of the magic constants of PHP, thus called because they change depending on circumstances 123. Their names are self-explanatory, and they can be used to display information about logistics: echo LINE. '<br>'; // Current line number echo FILE. '<br>'; // File name echo DIR. '<br>'; // Folder name echo FUNCTION. '<br>'; // Function name Other magic constants ( CLASS, TRAIT, METHOD, NAMESPACE ) belong to the realm of OOP, and are not used in this course. Variable variables If PHP constants can change, another curious feature of the language is the possibility of storing a variable name into another variable, then access the value of the former with the latter. It can be useful when working with data structures (lists or arrays), or to enhance data flexibility. Actually, this is a very specialized tool, used in very complex situations. The following example shows how to deal with these elusive entities: $a = 'v'; $v = 'Content of v'; echo $$a; // displays Content of v $v = 18; echo $$a*2; // displays Winston Churchill (February 9, 1941). 123 Which does make them a little more like variables.

100 Strings As in JavaScript, PHP strings are a staple of the language, possibly even more so. The processing of input elements and database values, in fact, calls for a great deal of string operations. A string constant (also called a literal ) has the usual aspect as in most programming languages: "Here's your crowbar and your centrebit" In the first examples, we will see string variables getting their value from literals (more on input elements and data processing later), so the basic assignment is like this: $a = "We sail the ocean blue"; Most of the key concepts are the same as in JavaScript, so we may refer to the corresponding section. For example, as in all C-derived languages, PHP strings are zero-based: i.e., the first character of a string is in position ZERO. Strings are also analogous to arrays of characters. There are differences, however: PHP strings are not immutable, i.e. they can be directly modified (as in $a[4]="e"); of course, they can also be replaced by a new expression, possibly involving the previous value (as in $a=$a."x";). The length of a string is not evaluated with a method, but with a function, mutuated from C++: for example, strlen("abcde") returns 5. As seen in previous examples, most strikingly different is the concatenation operator, which is a dot (.) symbol: so, we will write "blue ". "dress", not +. $a=$a."x"; is equivalent to $a.="x";. PHP has the classic string delimiters, single and double quotes (' and "): for example, we may see echo("take the 'A' train"); or echo('take the "A" train');. The key difference, as we have seen, is the macro expansion mechanism in echo statements. When possible, use single quotes. Deletion, insertion, replacement, and search are still the other common operations. Arithmetic on the G string? PHP numeric strings can be used in the same quirky calculations possible in JavaScript, with the added bonus that addition works arithmetically ("+" being different from the dot concatenation operator): echo("4"+"2"); // result: 6 echo("4"+3); // result: 7 echo("4"*"2"); // result: 8 (the strings are cast to a numeric type) As already commented, this is just a curiosity, not to be followed in the real world. How to apply the JavaScript show method What could pass for interaction is the application of the JavaScript show method for string rendering. But it s just an illusion, since, as we know, any element of the page must be known to PHP in advance. The following example is somehow limited because it refers to a direct assignation, but even in the case of an external source for variable values, the data must be supplied before the HTML code is built. So it is not that different from what we will meet in the data processing section. Note that quotation signs effectively turn the variable into a literal; in the second script, without quotations, assumptions are made, and PHP could print anything. The pre-processed HTML code is also included, to show the difference. <?php $x = "sinn fein"; echo "<script>'$x'.show(out1);</script>";?> Actual HTML: <script>'sinn fein'.show(out1)</script> <?php echo "<script>$x.show(out1);</script>"; sinn fein.show(out1);</script>?> Actual HTML: <script>sinn fein.show(out1)</script> In most cases, nothing gets printed, but the actual outcome is just unpredictable.

101 intval, floatval These functions are the counterpart to parseint and parsefloat of JavaScript, and are used to transform string data into numbers. The context of their use is different, however: while in JavaScript they usually translate input data, in PHP data are read from text or database files, where it may happen, very often indeed, to find numeric data stored as strings. PHP numbers come in two varieties, integer and double (doubleprecision), but that depends on the values rather than on a type declaration. In fact, the type can change, and can be detected with the aptly named gettype function: $n = ; // gettype($n) returns "double" $n = 45; // gettype($n) returns "integer" The two functions examine the parameter string in similar ways, accepting all the numeric characters until the string ends or a non-numeric character is met (whichever comes first). Numeric characters include the "+" and "-" signs (provided there is only one of them, and at the beginning of the string), and the decimal point (only for the floatval function, and only the first one: a second point stops the parsing, just like any non-numeric character). Clearly, the processing of the decimal point is what sets apart the two functions. Here are some examples of the two functions in action. An asterisk indicates where the parsing operation has been interrupted by a non-numeric character. Unlike JavaScript, null and empty strings force the result to 0. Numeric output intval("12") 12 floatval("12") 12 intval("87y") * 87 floatval("87y") 87 * intval("730y3") * 730 floatval("730y3") 730 * intval("-12.5") * -12 floatval("-12.5") intval("6 4") 6 floatval("6 4") 6 intval("6-4") 6 floatval("7.8.9") 7.8 * intval("") 0 floatval("") 0 intval(" ") 0 floatval(" ") 0 Numeric formatting, with respect to JavaScript, has a somewhat backward feeling, derived from the C-style functions used. Among the several options, the simplest to use is probably sprintf (the name means, more or less, string-print-formatted) There are differences from C, however, due to the uniform nature of PHP numbers: the function, in fact, is rather unfazed by the presence of decimal digits, or lack thereof; so, instead of wasting time with the %d or %f formats, it is perhaps wiser to stick to the old hand, the %g format. In the following snippet, all formatting options yield the same result: $n = ; $z = sprintf($n,"%g"); // $z = sprintf($n,"%6.2f"); // (waste of time) $z = sprintf($n,"%d"); // For documents or forms, there is another function, which uses the thousands separator and a fixed number of decimal places (which can be used with most currencies, such as dollars, pounds, and euros): $x = number_format($n,2); // 6, The default locale (which is, rather understandably, English) can changed by specifying the new decimal and thousands separators as additional parameters, sometimes with outrageous results:: $x = number_format($n,2,',','.'); // 6.542,35 (Italian) $x = number_format( ,2,'comma','dot'); // 6dot542comma35 (???) Base conversion PHP offers a flexible base conversion function, aptly named base_convert, which can work with numbers or numeric strings, and returns a string. Both bases (source and target) are required; errors yield '0': $c = base_convert('35',8,10); // 35 in base 8 becomes 29 in base 10 $d = base_convert(35,10,36); // 35 in base 10 becomes 'z' in base 26 $e = base_convert(9,8,36); // result: '0' (error: 9 is not in base 8)

102 Operations on strings PHP has scores of string functions, some of which quite mysterious. The most common are the following (shown on a fictitious string $s or $h): strtoupper($s) return the content of "$s", with all letters in UPPERCASE strtolower($s) just the same, only in lowercase substr($s,$i,$j) extracts a substring of "$s" starting at position $i, with length $j strpos($h,$n,[$i]) returns the position of substring "$n" in "$h", ($i=start position) strrpos(...) searches from the end of the string towards the beginning There is no counterpart to the JavaScript charat method: characters (which are strings in their own merit) are extracted with the usual $s[$i] array format. At the bottom of the page, a brief summary is included. Before examining that, since the behavior of these functions is sometimes different from their counterparts in other languages, we should consider the following peculiarities of PHP string handling: strtoupper, strtolower These functions do not modify the string: they return a string with the same general content of the source string, processed accordingly. If we need to modify the original string, it is necessary to store the modified string back to the variable, with the usual assignation operator: substr $s = strtoupper($s); $x = substr($s,$i,$l); Incongruent parameters may cause the function to return false, null, or an empty string If the substring length is omitted, all remaining character will be extracted If $l is negative, that many characters will be omitted from the end of the string strpos, strrpos "$n" and "$h" are mnemonics for needle and haystack: respectively, what to search and in which string. If the second argument is missing (the default), the search starts from the beginning of the string; When present, the second argument specifies from which position to start the search; Unsuccessful searches return false. substr_count substr_count($h,$n[,$i]) counts all occurrences of "$n" in "$h" ($i=start position) This is a rather unique function, as no other commonly used language offers its equivalent 124. Sample values Function calls Results $s "We sail the ocean blue" strtoupper($s) "WE SAIL THE OCEAN BLUE" strtolower($s) "we sail the ocean blue" substr($s,$i,$m) "the" $i 8 strpos($s,$t) 12 $j 20 strpos($s,$t,$j) false $m 3 strpos($s,$v) 1 $t "ocean" strpos($s,$v,$j) 21 $u "sea" $v "e" strrpos($s,$v) 21 strrpos($s,$v,$j) 14 substr_count($s,'e') With the exception of the now defunct Visual FoxPro, which has never been considered a mainstream language.

103 Solved problems Alternating uppercase and lowercase letters This example shows how to build a new string, one character at a time: function alternating(s) // input: donkey; output: DoNkEy $t = ''; for( i=0; i<strlen(s); i++) if ( $i%2 == 0) $t.= strtolower($s[i]); else $t.= strtoupper($s[i]); return $t; Reversing a string As we have seen in JavaScript, this problem can be solved with a reverse loop, quite similar to a sum of numbers. function reverse($s) // input: watch; output: hctaw $t = ''; for( $i=strlen($s)-1; $i>=0; $i--) $t.= $s[i]; return $t; function sum($n) $t = 0; for($i=$n;$i>=$1;$i--) $t+=$i; return $t; But there s more: PHP offers a built-in function for string reversal: $x = strrev('rabbit'); // returns tibbar Building a proper name Proper names are obtained with two functions: ucfirst capitalizes the first character of the entire string (lcfirst curiously transforms it into lowercase), ucwords on all the words in a sentence. $x = ucfirst('this is a sentence'); // This is a sentence (lcfirst) $x = ucwords('this is a sentence'); // This Is A Sentence HTML spaces The mnemonic for a HTML (non-branching) space is " ", not too simple to insert into an echo call. With the useful str_repeat function, it is possible to multiply any string a given number of times; the example shows how the task of echoing true spaces on the page is greatly simplified: function blank($n=1) return str_repeat(' ',$n); String padding // Waste of time: ' '; // good: echo blank(5); A padding is a protective layer put around objects. In data processing, the analogy describes the addition of a number of characters to a string, to make it reach a specified length (usually to fill a predetermined space on a form). Normally, the padding character is a blank space, as in: while( strlen($s) < $target ) $s.= ' '; The function str_pad does just that, with the possibility of specifying the padding string and where to add the characters (to the left, to the right, centering the original string).this format: str_pad( $input, $length, $padstring, $mode); $mode can be set to STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH., so the preceding snipped could be replaced with the following: str_pad( $input, $target, ' ', STR_PAD_RIGHT);

104 Following string changes PHP strings are processed by reassigning a value in the calling program, possibly combining multiple calls in the same statement. We can track the sequence of value changes in the following snippet: $s = "abcdef"; // original value $s = ucfirst($s); // now "Abcdef" $s = strrev($s); // now "fedcba" $s = strrev(ucfirst($s)); // proper before reverse (capital F); now "abcdef" Note that the calling order matters, as ucfirst(strrev(s)) would yield "Abcdef", with a capital "A". Character or substring substitution/deletion in PHP Since PHP strings are not immutable, the substitution of a single character can be made in array fashion: $s[$i] = strtolower($s[$i]); Substitutions could also be done by dividing the string into 3 parts, just like in JavaScript: $s = substr($s,0,$i). strtolower($s[$i]). substr($s,$i+1); PHP, however, among its many string functions, offers one for string replacement: $s = substr_replace($s, strtolower($s[$i]), $i, 1); Similar considerations apply when deleting parts of a string (only without a new substring in the middle). For example, one single character can be deleted with this call: $s = substr_replace($s, '', $i, 1); String normalization This operation is sometimes called purging, as it erases redundant blank spaces, three kinds of which exist: leading (" xyz"), trailing ("xyz "), and multiple ("x y z"). Reworking the JavaScript solution, we will first delete leading and trailing spaces, with the PHP function aptly named trim(), then looping through a search for double spaces. The following function returns the purged copy of its parameter s. The call to function space makes the script more readable: the expression space(2) identifies the object of the search, whereas the corresponding string literal " " could be easily misread. The function is also reusable in any other application. function purge($s) $s = trim($s); $c = space(2); while( ($i=strpos($s,$c)) ) $s = substr($s,0,$i). substr($s,$i+1); return $s; function space($n=1) return str_repeat(' ',$n); The same result could be obtained with the substitution function. We can also introduce another mnemonic, called $b, standing for a single blank spaces: $c = space(2); $b = space(); // The default value of parameter is ONE while( $p = strpos($s,$c)) $s = substr_replace($s,$b,$p,2); Finally, a totally devilish method which uses repeating functions (functions that examine all the possible substrings). substr_count counts the total number of occurrences of a substring, str_replace replaces all such occurrences. This is rather working with an axe where a scalpel is needed: while( substr_count($s,$c)) $s = str_replace($c,$b,$s); // search replace subject Note that these last two methods are rather crude, and in some cases they fail miserably. Just to be on the safe side, it is recommended to stick to progressive searches.

105 Searching for words Words are those parts of a string which are enclosed between consecutive two blank characters. That s where a normalized string is needed: unwanted spaces may generate empty words, possibly fouling the processing (and the reconstruction) of the whole phrase. Let s consider the string "We sail the ocean blue". Suppose that, with the strpos() function, we have managed to set "$i" to 2 and "$j" to 7: substr($s,$i+1,$j-$i-1) extracts the word "sail", which can be processed as desired 125. The same applies for any such pair of indexes, as shown here: A single loop will suffice for the indexes to proceed along the string, provided that the search for each new blank started from the last position reached. Having "i" chase "j" is not a great deal; the situation, however, is not quite as clear at the boundaries of the phrase (that is, the first word and the last). The first word can easily be identified by setting the initial value of "i" to -1. The real problem is at the end, when "i" is 17 and "j" becomes false, which is the result of the unsuccessful search for another blank. One simple solution is to attach a blank space at the end of the string, thus ending up with the correct value of 22 for the forward index "j". It may sound silly to go through the trouble of normalizing the string, then adding a redundant space of the same sort as the ones we have struggled to delete. The point is that the trailing space is not of the same sort after all, being a totally different beast: besides being placed there for the purpose of coping with a search result which disrupts the algorithm, the extra space is temporary 126, being added only for the duration of the function, quietly disappearing at the end of the process. The skeleton for this procedure is the following: function words($s) $c = space(); $s.= $c; $i = -1; $j = strpos($s,$c); while ( $j ) $word = substr($s,$i+1,$j-$i-1); BEWARE!!! The function does not specify what to do with each word. This is left as an exercise.... // Processing the single word $i = $j; // "i" reaches the "j th " position $j = strpos($s,$c,$j+1); // Search for the next blank As in JavaScript, these is the much simpler solution which uses a slack array. The PHP functions for stringto-array and array-to-string transfers, named explode() and implode(), respectively, differ from their JavaScript counterparts in that explode() requires a mandatory separator character, as in: $a = explode(' ',$s); // Store the words into array "a"... // Process the array $s = implode(' ',$a); // Reconstruct the sentence from array "a" But first we need to know a bit about arrays. This will be the topic of the next chapter. 125 The formula $j-$i-1 is used because the second parameter of the substr function is the length of the substring. 126 Normally, the space is called a slack data, in that it is used, then discarded without further effects.

106 Arrays Arrays should be known from previous courses. PHP arrays are no exception to the general rule, being collections of data, identified by their position (also called index). An example of array could be a list of the temperatures of one week: 25,30,28,34,32,35,36. As we saw with strings, PHP arrays are somewhat more primitive objects than in JavaScript, and their management reminds much the C++ language. Yet, array handling is quite advanced, thanks to many useful functions. Arrays can be declared in a couple of ways: $a = array(); // Empty $a = array(87); // NO JavaScript: one element, number 87 $b = array(1,2,3,4); // Direct value assignation $c = [1,5,3,2]; // Not safe (only PHP 5) Some considerations apply: The first element of a PHP array is in position zero (like C/C++ arrays); Unlike C/C++ arrays, PHP arrays are elastic (i.e.: their length can vary, adding or deleting elements); Tthe length of an array is a calculated with a function, called count($a); The last element of array $a is in the position count($a)-1 (length minus one, due to the presence of the element in position zero). There can be no unassigned array elements; they can be deleted, though, along with the index (this means that an array could be left, for example, with positions 0 and 2, but no position 1). PHP arrays are linear (or mono-dimensional); with some tricks, it is possible to mimic matrices (multidimensional arrays, with any number of dimensions), including the familiar syntax a[i][j]; matrices, however, are outside the scope of this course, as their use in Web applications is limited. Some of the most common functions for assigning and extracting values are listed below: array_push($a,...); // Append at the end of the array (sequence) array_unshift($a,...); // Insert at the beginning (sequence) array_pop($a) // Remove last element array_shift($a) // Remove first element array_splice($a,$p,$n); // Remove $n elements starting at position $p array_splice($a,$p,$n,$b); // Remove, then insert (element or array) array_reverse($a) // Flips the array sort($a)/rsort($a) // Sort elements in ascending/reverse order array_slice($a,$p,$n); // Copy $n elements starting at position $p The pop and shift methods are limited to just one element. The same holds for the simplest way of adding an element to an array, which uses an empty couple of brackets, as in: $a[]=18;. The following sequence shows the methods in action. At each step, the new elements are written in green; the elements written in red are those which the following method would remove from the array: array_push($a,21); 21 array_push($a,31,32,33); 21,31,32,33 array_unshift($a,41); 41,21,31,32,33 array_unshift($a,51,52,53); 51,52,53,41,21,31,32,33 array_pop($a); 51,52,53,41,21,31,32 array_shift($a); 52,53,41,21,31,32 array_splice($a,3,4); 52,53,41 array_splice($a,1,1,array(61,62,63)); 52,61,62,63,41 array_splice($a,0,1,37); 37,61,62,63,41 array_reverse($a); 41,63,62,61,37 sort($a); 37,41,61,62,63 $new = array_slice($a,1,3) 41,61,62 (new array)

107 No show Just for curiosity, javascript:show sort of works with arrays, but not quite: the result is just a string containing the word Array. The flexibility of JavaScript does not hold in PHP, which, once again, is not dynamic, but must process the whole page before submitting it. The image below shows the effect: <?php $x = array(); echo "<script>'$x'.show(out1);</script>";?> The actual HTML also contains a warning that there is something fishy: Notice: Array to string conversion in xxx on line yyy <script>'array'.show(out1)</script> Stretching arrays As seen before, arrays can be stretched with a generic assignment to the array, containing a pair of empty square brackets; actually, they could even be generated in the same way. It should be noticed, however, that in such cases the first element should be assigned directly, as with array $a in the example; and while array $b and $c have the burden of an extra element, array $d is built in a more proper way: $a[] = 1; $a[] = 'a'; $a[] = false; $a[] = array(); $a[] = 5.6; $b[] = null; // Not suggested (generates one null element) $b[] = 15; // this element would be the SECOND one $c[] = array(); // BAD: one element: an empty array $d = array(); // Empty array $d[] = 21; // extension Deleting variables The unset function can be used to erase any variable from the symbol table, and is sometimes used on array elements. Care must be taken, however, because this can disrupt the numeric indexing, as in the following example, which generates an error when trying to access $a[2] after its deletion: 127 unset($a[2]); for($i=0;$i<count($a);$i++) var_dump($a[$i]); Notice: Undefined offset: 2 in xxx on line yyy Look ma, no indexes The previous error can be avoided with an useful array visiting tool, the foreach statement 128. Disposing with the use of an index, foreach is simpler and safer than the usual traversing loop. The two loops of the following example have the same effect: for($i=0;$i<count($a);$i++) var_dump($a[$i]); foreach($a as $v) var_dump($v); It is also possible to call the elements by reference, in order to modify them: foreach($a as &$v) $v*=2; Of course, this statement can be useful when the same operation must be performed on all elements, regardless of position. 127 Erasing variables (with the unset function) could be useful in complex applications. More widely used is the test on the existence of a variable, as in: if (isset($v)) foreach is present in other languages, including Java and Visual Basic. In JavaScript, it is limited to objects.

108 Associative arrays Arrays can be used without numeric positions, using only string indexes (this is the meaning of associative). This example was given by Jeffrey Way in one of his precious lessons, where he shows a list of links to some of his courses: $a = array ( "nettuts" => " "psdtuts" => " "wptuts" => " // this last comma is optional ); // don t forget the semicolon echo '<ul>'; foreach( $a as $name=>$url) // LIST OF COURSES AND URLs echo "<li><a href='$url'>$name</a></li>"; echo '</ul>'; The $name=>$site association in the foreach statement corresponds to the => couples in the array declaration, so that: "nettuts" replaces $name " replaces $url The <li> elements can also be assigned with a forced double quote (which requires a backslash prefix): echo "<li><a href=\"$site\">$name</a></li>"; // This is also correct echo "<li><a href="$site">$name</a></li>"; // WRONG: same quotation sign An alternate syntax is given by the endforeach keyword, which can replace the closing brace while disposing of the opening one. This is not suggested, as it deviates from the usual syntax: foreach( $a as $name=>$site) echo..."; endforeach Some consider this construct useful when breaking out of PHP, but the fact remains that, even if breaking were necessary, more PHP would be included in the loop, and confusion might ensue. Anything that mixes PHP and HTML is deprecated, and, fortunately, seldom used 129 : <?php foreach( $a as $name=>$site)?> // PHP <!-- HTML stuff --> // HTML <?php endforeach?> // PHP The following examples (one bad, one worse) show the mess that can be generated by mixing too much: <ul> // BAD <?php foreach($tuts_sizes as $name => $url) echo "<li><a href='$url'>$name</a></li>";?> </ul> <ul> // FROM BAD TO WORSE <?php foreach($tuts_sizes as $name => $url)?> <li> <a href="<?php echo $url;?> "> <?php echo $name;?>" </a> </li> <?php endforeach?> </ul> 129 PHP developers seem more willing to adhere to good programming practices than their JavaScript counterparts.

109 Solved problems PHP built-in functions cover most of the routine array operations, such as sorting, flipping, and extracting. This frees the programmer from the burden of writing and testing the corresponding scripts. The following examples, though of little intrinsic value, will be used to introduce some useful features of the language. Problem 1: Flip part of an array Given an array, find two random positions $p and $q, ensuring that $p<$q, then flip the part of the array which lies between the two positions. In the examples, the values of $p and $q are 3 and 6, respectively: $a = [0,1,2,3,4,5,6,7,8,9]; $p=3; $q=6; // possible result: 0,1,2,6,5,4,3,7,8,9 We will tackle the numeric part first, showing how to deal with random numbers. The PHP tool is the rand function, one of a series of mathematical functions 130. Unlike its JavaScript counterpart, the PHP random 131 generator returns, by default, an integer value between 0 (included) and the result of the JavaScript function getrandmax() 132 (excluded). It is quite simple, though, to specify an interval for the result: $x = rand( min, max); This way, we do not need any special calculations to find positions which belong to the array. The swap solution shown, a nice PHP alternative, is not the fastest around, so it would not be suggested for a situation with many exchanges: in any instance when time is a factor, the usual swap function is still preferred. $p = rand(0,count($a)-1); // The PHP list statement is a construct $q = rand(0,count($a)-1); // which assigns the values of an array if ($p>$q) list($p,$q) = array($q,$p); // to a list of variables There rest of the solution, with a flip loop, is elementary: while ($p<$q) swap($a[$p],$a[$q]); $p++; $q--; With the list construct, the swapping would be: list($a[$p],$a[$q]) = array($a[$q],$a[$p]); A much shorter method uses the array_splice function, which, contrary to JavaScript, allows for the insertion of an entire array in a given position. This way, it is possible to extract and reverse a section of the array, then graft it back in the same place where it was pruned. For the sake of simplicity, a new variable can be used to specify the length of the section ($p and $q are still 3 and 6): $n = $q-$p+1; array_splice($a,$p,$n,array_reverse(array_slice($a,$p,$n))); Problem 2: Find the smallest (or largest) element, using a comparison function A couple of other functions, min() and max(), can sometimes be useful in comparisons. They return, respectively, the minimum and maximum value among a list of values, as in: max(41,63,4,5,116,87); // result: 116 The lists can be of any length: there does not appear to exist an explicit limit, but some experts estimate a resource limit at around 2 billion (2*10 9 ). Unlike other similar functions in other languages, using min and max on an array seems almost unfair, as, unlike in JavaScript, they only need the array name: $a = [53,41,55,63,47,48]; $min = min($a); // result: 41 $max = max($a); // result: 63 function swap(&$a,&$b) $c = $a; $a = $b; $b = $c; 130 Many of these (exponential, logarithmic, trigonometric) are hardly used. 131 Actually, a pseudo-random generator, since it follows an algorithm: for practical purposes this makes no difference. 132 Normally, this value is (2 15-1).

110 Looking for mr.goodbar Arrays are collections of data, and, as such, can be searched for particular values. The corresponding function is aptly named array_search: $result = array_search( $needle, $haystack); Where $needle is the value to be found and $haystack is the array to be searched. The function returns either the key corresponding to the value, or false (a boolean value) in case the search is unsuccessful. Of course, if the value is present more than once, only the first matching key is returned (in the following examples, a numeric array will contain three occurrences of the number 13, and an associative array two occurrence of the value "red"). With normal arrays, the numeric value of the index is returned: $a = [10,11,12,13,14,13,16,13,18,19]; $r = array_search( 16, $a); // return value: 6 (found) $s = array_search( 13, $a); // return value: 3 (found) $t = array_search( 87, $a); // return value: false (not found) With associative arrays, the value of the key is returned: $a = array ( "color1" => "red", "color2" => "green", "color3" => "blue", "color4" => "red", ); $r = array_search( "red", $a); // return value: "color1" (found) $s = array_search( 87, $a); // return value: false (not found) Repeated values require another function, called array_keys. This function always returns an array (which will be empty when no matches are found). Rather annoyingly, the parameters are in reverse order with respect to the other function, which may occasionally lead to syntax errors: $result = array_keys( $haystack, $needle); The following examples use the same arrays as the preceding ones. $a = [10,11,12,13,14,13,16,13,18,19]; $r = array_keys( $a, 13); // [0]=>int(3) [1]=>int(5) [2]=>int(7) $s = array_keys( $a, 87); // The associative arrays contains two occurrences of the value "red": $r = array_keys( $a, "red"); // [0]=>"color1" [1]=> color4" $s = array_keys( $a, 87); // There is a logic behind the array being the first parameter of array_keys: the search value could be omitted, in which case the function would return all the keys contained in the array. Of course, normal arrays with a numeric index return a list of numbers from 0 to count($a)-1, so the inquiry is not very significant: $a = [1,2,3,4,5,6,7,8,9,10]; $r = array_keys( $a); // 0,1,2,3,4,5,6,7,8,9 Only when the numbering of the keys is very peculiar, or there is a mix of numeric and mnemonic keys, does the search for keys bear some meaning: $a = array( 0=>10, 2=> 12, "color" => "red"); $r = array_keys( $a); // 0,2,"color" Another possible use of this search could be to verify if some elements of the array have been deleted: but this is a very special case, not treated in this course.

111 Strings and arrays Just as in JavaScript, strings and arrays will meet in the processing of a whole sentence, without resorting to the search for blank spaces. The problem can be summarized as: 1 transfer the words of a sentence to an array 2 process the words separately 3 repack the array into a single string. The solution has been studied before, so it should surprise no one. The notable difference with JavaScript is that here the substring separator (the first argument) is mandatory in the function calls: $s = 'We sail the ocean blue'; $a = explode(' ',$s); foreach($a as &$x) $x = strrev($x); // Reverse EACH WORD $s = implode(' ',$a); $t = "go with the flow"; $b = explode(' ',$t); foreach ($b as &$x) $x = ucfirst($x); // Capitalize EACH WORD $t = implode(' ',$b); Of course, the second example could be solved with one call to ucwords($t). Omitting the separator in the call to explode is not a choice, as it would generate an error; an empty separator is also not allowed. The respective error messages are the following: Warning: explode() expects at least 2 parameters, 1 given in xxx on line yyy Warning: explode(): Empty delimiter in xxx on line yyy The blank separator in the subsequent call to implode, though not mandatory, is strongly suggested, or the spaces would not be restored (the result would be GoWithTheFlow). It is still possible to transfer one character per element in the target array, with the str_split function. This could turn out to be useful when some specific array functions are needed (array_reverse, to name one), or when a character might be replaced with a string of a different length (or even deleted). The following examples show nothing that could not be obtained with normal string operations, but they should give the idea. Actual problems would analyze the characters, and take the appropriate actions, with far more complicated processes. WARNING!!! the reconstructing implode function should be called without a separator, or at least with an empty one (which, contrary to explode, is allowed), to avoid inserting unwanted spaces between characters (as in "c u r s e", instead of "curse"). Normal array visit with character check Deleting some characters Substituting with longer expression $z = 'hammock'; $u = 'princess'; $v = 'curb'; $a = str_split($z); $a = str_split($u); $a = str_split($v); foreach($a as &$x) unset($a[6]); $a[3] = 'se'; if ( $x=='m' ) $x='d'; $u = implode($a); $v = implode('',$a); $z = implode($a); Before hammock Before princess Before curb After haddock After princes After curse

112 PHP in action: processing parameters Strings and arrays are the staples of PHP, but, until now, they have shown nothing that could not be done with JavaScript 133. Some of the real power of these tools can be appreciated with the processing of page parameters, which has been left pending both in the HTML and in the JavaScript courses. This is a possible complete URL of the called pages, along with the arguments: file:///d:/web/application/index.html?h1=oneword&h2=two+words There is a little tweaking to be done: it is necessary to substitute PHP pages for HTML ones, so the calling page should be rewritten in this way: <form action="php8.php" method=get> <input id=h1 name=h1 value="oneword"> <input id=h2 name=h2 value="two words"> <input type=submit value="send"> </form> In this example, the fields are in plain sight: this makes no difference in their handling by the called page. Of course, we will end up with this URL line: file:///d:/web/application/php8.php?h1=oneword&h2=two+words The page is called with the get method, just to show the parameters: normally, though, we should use the post method, for security reasons. Internally, there is actually no difference, as the called PHP page is always capable of recognizing the parameters, via a special array called superglobal 134, which stores all the data that the page has been sent. For now, we will only display the array like so: <?php var_dump($_request);?> Sure enough, the array contains the parameters. They are stored as strings 135, keyed by their names (assigned in the form element of the calling page), as the following var_dump result shows: array 'h1' => string 'oneword' (length=7) 'h2' => string 'two words' (length=9) This is an associative array A PHP page has three such superglobal arrays. Just to avoid any doubts, the $_REQUEST arrays is sure to contain the desired values: $h1 = $_GET['h1']; // Parameters passed with the get method $h2 = $_GET['h2']; $h1 = $_POST['h1']; // Parameters passed with the post method $h2 = $_POST['h2']; $h1 = $_REQUEST['h1']; // Either method $h2 = $_REQUEST['h2']; After that, it is still advisable to check for the parameters received, with call to isset: if( isset($request['h1'])... ; if( isset($request['h2'])... ; isset checks for existence Also, default values can be assigned: if(! isset($request['h1']) $_REQUEST['h1']='default value'; This is especially suggested when receiving input values from forms containing check boxes or radio buttons: when such elements are left empty, their names do not even appear in the $_REQUEST array. 133 This is going to change in the chapter dedicated to data processing 134 There are several superglobal arrays, for various purposes. More on this later. 135 This is true also for numeric values, hence the importance of the type transformation functions.

113 Case study: accessing the server As already mentioned, PHP has access to the file system on the server. In this study, we will see some operations on text files. Reading a text file is the simplest operation, and one that does not require access permits; creating, modifying, and deleting files, on the other hand, are subject to the security measures on the server 136. In a local environment, though, anything goes, so it will be possible to operate at will. We can use a simple text file, for example, one named text.txt, which contains a list of names. The file can be stored in the current folder (localhost, or '.'), with any text editor. Cochrane Foxx Bishop Boley Dykes Simmons Miller Haas Grove File access is allowed once the file is opened (fopen), until it is closed (fclose). When the file is opened, a reference to it can be assigned to a handle (which is a particular object, called a resource), through which all further operations will be executed. Function Example Meaning fopen $h = fopen('text.txt','r') Open for reading fclose fclose($h); Close fread $x = fread($h,$n); Read a given number of bytes fgets $x = fgets($h); Read to eof or line break feof while (!feof($h))... End-of-file rewind rewind($h); Reposition at file beginning filesize... filesize($h)... Total number of bytes fwrite $w = fwrite($h,...); Write to file (any value) A file can be opened in a number of ways (called modes), the most common being the classic three: 'r' (read) for input,'w' (write) or 'a' (append) for output. Some examples (of course, reading an existing file requires a 'r' opening mode): $handle = fopen( text.txt, r ); $x = fread($handle,11); fclose($handle); $handle = fopen('text.txt','r'); $x = fread($handle,filesize('text.txt')); fclose($file); $handle = fopen('text.txt','r'); $x = fgets($handle); while(!feof($handle)) echo $x. '<br>'; $x = fgets($handle); fclose($handle); $handle = fopen('text.txt','r'); while($x = fgets($handle)) echo $x. '<br>'; fclose($handle); echo( readfile('text.txt')); Reading a given number of bytes Reading ALL the bytes of the file Reading each line of text. The test is done through the feof function. Shorthand: the loop assigns the line to a variable and tests for end-of-file in the same token. This is probably the most convenient structure. Quick-and-dirty way for displaying text content (but without line feeds). 136 Some servers do not allow direct handling of the remote file system, unless a user has logged in through a portal. In such cases, PHP pages only have reading privileges.

114 Error trapping Whenever a program tries to access a file, the problem arises of whether the file actually exists: after all, you cannot extract data from a resource that cannot be located. Trying to open a file not present in the search folder, to use technical jargon, throws an error; and while the script does not abort, a flurry of error messages appears: $file = fopen('xxx.txt','r'); // This file does not exist $x = fread($file,11); fclose($file); This is what gets written on the screen: Warning: fopen(ext.txt): failed to open stream: No such file or directory in C:\web\textfile.php on line x Warning: fread() expects parameter 1 to be resource, boolean given in C:\web\textfile.php on line y Warning: fclose() expects parameter 1 to be resource, boolean given in C:\web\textfile.php on line z The fact is that the handle has a value of false, hence the clause boolean given in the message. Aborting the script can be a very simple choice with the aptly named die() clause, but a warning message appears anyway: $file = fopen('xxx.txt','r') or die(); Warning: fopen(ext.txt): failed to open stream: No such file or directory in C:\web\textfile.php on line x Aborting the program, though, is not a flexible solution. It is wiser to use some error prevention mechanism, such as checking for the presence of the file before using it: if (file_exists('xxx.txt'))... The situation can also be controlled by disabling the standard error handler (that is, the built-in function that processes errors and displays the corresponding messages). An empty error handler does not stop the script, but appropriate action should be taken, typically by checking the result of the fopen statement: set_error_handler('errortrap'); // set a custom error handler $file = fopen('ext.txt','r'); if($file!=null) // open successful?... // proceed processing fclose($file); restore_error_handler(); // restore default error handler function errortrap() // no action In file processing, there are not many error situations, so an empty handler is perfectly legit. In other situations, it may be useful to give more detailed explanations; that s why an error handler has several parameters that can help the programmer locate the error. $errno $errstr $errfile $errline numeric code error description name of the page where the error has occurred line number where the error has occurred The parameters are optional, and the program may contain a die() clause, although this is doubtful, or the error handler would not have been written in the first place: function errortrap( $errno, $errstr, $errfile, $errline) echo "<b>error:</b> [$errstr]<br>"; echo "<b>program:</b> [$errfile]<br>"; echo "<b>line:</b> [$errline]<br>"; die(); // Cui prodest?

115 Writing text The quick-and-dirty way of storing text into the server folder is: file_put_contents('text1.txt', 'we sail the ocean blue'); The function, if successful, returns a value corresponding to the number of bytes written (in this case, 22).The resulting text file can be opened with any text editor: In a more conventional way, the file can be opened either in output or in append mode, then data can be written with the fwrite function (the combination chr(13).chr(10) forces an end-of-line). The handle mechanism is still valid: $x = array('we','sail','the','ocean','blue'); // data to be written if ($h=fopen('text2.txt','w')) // output mode // (new file) foreach( $x as $v ) fwrite( $h, $v. chr(13). chr(10) ); fclose($h); if ($h=fopen('text2.txt','a')) // append mode // (data are added) foreach( $x as $v ) fwrite( $h, strtoupper($v). chr(13). chr(10) ); fwrite( $h, 45); // numeric data fclose($h); By using the append mode in the second loop, the array of words has been written a second time (in UPPERCASE), so that the final content of the text file is as follows (one word per line): The number 45 has been written without quotes: we can see that it has been transformed into a string. When write errors happen, the return value of fwrite is false (or 0), as in the following example: if ($h=fopen('text2.txt','r')) // file opened in input $f = fwrite( $h, 'test'); // attempt to write echo $f; // $f (return value) is FALSE fclose($h);

116 Case study: building a photo gallery There are innumerable photo galleries on the Internet, from corporate sites to social networks. In this example, we will use HTML, CSS, JavaScript, and PHP to produce a synergic Web page accessing a folder with our favorite pictures. This page will also receive the name of the folder as a parameter, therefore completing the circle with most of the elements studied so far. The roles for each actor are: HTML CSS JavaScript PHP Infrastructure on which all the rest is built Appearance of the page Dynamic access to different pictures Engine to access the file system on the server, containing the pictures First, let s examine how to access the images in a given folder (more specifically, a subfolder of where the page is located). The PHP functions that will be used here are four: is_dir(<string>) Check if the string (presumably, a parameter of the function) contains a valid folder name. opendir(<name>) Open the folder and assign it to a handle (a variable for future reference) readdir(<handle>) Access the folder content with the specified handle (each open folder requires its handle: in our case, only one folder is used) closedir(<handle>) Deny further access to the folder (which, of course, can be reopened at will) Step 1 accessing the file system The following is a function which receives the folder name in input, checks for validity, then returns an array containing the names of the images (or an error message, if the parameter is not a valid folder name). function getimages($dir) if (is_dir($dir)) $images = array(); // empty array $handle = opendir($dir); // open folder while ($x = readdir($handle)) // reading loop $x = strtolower($x); if // check common formats ( strpos($x,'.bmp')!=false strpos($x,'.gif')!=false strpos($x,'.jpg')!=false strpos($x,'.jpeg')!=false strpos($x,'.png')!=false ) $images[] = $dir. '/'. $x; // add to list closedir($handle); // close folder else // ERROR: return a string $images = '"'. $dir. '" is not a valid folder name'; return $images; The features of this function: Variable $handle, which is the reference to the folder, once opened; The direct assignment of each folder entry to variable $x, in the visit to the folder.

117 Step 2 designing the page The page will consist of two containers: one to the left (<aside>), containing a list of links made with the preview images; one to the right (<div>, class content), containing the image selected from the list (initially, the first one, number zero). In the preview list, the selected image will have a red outline. A bit of CSS will suffice to set up the page: aside /* container for preview */ background-color : palegreen; float : left; width : 10%; aside,.content /* shared settings /* height : 100%; overflow : auto; text-align : center; /* centers the images */.content /* magnified image */ background-color : lightcyan; width : 90%; float : right; margin : auto;.preview /* preview list */ width : 80%; margin-top : 10px;

118 Step 3 building a JavaScript array Now, PHP meets JavaScript and builds the dynamic array for the pictures, which will make it possible to dynamically change the central image. The five red echo statements actually write into the page the declaration and initialization of a JavaScript array: function js_array($images) $s=''; foreach( $images as $x ) $s.= '"'. $x. '",'; // comma-separated list $s = substr( $s, 0, strlen($s)-1); // cut last comma echo '<script>'; echo "images = [$s];"; // could be: "a.gif,b.jpg,c.jpeg,d.png" echo '</script>'; Step 4 building the dynamic elements Now, PHP will build the preview list and the central picture. Each entry in the preview list comes with an event which enables JavaScript to change the selected image, both in the list and in the central picture. Another JavaScript variable, named p, initialized through a stray statement, keeps track of the selection. The anchors are not really necessary: their only use is to change the cursor from arrow to link. <script> p = 0; // Selected image (initially 0) </script> <?php function gallery($images) $t = count($images); echo('<aside id=aside>'); // Preview (aside) for($i=0;$i<$t;$i++) $x = $images[$i]; $z = "style='border:". ($i==0? 'solid red 3px' : '0px'). "'"; echo("<a href='#'>"); echo("<img id='pic$i' class=preview $z src='$x' onclick='change($i)'>"); echo("</a>"); echo ' '; // Just for a bottom padding echo('</aside>'); // Central picture echo('<div class=content>'); echo("<img id=central height=90% src='$images[0]'>"); echo('</div>');?> <script> /* changing the selected image */ function change(i) // i = index in array "images" z = get('pic'+p); // Old "selected" loses border z.style.border = '0px'; z = get('pic'+i); // New "selected" gets border z.style.border = 'solid red 3px'; z = get('central'); // Change central image z.src = images[i]; // (using name of image #i) </script>

119 Step 5 calling the page Now it is time to put everything together. As anticipated, the gallery page will get the folder name from another page, where it will be written in a textbox. An example of a very minimalist page, which does not even need any PHP: <html> <head> </head> <body> <form action="gallery.php" method=post> <label for=folder>folder name</label> <input style="width:200px" id=folder name=folder> <input type=submit value=view title="view gallery"> </form> </body> </html> Step 6 receiving the parameter value The content of textbox folder will be received by the called page. The necessary steps to get the parameter value with the folder name will be added to the page. The first PHP statement (***) are not necessary if the page is activated by the preceding one via the submit button; it is added to cover the case when the page is directly addressed in the URL line. After the call to getimages, it is possible to check for errors: the only one possible is a name not corresponding to a folder. If this is the case, only the error message appears: If the test is successful, the functions examined before will be activated, and, pronto, our gallery will appear. <html> <head> <link href='gallery.css' rel='stylesheet' type='text/css'> </head> <body> <?php if (!isset($_request['folder'])) $_REQUEST['folder']=false; // *** $folder = $_REQUEST['folder']; $images = getimages($folder); if (is_string($images)) // Remember: string means "error" echo $images; // Display error message else js_array($images); // Build the JavaScript array gallery($images); // Build the rest of the page...?>... </body> </html> Of course, the ellipses stand for the rest of the page (PHP and JavaScript code).

120 Step 7 cleaning up the code The page may work, but we should oblige to the KISS principle and slim it up by using references to modules. Each component (PHP, JavaScript, CSS) has its most peculiar include directive: PHP <?php include...?> JavaScript <script src... > CSS <link href... > The resulting page shows the benefits of modular programming, as most activities are hidden in other files, and only the most relevant parts are in plain view. There is a bit of irony, though, since most of the PHP will not show up in the final HTML document <html> <head> <?php include('gallery lib.php');?> <!-- PHP --> <script src=gallery.js></script> <!-- js --> <link href='gallery.css' rel='stylesheet' type='text/css'> <!-- CSS --> </head> <body> <?php if (!isset($_request['folder'])) $_REQUEST['folder']=false; $folder = $_REQUEST['folder']; $images = getimages($folder); if (is_string($images)) echo $images; else js_array($images); gallery($images);?> </body> </html> <script> p=0; </script> To the right, a glimpse of how the finished page appears on the server: there are no surviving PHP statements (not even the include directive), as they have all been pre-processed. The only trace left by PHP are the arguments of the echo calls. <html> <head> <script src=gallery.js></script> <link href='gallery.css'...> </head> <body> <script>images =... </script> <aside id=aside> <a href='#'><img... </a>... </aside> <div class=content> <img...> </div> </body> </html> <script> p=0; </script> The finished project comprises the main page and three supplemental documents; there should also be at least one folder containing images, as in the following listing:

121 PHP Appendices

122 What, if anything, is a database? A database is an organized collection of information, normally associated with computer systems. In fact, databases have been designed to take advantage of the storage and retrieval capabilities of the electronic computer: not surprisingly, the first known use of the word database dates back to the early 1960 s, when large businesses were massively starting to automate their management. A DBMS (DataBase Management System) is a computer software used to process databases, providing what is called the database engine. Most DBMS offer four classic basic functionalities, commonly described as: Data definition (describing the database structure, that is, how data are organized); Data manipulation (a set of functions for inserting, modifying, and deleting data); Data retrieval (obtaining information through requests called queries); Administration (user access, data security, data integrity, crash recovery procedures) 137. If data retrieval seems closely associated with data manipulation, that s because it is. The distinction stresses the fact that, in many instances, users need only to access, rather than process, information. Arguably the most popular language for database processing is SQL (Structured Query Language) 138. Database theory was developed mostly during the 1970 s. As in all new fields of technology, different models were proposed, most of which have been phased out. Since the 1980 s, the dominant model has been the relational database 139. The relational model is based on tables 140, an example of which is the following, taken from a commercial website, showing codes, names, and prices associated to some stocks of bull semen: Some of the more popular DBMS, both open source and commercial, are listed below. The system chosen for this course is MySQL, the database engine bundled with EasyPHP, AMPPS, and XAMPP. MySQL Open source PostgreSQL Open source Firebird Oracle MS SQL Server Open source Commercial; considered the best by many; quite expensive Commercial; widely used The new frontiers for database systems are the object and XML models, not treated in this course. 137 Two issues not covered in this course are data security and data integrity; the former regards access to data, the latter, if not preserved, would undermine the entire database structure. Of course, data security is just as important when it comes to protection from theft and hacking. 138 The name can be misleading: SQL provides for all database operations, not just queries. 139 The other noteworthy legacy models were called hierarchical and network. 140 Databases normally comprise several tables: when people describe their single spreadsheet as a database, it is almost certainly an exaggeration.

123 RDBMS ABC Not surprisingly, RDBMS stands for Relational DBMS. The characteristics that have made it the reference model are not related to either hardware or software, but may be described as absolute: reliance on simple algebraic structures and operations (the algebra of relations); simplicity of the table layout. Tables contain related, homogeneous entities: in a single table, distinct entities occupy distinct rows (records), while columns (attributes or fields) represents characteristics shared by all entities. Algebraically, a table is a relation (being, as it were, a Cartesian product between entities and attributes). The following example shows how to organize the data for a fictitious hardware store. The model is quite rudimentary for an actual application, but it should at least give an idea of the most common reasoning behind the solutions. 1 Static tables store data not subject to frequent changes (of course, prices are modified and customers move to new addresses, but it does not happen on a daily basis). The first pair of tables shows one of the main features of the relational model, the connection (another relation) between tables. If each item belongs to a category, instead of storing the category description in the items table, a code is used, linking the item with the corresponding record in the categories table. Since the actual description is in another table, the linking field is called a foreign key. This, in algebraic terms, establishes a further relation between the tables, hence the name of the model (which also has other complex mathematical details, not treated in this course). Foreign keys, beside saving space, minimize data duplication, helping reduce errors due to the lack of synchronization between tables (that is, data modified in one table but nor in the other). ITEMS Code Description Category Price Retail A8UIW75 Hammer T G4JJKW Crowbar T H8TR100 Nails (100 pcs) P H8TR500 Nails (500 pcs) P G6LGS Leather gloves (small) E SUPPLIERS CATEGORIES Code Description E P S T Equipment Parts Shoes Tools Code Name Address ZIP City State Nation A8 Hampton Metal Works 15, Dead Rat St Las Vegas NV USA G4 George Brett & Co. 3301, 15 th St Las Vegas NV USA G6 Ramses & Sons 7 th Pyramid Nuri Egypt H8 Mario Ice Heap Urdz Antarctica CUSTOMERS Code Name Address ZIP City State Nation NE190 Building Wizards 7610, Beech St Worms OR USA NW447 The Sandmaster 8005, Pepper Grove Miami FL USA NW789 Electric Chairs Ltd. 4100, 87 th St Tannenberg PA USA 2 Dynamic tables store the daily activity of the business. They contain dates corresponding to events. Foreign keys are used extensively, generating links among several tables of the database. EVENTS Code Description S P D R Sale Purchase Damaged item Returned goods TRANSACTIONS Date Type Item Customer Supplier qty price 2014/01/15 P G6LGS G /02/24 P G4JJKW G /03/04 S G6LGS NW /03/05 S A8UIW75 NE Leaving aside dates and prices for a moment, selling 10 crowbars to The Sandmaster is stored as [S,G4JJKW,NW789,10], and buying 80 pairs of gloves from Mario as [P,G6LGS,H8,80]. These entities, consisting of collections of data, are called tuples. Of course, dates and prices must also be included.

124 Database design The relational model was introduced by the late Edgar Codd in the early 1960 s, and later championed by Codd himself and Chris Date (both English), with some classic textbooks and manuals. During time, a sound theoretical basis was added, summed up in the 13 Codd s twelve rules 141, which list what a DBMS should provide (though giving no technical indications on how to do so). It is not necessary to analyze all the rules, just the main points: All information in a database must be in relational form (table); Null (or empty, representing unknown data) values must be supported; Inserting, modifying, and deleting must support sets of rows (not just one row at a time: note that this may extend action on all the rows of a relation); The same query language must work both interactively and embedded in stored procedures; Logical and physical details of storage and administration must be transparent to the user (that is, the users should not know, or even care, about how the system works internally). Database design can be quite a daunting task, but the basic ideas are not that complicated. The first step in a project is recognizing the different entities, and the corresponding relations, that must be included into the database; each component corresponds to a key concept in the management of the business (conceptually), and to a particular table or relation 142 present in the DBMS (technically). In the hardware store model seen before, we can expand the analysis to include further information (by no means complete): Items and categories Warehouses and stocks (items may be stored in several locations) Suppliers and customers (subjects of interaction with our firm) Authorized users (operators may have different levels of access) Discounts (during sales management) Shopping carts (during sales management) Events (in warehouse handling, these are called inventory transactions) Event types (purchases, sales, damaged items, stolen items, free samples,...) Terms of payment (for the preparation of invoices) Banks, billings, and payments Sales tax and income tax management The second step is recognizing the information requests associated with the database, again with the need to match the concepts of the business with a series of programs or queries in the DBMS: Preparation of events (assigning items to shopping carts, or choosing which customer to bill) Summary lists of suppliers and customers (for accounting purposes, or for tax calculations) Lists of events (also called warehouse tracking) Storage reports and analyses (which items need re-supplying, or which ones should be discontinued) Various activities (lists of outstanding payments, VAT management, closing the fiscal year) The third step is reproducing the daily activity of the business by setting up the programs that gather data from the static tables and generate the dynamic data. In a commercial application like our example, all item transactions must be tracked. Of course, purchases and sales make up the bulk of the business, but there are other events or calculations that depend on various situations, such as: Damaged or stolen items Promotions (for example, complimentary goods, given away at zero price) Price changes Discount calculations and policies As previously mentioned, all inventory transactions (besides purchases and sales) usually share the same table, in order to simplify searches. Warning!!! The steps described above are not necessarily taken in that exact order. Experienced database designers know how to merge their ideas smoothly, often recycling from old applications. 141 The reason for this apparent contradiction is that they are numbered from zero through A relation may span several tables. More on this later.

125 A summary of the sample databases This textbook refers to three databases, which is best to use separately. It is true that all the tables could be stored into the same database, but this would not be advisable, if only for the sake of clarity. Sample data for all databases are present in the appendices. A fictitious store selling hardware and related items, bought from fictitious suppliers, to fictitious customers, at fictitious prices. ITEMS CATEGORIES SUPPLIERS CUSTOMERS TRANSACTIONS The objects we deal with: hammers, crowbars, pitchforks, safety shoes, paint buckets, nail boxes, candles, etc. Groups of items with similar characteristics: tools, power tools, equipment, etc. The companies we buy stuff from (normally wholesalers) The companies we sell stuff to. Customers of retail sales (over-the-counter) are not stored, since they cannot be identified. Anything happening in the store (purchases, sales, returned goods, giveaways, etc.), organized by date. These data refer to a half-marathon held in Carpenedolo a few years ago. RUNNERS TEAMS ARRIVAL The participants to the race. Since this was a masters race, they are grouped into age brackets spanning five birth years (for example, SM40 and SF40 are men and women aged 40 through 44, SM55 and SF55 are aged 55 through 59). Runners enter an age bracket when they turn 35, 40, 45, and so on. There are two more categories: the Senior (SM/SF), who have no age bracket (being usually the strongest ones), and the Amatori (TM/TF), who don t engage with Seniors, but are too young (23-34) to enter the Master. Of course, categories are split for men and women. Most teams were from the province of Brescia, like 'G.S. MONTEGARGNANO' (code 'BS362'), but there were others, like 'MARATHON TEAM BG' from Bergamo (code 'BG420'). The race time for every finisher. Of course, there are many winners, one for each age bracket, plus the absolute winners (in all cases, male and female). Data about some hypothetical Italian citizens (the names have been chosen among noted criminals and former soccer players, while some have just been made up). CITIZENS CITIES PROVINCES REGIONS Names, dates of birth, and cities of residence for 50 fictitious Italians. Some municipalities, complete with the number of inhabitants (as of the 2015 census). It is possible that some cities have since been grouped together. All the 110 provinces of Italy (which may or may not be dismissed, but still useful for distribution and logistics). Of course, given the limited choice of citizens, most of them will be ignored. All the 20 regions of Italy. Appendix D Appendix E Appendix F

126 MySQL/phpMyAdmin ABC This chapter covers phpmyadmin local servers, with two sample queries. The next one covers MySQL with MAMP, where the same queries can be used: in line with Codd s rules, every platform works with the same syntax, and only some activation details will change. Database administration in EasyPHP, AMPPS, and XAMPP is done with the same module (phpmyadmin), which can be accessed through a link in the EasyPHP Administration page (right-click on the EasyPHP icon, then Administration), through the control center in AMPPS, and with a button in XAMPP: The phpmyadmin page has two sections: a summary to the left, and an interaction area to the right. In both sections, it is possible to activate a query window for the input of SQL commands: How to activate a query window The query window opens a new page, which contains a textarea where the query can be typed, and a Go button for the activation: In most windows and feedback areas, it is possible to see the server name: in a local environment, the identification is the loopback address , whereas on a true server an actual IP address will be shown, such as (which is totally fictitious, and not even correct). Our first query should create a new database for a road test of MySQL: CREATE DATABASE test If the command is successful, the administration window should reflect the new situation, with an empty database waiting for new tables to be defined:

127 Data definition If the database were already established, it would be possible to see a list of the tables and a series of buttons and icons for both administration (Create table and Structure for data definition, Drop for erasing the table) and interaction (Browse, Search, Insert, Empty): The structure of a table, in its elementary acception, is nothing more than the list of its fields (complete with type and length), thus describing the content of each record, as shown in the following image: There are over twenty field types, but the commonly used ones are the following: Type Use for Size INT/INTEGER Integer through DECIMAL/NUMERIC Floating-point Size: N,D (digits,decimals) DATE Date through TIME Time -838:59:59 through 838:59:59 CHAR Fixed-length string The range of Length is 1 to 255 characters VARCHAR Variable-length string Same as above BLOB/TEXT Binary Large OBject A BLOB or TEXT column up to characters (Source: A BLOB is a container which can hold not only text, but also images or other binary data. The handling of these objects is outside the scope of this course. There are several variants on the basic types, with different sizes, plus a couple of enumerated data (familiar to C/C++ programmers): TINYINT/SMALLINT/MEDIUMINT/BIGINT FLOAT/DOUBLE DATETIME (date+time combo) TINYBLOB/TINYTEXT - MEDIUMBLOB/ MEDIUMTEXT - LONGBLOB/LONGTEXT ENUM/SET (field with a list of allowed values, as in F/M for gender)

128 Importing tables The first thing to do is creating a table of suppliers, matching the hardware store example. But keying in all the values cane be a very frustrating procedure: the following shows a very convenient and simple way for storing a table, complete with structure and data, all in a plain text file with an extension of.sql, not particularly complicated to decipher. One noteworthy thing is that, presumably to avoid confusion, table and field names are delimited by the ` character (grave accent: ASCII code 96), and actual values by regular quotation marks. Actually, though, the grave delimiter is optional. Of course, in the INSERT INTO statement, care must be taken in matching the data rows (introduced by the VALUES clause) with the specified field list. As previously mentioned, appendices D, E, and F contain dumps of all the tables used in the examples. They can be saved as.sql files and used for data import, or they can be obtained as distribution 143. This sample table is from the hardware store database, a more complete set of data being in appendix D: CREATE TABLE IF NOT EXISTS `suppliers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `code` char(10) NOT NULL, `name` varchar(100) NOT NULL, `address` varchar(100) NOT NULL, `zip` char(5) NOT NULL, `city` varchar(50) NOT NULL, `state` char(2) NOT NULL, `nation` char(20) NOT NULL, PRIMARY KEY (`id`) ); AUTO_INCREMENT fields contain automatically generated values, useful for a univocal identification of records, as the database engine ensures that there are no duplicates. Only one such field per table is allowed, and is almost invariably used as the primary key. INSERT INTO `suppliers` (`code`, `name`, `address`, `zip`, `city`, `state`, `nation`) VALUES ('B5', 'Bill Oglethorpe', '5020, Beech St.', '11100', 'Thunder Bay', 'ON', 'Canada'), ('G4', 'George Brett & Co.', '3301, 15th St.', '56100', 'Las Vegas', 'NV', 'USA'), ('G6', 'Ramses & Sons', '7th Pyramid', '12500', 'Nuri', '', 'Egypt'), ('H3', 'Hampton Metal Works', '15, Dead Rat St.', '48020', 'Las Vegas', 'NV', 'USA'), ('T8', 'Mario', 'Ice Heap 5026', '33100', 'Urdz', '', 'Antarctica'), ('N7', 'Color paradise', '5560, Mirage Rd.', '76980', 'Portland', 'OR', 'USA'), ('W9', 'Kippis Electric', '3049, Midnight Dr.', '63900', 'Fargo', 'ND', 'USA'); In the standard procedure, the file is chosen interactively (browsing the file system) after selecting the IMPORT tab, and the process is activated with a GO button. However, this may not work with certain operating system versions: in such cases, the whole content of the.sql file can be pasted in the SQL textarea, the activated with the corresponding, GO button as shown in the image to the right: After importing, we will be able to see both structure (left) and data (right) for the table: 143 A SQL file is a text file used to store queries. As previously mentioned with Codd s rules, stored queries must be just the same as interactive ones.

129 For another example, we can import into a separate database for the road race a new table called runners, containing, among other data, the names and bib numbers of some athletes participating to a road race 144. CREATE TABLE IF NOT EXISTS `runners` ( `id` int(11) NOT NULL AUTO_INCREMENT, `bib` int(5) NOT NULL, `family` varchar(30) NOT NULL, `name` varchar(20) NOT NULL, `gender` enum('f','m') NOT NULL, `year` int(4) NOT NULL, `category` varchar(4) NOT NULL, `nation` varchar(30) NOT NULL, `team` varchar(5) NOT NULL, PRIMARY KEY (`id`) ); INSERT INTO `runners` The enum type is used when a field may contain one from a small set of predefined, easily recognizable values, as is the case with gender. (`bib`, `family`, `name`, `gender`, `year`, `category`, `nation`, `team`) VALUES (17, 'BOTTARELLI', 'ANDREA', 'M', 1987, 'SM', 'ITA', 'BS274'), (18, 'RIMI', 'MUSTAPHA', 'M', 1980, 'SM', 'MAR', 'BS243'), (19, 'MARROCCOLI', 'MARCELLO', 'M', 1969, 'SM', 'ITA', 'BS274'), (20, 'BRESCIANI', 'GIORGIO', 'M', 1966, 'SM', 'ITA', 'BS183'), (31, 'RICOTTA', 'GIOVANNA', 'F', 1972, 'SF', 'ITA', 'VE483'), (34, 'ROBERTI', 'MARIAGRAZIA', 'F', 1966, 'SF', 'ITA', 'RI224'), (35, 'MORENI', 'SILVIA', 'F', 1972, 'MF35', 'ITA', 'BG134'), (37, 'TONOLINI', 'ASHA', 'F', 1979, 'SF', 'ITA', 'BS243'), (38, 'BACCANELLI', 'MONICA', 'F', 1975, 'MF35', 'ITA', 'BS688'), (39, 'TUROTTI', 'NADIA', 'F', 1962, 'SF', 'ITA', 'BS243'), (42, 'CLEMENTI', 'STEFANO', 'M', 1972, 'MM35', 'ITA', 'BS368'), (48, 'REBUZZI', 'MANUELA', 'F', 1983, 'SF', 'ITA', 'RE105'), (49, 'LUSARDI', 'ROBERTO', 'M', 1967, 'MM40', 'ITA', 'BS278'), (52, 'APOLONE', 'ELENA', 'F', 1969, 'MF40', 'ITA', 'BS707'), (53, 'SBARDELLATI', 'VALTER', 'M', 1959, 'MM50', 'ITA', 'BS707'); The following are snapshots of the structure and some records of the resulting table: 1. The athletes are separated by gender (M/F) and category (different age brackets). 2. The association between team code and team name will be done later. 144 A more complete set of tables for the road race can be found in Appendix E.

130 MySQL with MAMP 1 Launch MySql PRO WARINING!!! WHEN USING MYSQLPRO, THE MAMP SERVER MUST BE SWITCHED ON. 2 Select the SOCKET tab to connect to a local MYSQL server complete Username: root Password: root 3 Click connect to start the connection. To create a database, go at the top of the window, in the Add database section, and create a new one.

131 The queries can be transcripted or copied from the ones contained in the preceding pages: CREATE DATABASE test CREATE TABLE IF NOT EXISTS `suppliers`... INSERT INTO `suppliers` (`code`, `name`, `address`, `zip`, `city`,... It is also possible to open a.sql file containing the queries, which could obtained as distribution. The following is an example of such a file saved from the appendices of this document: Select all the required lines, then copy and paste them into the Query section at the top of the MYSQLPRO window: To run all the queries, click on the arrow-shaped object near Run previous and then run all queries

132 After all the queries have been run, the imported tables will appear on the left pane of the window. The image is taken from a complete database, while with our first three queries the only table will be suppliers: Choose File, then Save Connection As...; choose a name, then click on Save: Now it is possible to write any query. Just click on query at the top of the MYSQLPRO window, delete all the existing queries, and write a query: This particular query, which is quite intuitive, will show all the data stored in table suppliers. Click Run all queries one more time to run the one just written.

133 Queries: an overview The workhorse of SQL is the SELECT statement. In its simplest form, it contains a list of fields to be extracted from a table (the keyword null stands for no fields, the wildcard character * stands for all fields). SELECT * FROM customers SELECT code, name FROM customers SELECT date, item, qty, price FROM transactions SELECT null FROM transactions The request for specific fields is called projection: simply put, it corresponds to a vertical slicing of the table, choosing some columns and neglecting the others 145. The dual 146 operation of the projection is called section, and corresponds to a horizontal slicing of the table, choosing which records to extract and neglecting the others. This action, sometimes called filtering, is done with the WHERE clause, which supports a condition: SELECT code, address FROM suppliers WHERE city = "Las Vegas" The preceding SELECT extracts the fields written in red (the blue field is the match to be met): SUPPLIERS id code name address zip city State Nation 1 B5 Ogie Oglethorpe 5020, Beech St Thunder Bay NV USA 2 G4 George Brett & Co. 3301, 15 th St Las Vegas NV USA 3 G6 Ramses & Sons 7 th Pyramid Nuri Egypt 4 H3 Hampton Metal Works 15, Dead Rat St Las Vegas USA 5 T8 Mario Ice Heap Urdz Antarctica This course does not analyze the mathematical properties of relational operations 147. What we need to know is that projections and sections, retaining the tabular form, result in other relations 148, as shown below: code address G4 3301, 15 th St. T8 15, Dead Rat St. Along with the usual six comparison operators (with a single = sign for equal, unlike C/C++, and the choice of not equal as both!= and <>), there is a further operator for strings (LIKE), which supports the wildcard character (%, which stands for any substring, of any length). Some examples of how the % wildcard works: 1. SELECT * FROM suppliers WHERE city LIKE "a%" 2. SELECT * FROM suppliers WHERE city LIKE "%a" 3. SELECT * FROM suppliers WHERE city LIKE '%a%b%' The corresponding sections operated on the table: A request for null ( no fields ) saves time when just counting records. Strings can be delimited with both single and double quotes. 1. Anything starting with "a" (uppercase or lowercase) 2. Anything ending with "a" (uppercase or lowercase) 3. Anything containing an "a" followed by a "b" (anywhere, as in "able", "jab", or "Maracaibo") Of course, filters may be complex, with several conditions linked by logical operators (AND, OR, NOT), and possibly with parentheses:... WHERE city = "Las Vegas" AND address LIKE "%st."... WHERE city = "Las Vegas" AND ( address LIKE "%st." OR zip = "56100" ) 145 This is still valid in a request for all fields, where the subset of discarded columns is the empty set, or in a request for no fields, where the subset of discarded columns is the universe of all columns. 146 The concept of duality is mutuated from projective geometry. 147 Relations are subsets of Cartesian products, and, as such, follow the rules of algebra. 148 This uniformity is one of the reasons of the success of the relational model.

134 We talkin bout PRACTICE 149 Queries can be submitted after choosing either the SQL or the Query tab. Both screens contain a textarea for the entry of a written query; the latter, though, is designed for a more interactive selection, made through select boxes, checkboxes, and radio buttons 150. Of course, practicing SQL means that, rather than using interactive elements, we should stick to the textarea and write complete queries in text form. Suppose we submit this query: SELECT * FROM suppliers WHERE city = "Las Vegas" The screen will subsequently show a view of the resulting projection/section: Several actions can be done on the resulting records, by clicking on the corresponding icons. Records can be selected/unselected with check boxes, or by clicking on the Check All/Uncheck All links: global actions can be made by clicking on the icons placed below the view, and labeled With selected. Normally, large sections will only be copied or deleted, as editing is a little awkward to negotiate 151. The outcome of an unsuccessful 152 query is described with an appropriate message: One interesting feature is bookmarking, which allows to store the current query for later use: The corresponding section of the SQL screen is labeled, not surprisingly, Bookmarked SQL query, and contains a set of radio buttons, which allow the user to submit, view, or delete any query present in the list of stored queries, which is also shown: 149 Allen Iverson (The Answer), American basketball player (May 7, 2002). 150 This design follows a rather ancient mantra, according to which anybody will be a computer programmer by the next five years, given the appropriate software tools. However, experience shows that this is only wishful thinking: more often than not, most would-be programmers give up after a quick glance at the and/or radio buttons (and rightly so). That this is being repeated since the 1980 s is further proof of the nonsense being brought forth. 151 Also, complex actions would also call for other queries, rather than individual actions. 152 Unsuccessful does not mean wrong, only that no records were found.

135 Joining tables Data are often spread out across multiple tables. This happens 153 when a certain attribute can be coded with simpler and/or shorter information: in such cases, the main table is linked to a secondary one through a foreign, or external key. In one of the examples, hardware store items were categorized in a very simple (and probably unreal) fashion, with a letter. The idea is that it is quite preferable to store E in the items table, in place of the full description Equipment: the advantage is not so much in the saved memory space (which could have been an issue in the pioneering years of computer science, certainly not now), but rather in the reduced possibility of mistyping the corresponding data 154. ITEMS code Description category price retail A8UIW75 Hammer T G4JJKW Crowbar T H8TR500 Nails (500 pcs) P G6LGS Leather gloves E CATEGORIES code description E P T Equipment Parts Tools In another example, all the municipalities in Italy have been assigned a national code, which loosely follows an alphabetical order. It is presumable that an operator, during data entry, would choose the city from an alphabetic list, and the program would store the associated code into a table of Italian residents (after all, national codes were not designed to be memorized by humans). One possible situation can be sketched in the following example, with one table for Italian residents (citizens), and one for the municipalities (cities): name other data city Tanghetti Ezio... G149 Turotti Alberto... G150 Zilioli Giuseppe... G149 Facchetti Fabio... G149 Citizens residing in Orzinuovi are associated to the national code G149; for those residing in Orzivecchi, of course, the corresponding national code is G150. code province name G148 TR ORVIETO G149 BS ORZINUOVI G150 BS ORZIVECCHI G151 TO OSASCO source: The trick, during data retrieval, is to extend relations across tables, by using one of the smartest weapons of SQL, the JOIN clause, where the foreign key (in red) links to the corresponding row in the reference table. Of course, fields must be qualified (even more so in this example, where some fields are homonymous): SELECT items.code,categories.description FROM items JOIN categories ON items.category = categories.code SELECT citizens.name, citizens.city, cities.name FROM citizens JOIN cities ON citizens.city = cities.code The results, as anticipated, are new relations, with qualified field names: items.code categories.description A8UIW75 Equipment G4JJKW Parts H8TR500 Tools G6LGS Tools citizens.name citizens.city cities.name Tanghetti Ezio G149 ORZINUOVI Turotti Alberto G150 ORZIVECCHI Zilioli Giuseppe G149 ORZINUOVI Facchetti Fabio G149 ORZINUOVI 153 Rather, good database design implicitly requires this to be done. 154 Errors can only be reduced, but never avoided completely: sooner or later, even the most experienced operator will hit the wrong keys or click on the wrong link.

136 Give us the tools, and we will finish the job 155 Anyway, the time has come for a review of the basic components of the SQL-SELECT statement. projections are determined by the field list 156, immediately after the keyword SELECT; sections are determined in the WHERE clause (or HAVING; more on this later); data are sorted according to the ORDER BY clause; relations are extended across tables by the JOIN clause; summary data are obtained by the GROUP BY clause. Before starting with our review, though, it will be necessary to load the table called teams, containing the names of the teams to which the runners belong, and the table called arrival, containing the final race time. This will enable us to use more complex queries. The complete data are in Appendix E. This is a snapshot of some records of the resulting table: With this data, it will be possible to link the codes present in the runners table with the corresponding team, e.g.: GE017 = Gruppo Città di Genova BS341 = Atl.Falegnameria Guerrini This is the easiest part, as it only takes choosing the fields involved in the projection, either explicitly (with a comma-separated list) or implicitly (with the wildcard character * or the null argument). 1. SELECT bib, family, category FROM runners 2. SELECT * FROM runners 3. SELECT null FROM runners The WHERE clause is normally quite simple, as in: 1. SELECT * FROM runners WHERE category = 'SM' [only 'Senior Male' runners] WHERE team = '' OR team = '-' [no team listed] WHERE bib < '100' AND category LIKE 'MF%' [top 'master' female runners] WHERE team NOT LIKE 'BS%' [teams outside Brescia] Commercial application sometimes have much more complex requests (more on these later, in the paragraph on the JOIN clause). It is possible to be very creative, but the necessity seldom arises. No application, except presumably a school test, calls for something like the following: List all runners with an 'A' in the first name or a 'T' in the last name, born either before 1970 or in WHERE ( name LIKE '%a%' OR family LIKE '%t%' ) AND ( year < 1970 OR year = 1993 ) 155 Winston Churchill, February 9, 1941, on the BBC. 156 The wildcard *, which in certain SQL versions is written as (*), is itself a list of fields.

137 Query results can be ordered through any field or combination of fields, in either ascending (the default) or descending order. A descending order is normally used with dates (or birth years), when most recent data (corresponding to younger people) are to be shown first. For example, before a road race, athletes and coaches may look up any of the following: 1. List of athletes by their bib number 2. List of athletes by name (for those who do not know their bib number) 3. List of athletes by team (in each team, athletes are listed alphabetically) 4. List of athletes by year of birth (for senior master categories, divided into age brackets) When large lists of people are processed, it is normal to encounter duplicate family names. For this reason, family names are usually complemented by first (given) names; if that should not suffice, other data may be used for sorting. It is doubtful that the same team, especially in a local race, would have athletes with the same family name, first name, and year of birth; yet, database designers should be prepared for the worst (meaning the wildest) combinations of data. This is not the case of the preceding requests, quite simple: 1. SELECT... ORDER BY bib 2. SELECT... ORDER BY family ASC, name ASC, year DESC 3. SELECT... ORDER BY team ASC, family ASC, name ASC, year DESC 4. SELECT... ORDER BY year DESC, team ASC, family ASC, name ASC Listing the fields in a multiple-table relation can be very tedious, and it is a common practice to qualify tables by a short alias, as in the following examples. The first set shows the full alias: 1. SELECT runners.bib, runners.family, runners.name, teams.name FROM runners JOIN teams ON runners.team=teams.code 2. SELECT runners.*, teams.* FROM runners JOIN teams ON runners.team=teams.code The equivalent queries using short aliases are the following: 1. SELECT a.bib, a.family, a.name, b.name FROM runners a JOIN teams b ON a.team=b.code 2. SELECT a.*, b.* FROM runners a JOIN teams b ON a.team=b.code Of course, after the race the main concern is the order of arrival (in a timed event, corresponding to the race time). In some races, though, athletes are divided into age groups, so their category is processed first (and, of course, the main division is by gender): SELECT a.family,a.category,a.gender,b.time FROM runners a JOIN arrival b ON b.bib=a.bib ORDER BY a.gender ASC, a.category ASC, b.time ASC It is quite normal to counts rows and sum numeric fields or expressions. It is invariably COUNT(*), as there is no advantage in counting a single field. Other common grouping functions are AVG, MIN, and MAX. The one thing to remember is that such operations collapse all the related records in one single row, as can be seen with the following examples, the results of which are shown below (at least, partially): 1. SELECT COUNT(*) FROM runners 2. SELECT SUM(inhabitants) FROM cities GROUP BY province

138 Queries and PHP A PHP page implementing a MySQL query must contain all the steps that users would take interactively: 1. Connecting to the MySQL server (mysql_connect) and qualifying as a legitimate user; 2. Choosing the database (mysql_select_db); 3. Submitting the actual query (mysql_query), stored into a PHP string; 4. Looping through the records one at a time (mysql_fetch_array), to obtain the actual data. The results of each operation (false for unsuccessful) can be checked with the usual PHP statements. In the real world, we would browse to the server address, then provide username and password. In our local environment 157, we did not set access control: this is perfectly safe, since hardly anybody from outside would mess around with test data 158. Each local server software has its own choice of default administrator credentials, which are listed below (remote servers assign specific credentials with their own criteria): AMPPS EasyPHP MAMP XAMPP $host='localhost'; $user_name='root'; $password='mysql'; $host='localhost'; $user_name='root'; $password=''; $host='localhost'; $user_name='root'; $password='root'; $host='localhost'; $user_name='root'; $password=''; These data are specified as arguments of the mysql_connect function: $conn = mysql_connect( $host, $user_name, $password); The outcome of the operation is stored into the lvalue of the statement, which is the handle for all future references to the data source. It is also possible to check the success of the operation, but in our first example, we will skip this part (of course, we must ensure that the data written in the program are correct). The database can be selected among those associated with the resource: $db = mysql_select_db('test', $conn); The lvalue of this statement cannot used as a handle, but only to check for a successful operation. Then comes the actual query, which is a PHP string, as in: $q = mysql_query('select bib, family FROM runners', $conn); It should be noted, however, that a successful query does not necessarily imply actual retrieval of any number of records: the result of the mysql_query statement is a resource, which must itself be polled in search for data. Each call to the mysql_fetch_array function delivers an associative array, whose keys are the names of the fields involved in the main query. Numeric indexes can be used, provided the programmer knows their actual order. $conn = mysql_connect( $host, $user_name, $password); $db = mysql_select_db('test', $conn); $q = mysql_query('select bib, family FROM runners', $conn); if ( $q ) while ( $row = mysql_fetch_array($q) ) var_dump( $row); // or other operations Putting everything together In the loop, each record is processed individually. The outcome is rather crude, but it gives the idea of how the data are returned, with both associative and numeric indexing to the individual records (that is, $row[0] and $row["bib"] refer to the same data): array(4) [0]=> string(1) "1" ["bib"]=> string(1) "1" [1]=> string(4) "TOSI" ["family"]=> string(4) "TOSI" array(4) [0]=> string(1) "2" ["bib"]=> string(1) "2" [1]=> string(7) "MOKRAJI" ["family"]=> string(7) "MOKRAJI" 157 The local server can be referred to either as localhost or (also known as the loopback address). 158 Normally, testing is done with fictitious data in a local environment, so as to avoid damaging the actual databases.

139 How to process queries in PHP Let us now examine the content of the fetched array, when executing the following query: $q = mysql_query('select bib, family, name, category FROM runners', $conn); while ( $row = mysql_fetch_array($q) ) // $row[] is an array of data If the query were issued to PHPMyAdmin, the data would be shown like this: In a PHP loop, the first round will store in the $row[] array the four data for Gobbo; the second round, the four data for Tononi; the third round, the four data for Moreni; the fourth round, the four data for Tonolini. The fetched array is both numbered and associative, and data can be retrieved by either position or key: Numeric index Associative index Sample Values $row[0] $row['bib'] '4' '10' '35' '37' $row[1] $row['family'] 'GOBBO' 'TONONI' 'MORENI' 'TONOLINI' $row[2] $row['name'] 'SIMONE' 'CRISTIAN' 'SILVIA' 'ASHA' $row[3] $row['category'] 'SM' 'MM35' 'MF35' 'SF' Normally, we might want to build a HTML <table> similar to the result obtained with phpmyadmin. In the PHP script, this is what we would write: $s = '<table>'; while ( $row = mysql_fetch_array($q) ) $s.= '<tr>'; $s.= '<td>'. $row['bib']. '</td>'; $s.= '<td>'. $row['family']. '</td>'; $s.= '<td>'. $row['name']. '</td>'; $s.= '<td>'. $row['category']. '</td>'; $s.= '</tr>'; $s.= '</table>'; Duplicate field names It should be noted that, when a relation comprises duplicate names (in different tables, of course), the keying mechanism is unable to recognize both fields in the associative array resulting from the fetch operation. Let us consider the query: SELECT family, a.name, b.name FROM runners a JOIN teams b ON a.team = b.code A dump of the fetched array shows that the preference goes to the last field listed in the projection, so that $row['name'] refers to the name field in the teams table, and the only way to access the field runners.name is by its numeric index (0, it being the first one listed): Field Numeric index Associative index Sample Values family $row[0] $row['family'] 'NASSINI' 'GIANI' a.name $row[1] NONE 'GIORGIO' 'MILENA' b.name $row[2] $row['name'] 'C.S. S.ROCCHINO' 'U.S. MALONNO'

140 By the book In actual applications, both error handling and clear user feedback should be included. In the following example, each database operation provides an escape mechanism (though rather crude), and the data are embedded in a HTML table, so as to get a better view on the screen. There are many ways (some of which, rather appalling, should be avoided) to enhance visual information: in this case, the table rows have different colorings, according to the gender of the corresponding runner. $conn = mysql_connect( $host, $user_name, $password) or die('unable to qualify'); $db = mysql_select_db( $db_name, $conn) or die('unable to connect to database'); $sql = "SELECT * FROM runners ORDER BY family"; $q = mysql_query( $sql, $conn); if ( $q == null ) $s = 'invalid query'; else // building a HTML table with all the proper details $s = '<table border=4 cellpadding=2>'; $s.= '<th>bib</th>'; $s.= '<th>family name</th>'; $s.= '<th>name</th>'; $s.= '<th>gender</th>'; $s.= '<th>year</th>'; $s.= '<th>team</th>'; while ( $row = mysql_fetch_array($q) ) if ( $row['gender'] == 'F' ) $color = '<tr class=pink>'; else $color = '<tr class=cyan>'; $s.= $color; $s.= '<td>'. $row['bib']. '</td>'; $s.= '<td>'. $row['family']. '</td>'; $s.= '<td>'. $row['name']. '</td>'; $s.= '<td>'. $row['gender']. '</td>'; $s.= '<td>'. $row['year']. '</td>'; $s.= '<td>'. $row['team']. '</td>'; $s.= '</tr>'; $s.= '</table>'; Classes for coloring the table rows:.pink color.cyan color echo $s; // Showing the table is necessary With the aptly named die() clause, programs with errors just stop after issuing a simple message. There are other, better techniques for error trapping, which are beyond the objectives of this course. The outcome is getting better: data are shown in a more fitting way, as in this partial view: : salmon; : steelblue; Setting up a table for a possible query error message is left as an exercise:

141 A new version? In some cases (notably, with XAMPP), a different set of PHP functions is required, identified with mysqli (which stands for mysql improved), which disposes of the database connection, or, rather, it embeds it into the qualification function. With just a few changes, the fetching mechanism has the same structure. In the following example, we will see how to activate a less rudimentary error trapping mechanism, with the use of the try structure. We will also join all the tables, to view the standings of the female race and the names of the running teams, which, as we saw before, are stored in another table; another feature shown will be a virtual column, generated by joining the family name and the first name of the runners. mysqli_report(mysqli_report_strict); // essential to avoid crashing the script $host=' '; $host='localhost'; // XAMPP settings $user='root'; $pw=''; $db_name='road race'; $s = '<table border=4 cellpadding=2 style="align:center; text-align:left;">'; try $conn = mysqli_connect($host,$user,$pw,$db_name); $sql = "SELECT a.bib,concat(a.family,', ',a.name) AS name,b.time,c.name,a.gender "; $sql.= " FROM runners a "; $sql.= "JOIN arrival b on a.bib=b.bib "; $sql.= "JOIN teams c on a.team=c.code "; $sql.= "WHERE a.gender='f' "; $sql.= "ORDER by b.time "; $q = mysqli_query($conn,$sql); if ($q==null) $s.= '<tr><td>unable to query</td></tr>'; else $i = 0; $s.= '<th>place</th>'; $s.= '<th>bib</th>'; $s.= '<th>runner</th>'; $s.= '<th>time</th>'; $s.= '<th>team</th>'; while ($row = mysqli_fetch_array($q,mysqli_both)) $i++; $s.= '<tr>'; $s.= '<td>'. $i. '</td>'; $s.= '<td>'. $row['bib']. '</td>'; $s.= '<td>'. $row['name']. '</td>'; $s.= '<td>'. $row['time']. '</td>'; $s.= '<td>'. $row[4]. '</td>'; $s.= '</tr>'; catch (Exception $e) // Traps error on mysqli_connect $s.= '<tr><td>unable to connect to database</td></tr>'; $s.= '</table>'; echo $s; The compound column family must be given a name, so as to keep its tracks in the fetching loop. The result is shown in the image below. The MYSQLI_BOTH argument ensures that the data array has both the numeric and the associative indexing. This looks fine enough, and some local servers even take the trouble of issuing a warning when the obsolete mysql set is used. But, alas, all that glitters isn t gold: on some remote servers, mysqli queries just don t work (what s worse, without any warning).

142 In the real world Developers normally use a trick to switch seamlessly between the local environment (where applications are tested) and the actual server (where applications are deployed for actual use). The HTTP_HOST element of the superglobal array $_SERVER returns the network address of page: on the local host, the result contains either the loopback address or the mnemonic localhost, associated to an open SQL server (open, that is, in not requiring a password, other than the default). function is_local() // This function should be public if ( is_numeric( strpos( $_SERVER['HTTP_HOST'], " ")) is_numeric( strpos( $_SERVER['HTTP_HOST'], "localhost"))) $x = true; else $x = false; return $x; Somewhere, in an initialization routine, key variables are set up accordingly: if (is_local()) // which environment? $host=' '; // secure local server no password $user_name='root'; // or follow the standard for the $password=''; // specific local server bundle $db_name='test'; else $host=' '; // public server password protected $user_name='sql '; $password='georgebrett'; // this will not be shown in the application $db_name='db_15'; In any PHP page of the application, scripts could just use these variables, without further considerations about which environment is being used; but then the problem arises of how to make them available. One solution is the global clause 159, which ensures that the script where it is placed has knowledge of the referred variables: global $host, $user_name, $password, $db_name; $conn = mysql_connect( $host, $user_name, $password);... Alternatively, one can resort to the $_SESSION superglobal: /* */ $_SESSION['host']=' '; $_SESSION['$user_name'] 'SQL '; $_SESSION['$password']='GeorgeBrett'; $_SESSION['$db_name']='DB_15';... Elsewhere in the application $host=$_session['host']; $user_name=$_session['$user_name']; $password=$_session['$password']; $db_name=$_session['$db_name']; $conn = mysql_connect( $host, $user_name, $password); As previously mentioned, variables are not declared in PHP: this clause regards scope, not existence.

143 DB management: deleting and modifying records No application would be complete without the possibility of deleting and modifying incorrect or unwanted data. Of course, the SQL language has got what it takes. Deleting an entire table is quite simple, and it can be done with two distinct statements: TRUNCATE TABLE runners DELETE FROM runners Normally, this is not required (quite the contrary: such operations are well hidden from the inaccurate user, sometimes called a yellow duck ), and records are deleted according to some criterion: DELETE FROM runners WHERE <condition> It only takes one line of code to delete all the customers residing in Nevada, or the sales done in the year 2015, as the WHERE clause is just the same as in the SELECT statement: DELETE FROM customers WHERE state = 'NV' DELETE FROM transactions WHERE date LIKE = '2015%' or DELETE FROM transactions WHERE YEAR(date) = 2015 Commercial applications have service functions for closing a business year, which include deleting batches of transactions (of course, these operations should be done after saving said transactions in safe backup files). So, it is quite possible to use a dialogue like the one to the right: the form sends a request to another PHP page, which receives the information through one of the superglobal arrays reserved for intercepting data entry: _REQUEST, _POST, or _GET. Supposing that the field name were year, the second page could include something like: $year = $_POST['year']; $query = "DELETE FROM transactions WHERE YEAR(date) = $year"; $q = mysql_query( $query, $conn); The matter is a little trickier when browsing through individual records, which are normally associated to a sequence of operations, activated with buttons or anchors. In the following screenshot, taken from an actual application, it is possible to activate the following functions for each record: review historical data (parchment icon); edit the record (pencil icon); delete the record (cross icon). Once again: the date can be treated either as a string or as a data structure In this case, the problem is singling out the correct record to operate on. What happens is that, during the construction of the HTML table containing the data, each link is associated to a JavaScript function which, in its turn, activates a PHP page with a unique record identifier as an argument: this way, the receiving page knows which record is to be modified or deleted. This is not as complicated as it may seem, thanks to the looping mechanism, which restricts building custom anchors to one single step, but it still is something for experts, requiring a combination of HTML, JavaScript, PHP, and SQL, not excluding CSS.

144 There s an error born every minute 160, for a number of reasons: even experienced operators can mistype data; existing information may be incorrect or incomplete; partial transactions may need to be completed, or modified due to new regulations. Whatever the reason, data can be modified with the aptly named UPDATE statement. For example, increasing by 10% the retail price of all the shoes on stock can be done with the following: UPDATE items SET retail = retail + 10 * retail / 100 WHERE category = 'S' The SET keyword introduces a comma-separated list of the fields that will be modified, each with the corresponding formula (rvalue). The norm for multiple fields to be updated is when a single record is being processed; in this case, the clause is used to identify said record, by specifying the value of its primary key 161. For example, the hardware store application will provide editing functions for all its tables. Suppose that we have identified the supplier George Brett & Co., whose data need to be verified and/or updated, having changed their company name to George Brett Ltd.. After retrieving the record through the code G4, its data could be shown in a form like the following: After editing the data and clicking on the submit button, a receiving page will gather the values of the fields from the superglobal array $_POST, then build an update string by combining them all: $name = $_POST['name']; $address = $_POST['address']; $zip = $_POST['zip']; $city = $_POST['city']; $state = $_POST['state']; $query = "UPDATE suppliers SET"; $query.= " name = '$name'"; $query.= ", address = '$address'"; $query.= ", zip = '$zip'"; $query.= ", city = '$city'"; $query.= ", state = '$state'"; $query.= " WHERE code = '$code'"; $q = mysql_query( $query, $conn); In the assignment clauses, the quote character (as in '$name') is necessary, because values containing spaces would break up the query syntax. WRONG ("Brett" is not recognized):... name = George Brett Ltd.... CORRECT:... name = 'George Brett Ltd.'... The result of the concatenation of strings in the sample statement above could be something similar to the following (where only two fields are included): UPDATE suppliers SET name = 'George Brett Ltd.', state = 'NV' WHERE code = 'G4' Incidentally, a query for inserting a new record into the table is not too dissimilar, except for the way fields are enumerated. The procedure would probably include the same identical form (presumably, with slightly different prompts), then something like: INSERT INTO suppliers (code, name, state) VALUES ('G4', 'George Brett Ltd.', 'NV') 160 There s a sucker born every minute, ca. 1850, origin unknown (attr. to either Joseph Bessimer or David Hannum). 161 A primary key is a unique identifier for each record. The database engine ensures uniqueness by not allowing duplicates during insertion and editing.

145 Some serious stuff Some data for the hardware store database are in Appendix D. Some data for the Italy database are in Appendix F. Extract all the items unsold in the year The problem here is to specify the unsold clause: as it always happens in data processing, this requires a translation into the available features of the language. In SQL we can resort to the EXISTS clause, which can be used to check whether a query result does have rows: of course, this implies a secondary query in the transactions table. Not needing any data from that table, this is one of those cases when a SELECT null may considerably speed up the resulting query. SELECT * FROM items a WHERE NOT EXISTS (SELECT null FROM transactions b WHERE b.event='s' AND b.item=a.code AND YEAR(date)=2013) List all the sales of items normally bought from supplier 'Mario', made between March and May 2014, to customers residing in Florida (commonly stored as 'FL'). In this case we have multiple tables, resulting in several JOIN clauses, some of which are chained. The transactions table joins the items table, which joins the suppliers table: this makes it possible to fetch all the data needed, possibly to print out a report. There also is an example of the BETWEEN clause, quite uncommon in programming languages, but very clear and useful when a search range is required. SELECT * FROM transactions a JOIN items b ON b.code=a.item JOIN suppliers c ON c.code=substring(b.code,1,2) JOIN customers d ON a.code=d.code WHERE c.code = 'H8' AND d.state = 'FL' AND ( a.date BETWEEN '2014/01/01' AND '2014/05/31' ) ORDER BY b.code ASC, a.date ASC List all the sales of safety equipment made for a discount greater than 25% in the year In this case we have an expression (instead of a field) involving the discount rate: this requires a little tinkering both in the projection and in the section. Projection A discounted price is normally calculated with a percentage rate: PRICE = RETAIL RETAIL / 100 * RATE With a little bit of algebra, the formula for the discount rate becomes: RATE = ( RETAIL PRICE ) * 100 / RETAIL If it is to be used in the SELECT clauses, the expression should be given a name through the AS clause. Section Expressions (like said discount) and groupings (an advanced topic, not treated in this course) do not fit into the WHERE clause, but require the HAVING keyword. The resulting query is the following: SELECT *, ( b.retail - a.price ) * 100 / b.retail AS discount FROM transactions a JOIN items b ON b.code=a.item WHERE a.event='s' AND b.category = 'E' HAVING discount > 25 ORDER BY a.date ASC, b.code ASC

146 Find which Italian province has the most inhabitants, then single it off, all in the same query. WARNING!!! a typical query would not show duplicates of aggregate values (such SUM or COUNT), in case multiple provinces had the same maximum total. Managing duplicates is possible, though, by tweaking the query via a wicked mechanism, which will be shown in the next example. Another solution could be managing the duplicates in the PHP data fetch loop, by using the familiar control structures of the language. Step 1: compute the total number of inhabitants for all the provinces of Italy SELECT province,sum(inhabitants) AS habs FROM cities GROUP BY province (ORDER BY province) The SUM column has been given an alias, so as to be recognized in further references to it (as we will see in the subsequent steps). In some obsolete versions of MySQL, the supplementary ORDER BY clause could be necessary, to ensure that all the records belonging to the same section be adjacent. The image to the right shows a situation where two cities in the province of Mantova, being separated by one in the province of Milano, would yield two distinct totals. This does not seem to be the case any longer. Anyway, adding the unnecessary clause does no harm. Step 2: use the previous result by adding the name of the province, then sort all provinces from the one with the most inhabitants down to the one with the least. That s true, we can feed the result of a SELECT query into another. In this case, it is necessary to give an alias to the result of the inner query, since it is not an actual table, but a computed one: SELECT a.*,b.name FROM ( SELECT province,sum(inhabitants) AS habs FROM cities GROUP BY province ORDER BY province ) AS a JOIN provinces b ON a.province = b.code ORDER BY habs DESC The innermost quety (in green), while not a table, is still a relation, so it can be used as such: of course, it cannot have an alias by itself, and that s the reason why we provide it with one (... AS a). Step 3: use the previous results to select ONLY the province with the most inhabitants. Now the reason for the ordering in the previous step becomes evident, since the max() function would return the sum field for the province with the most inhabitants (which is Rome), but the table would be collapsed to one row, with the other values coming from the first province (which, in alphabetical order, is Agrigento), resulting in a confused view. Again, the partial table must be given an alias. SELECT c.province,max(c.habs),c.name FROM ( SELECT a.*,b.name FROM ( SELECT province,sum(inhabitants) AS habs FROM cities GROUP BY province ORDER BY province ) AS a JOIN provinces b ON a.province = b.code ORDER BY habs DESC ) AS c The alias for the final query (in blue) could have been b, instead of c, as it would not have interfered with the same alias b in the second query (in red). Yet, a different alias may be preferable, just to avoid confusion on which b is which. And there it is, the province of Rome, all by itself:

147 Managing duplicates requires supplemental countings, with some redundancies. In this example, we are going to improve the previous query in case there are multiple provinces with the same number of inhabitants (a very improbable one, but still possible, presumably in other situations). We might rephrase the exercise as: find which Italian provinces have the most inhabitants, then single them off, all in the same query. SELECT province,habs,n FROM (SELECT province,sum(inhabitants) AS habs,b.name as n FROM cities a JOIN provinces b ON a.province = b.code GROUP BY province ORDER BY habs DESC) AS dummy WHERE habs = (SELECT MAX(habs) FROM (SELECT sum(inhabitants) AS habs FROM cities GROUP BY province ORDER BY habs DESC) AS dummy) Quite wicked, indeed. The tricky part is the filter on the calculated column habs, which is reduced to a single number by the query inside the green parentheses. The fake name dummy is a relic from the past, where it was widely used to indicate a slack variable or table. In a more plausible situation, the road race organizers might want to select the teams with the most participants, possibly to assign them a prize. There is a probability (not a strong one, though) that more than one team could have the same number of runners. SELECT team,n,c FROM (SELECT team,b.name AS n,count(*) AS c FROM runners a JOIN teams b ON a.team=b.code GROUP BY team) AS dummy WHERE c = (SELECT MAX(c) FROM (SELECT COUNT(*) AS c FROM runners a GROUP BY team ORDER BY c DESC) AS dummy) Another possibility is using the so-called views, which, simply put, are virtual tables based on the result of a SQL-SELECT. Views are relations, after all, and have two important features: 1. They only waste a minimum of storage space; 2. They keep calculated fields updated in real time. Views are best used to avoid redundancies, especially when dynamic data (in short: calculated fields) are present. The solutions to the last examples are summarized in the following table, where the first row creates the view and the second one is the actual query (which is greatly simplified) CREATE VIEW leshabs as (SELECT province,sum(inhabitants) AS habs,b.name AS n FROM cities a JOIN provinces b ON a.province = b.code GROUP BY province ORDER BY habs DESC) SELECT province,habs,n FROM leshabs WHERE habs = (SELECT MAX(habs) FROM leshabs) CREATE VIEW counter AS (SELECT team,b.name AS n,count(*) AS c FROM runners a JOIN teams b ON a.team=b.code GROUP BY team) SELECT team,n,c FROM counter WHERE c = (SELECT MAX(c) FROM counter)

148 For each province of Italy, extract the year when the most citizens were born. Hint: first, count the citizens grouped by province and year of birth. As in the other cases, the simple solution does not provide for duplicates, while a second one, making use of views, greatly simplifies the query. SOLUTION WITHOUT DUPLICATES SELECT province,max(c),y FROM (SELECT b.province, COUNT(*) AS c,year(dob) AS y FROM citizens a JOIN cities b ON a.city=b.code GROUP BY b.province,year(dob) ORDER BY b.province,c DESC) AS dummy GROUP BY province SOLUTION WITH DUPLICATES The situation is much more complex than in the previous examples, because of the presence of two levels of grouping. This branching makes it improbable to use a single query on the fly, because counting and choosing yield collapsed relations, both of which muse be matching the corresponding province. At least, nothing that yours truly can think of. One simplest solution involves two connected views, which can be compared over both the grouping fields, so as to match both province and maximum count: 1 CREATE VIEW v1 AS (SELECT b.province, COUNT(*) AS c, YEAR(dob) AS y FROM citizens a JOIN cities b ON a.city=b.code GROUP BY b.province,year(dob) ORDER BY b.province,c DESC) This view groups the citizens by province and birth year 2 CREATE VIEW v2 AS (SELECT province, MAX(c) AS c, y FROM v1 GROUP BY province) This view groups the citizens by province and maximum count 3 SELECT * FROM v1,v2 WHERE v1.province=v2.province AND v1.c=v2.c This query matches the two views so as to obtain the result Of course, any combination of fields can be used, especially since the values are the same in both v1 and v2.

149 MySQL

150 Appendix A: HTML summary <h.>, <p>, <span>, <div>, quotations, lists, <a> (links), <img> <p> <div> <blockquote> <h...> <ol> <ul> <dl> <dd> are BLOCK elements Most other tags (<img>) are INLINE <span> is the typical INLINE text element color background-color background-image : url(xxx); (no-repeat/repeat/repeat-x/repeat-y) border (ridge/groove/inset/outset/single/double) border-top, border-right, border-bottom, border-left border-color visibility height width margin margin-top, margin-right, margin-bottom, margin-left padding position (static/fixed) top, right, bottom, left font-size font-style (normal/italic) font-weight (normal, bold, bolder, lighter) text-align (left-right-center-justify) vertical-align (top-bottom-middle), (#, as in <span style="vertical-align:10px">) text-decoration (none/underline) white-space (normal/pre/pre-wrap) text-transform (lowercase, UPPERCASE, Capitalize) (allow for font-color-text attributes) hover first-letter first-line before (content) [ content : "text"; content : url(mario1.bmp) ] after (content) <table> <caption> <tr> <th> <td> label-textbox-password-textarea-checkbox-radio-select-button-submit-reset

Premier IDX Search. Site Administrator User Manual. September 16, 2018 Version 1.40

Premier IDX Search. Site Administrator User Manual. September 16, 2018 Version 1.40 Premier IDX Search Site Administrator User Manual September 16, 2018 Version 1.40 Table Of Contents Login to the Premier IDX Administration Section... 3 Start Page - Administration Overview... 4 Find A

More information

Quick Reference Library

Quick Reference Library Quick Reference Library CSS Quick Reference Copyright 1999-2002 by Infinite Software Solutions, Inc. All rights reserved. Trademark Information. Welcome to the DevGuru Cascading Style Sheets Quick Reference

More information

ShaDe for SketchUp. User's Guide All rights reserved For research use only (non-commercial use) Manuela Ruiz Montiel and Universidad de Málaga

ShaDe for SketchUp. User's Guide All rights reserved For research use only (non-commercial use) Manuela Ruiz Montiel and Universidad de Málaga ShaDe for SketchUp User's Guide All rights reserved For research use only (non-commercial use) Manuela Ruiz Montiel and Universidad de Málaga Author Manuela Ruiz Montiel Date September 5, 2012 Version

More information

729G26 Interaction Programming. Lecture 2 Jody Foo,

729G26 Interaction Programming. Lecture 2 Jody Foo, 729G26 Interaction Programming Lecture 2 Jody Foo, jody.foo@liu.se Lecture overview CSS syntax: selectors, properties and values CSS: borders and colors Using classes and id:s CSS Box model and layout

More information

4D Systems. Application Note: 4D-AN-M DGL Colour CONSTANTS. Document Date: 15 th December Document Revision: 1.0

4D Systems. Application Note: 4D-AN-M DGL Colour CONSTANTS. Document Date: 15 th December Document Revision: 1.0 4D Systems Application Note: 4DGL Colour CONSTANTS Document Date: 15 th December 2012 Document Revision: 1.0 2012 4D Systems www.4dsystems.com.au Page 1 of 6 Description This Application Note is dedicated

More information

Appendix A : srgb Colors

Appendix A : srgb Colors Appendix A : srgb Colors The SVG specification reads with regard to colours: All SVG colors are specified in the srgb color space. At a minimum, SVG user agents shall conform to the color behavior requirements

More information

Reading 2.2 Cascading Style Sheets

Reading 2.2 Cascading Style Sheets Reading 2.2 Cascading Style Sheets By Multiple authors, see citation after each section What is Cascading Style Sheets (CSS)? Cascading Style Sheets (CSS) is a style sheet language used for describing

More information

Color Coding Your Items. How to Dynamically Change the Color of Objects on Your Template WHITE PAPER

Color Coding Your Items. How to Dynamically Change the Color of Objects on Your Template WHITE PAPER Color Coding Your Items How to Dynamically Change the Color of Objects on Your Template WHITE PAPER Contents Overview 3 Using Layers to Change Object Color 4 How Layers Work in BarTender 4 Conditional

More information

Appendix D CSS Properties and Values

Appendix D CSS Properties and Values HTML Appendix D CSS Properties and Values This appendix provides a brief review of Cascading Style Sheets (CSS) concepts and terminology, and lists CSS level 1 and 2 properties and values supported by

More information

BIM222 Internet Programming

BIM222 Internet Programming BIM222 Internet Programming Week 7 Cascading Style Sheets (CSS) Adding Style to your Pages Part II March 20, 2018 Review: What is CSS? CSS stands for Cascading Style Sheets CSS describes how HTML elements

More information

CoDrone LINK. Communication Bluetooth Low Energy

CoDrone LINK. Communication Bluetooth Low Energy CoDrone LINK Communication Bluetooth Low Energy Updated in April 14th, 2016 Contents 1. Introduction 2. Data Link 3. Data Structure 1. Introduction CoDrone uses Bluetooth Low Energy (BLE) technology. DRONE_SERVICE

More information

A Proposal to Add 2D Graphics Rendering and Display to C++

A Proposal to Add 2D Graphics Rendering and Display to C++ Document Number: P0267R6 Date: 2017-07-30 Revises: P0267R5 Reply to: Michael B. McLaughlin mikebmcl@gmail.com Audience: Herb Sutter Microsoft Inc. hsutter@microsoft.com Jason Zink jzink_1@yahoo.com Guy

More information

<body bgcolor=" " fgcolor=" " link=" " vlink=" " alink=" "> These body attributes have now been deprecated, and should not be used in XHTML.

<body bgcolor=  fgcolor=  link=  vlink=  alink= > These body attributes have now been deprecated, and should not be used in XHTML. CSS Formatting Background When HTML became popular among users who were not scientists, the limited formatting offered by the built-in tags was not enough for users who wanted a more artistic layout. Netscape,

More information

A Proposal to Add 2D Graphics Rendering and Display to C++

A Proposal to Add 2D Graphics Rendering and Display to C++ Document Number: P0267R7 Date: 2018-02-10 Revises: P0267R6 Reply to: Michael B. McLaughlin mikebmcl@gmail.com Audience: Herb Sutter Microsoft Inc. hsutter@microsoft.com Jason Zink jzink_1@yahoo.com Guy

More information

SAS with Style: Creating your own ODS Style Template

SAS with Style: Creating your own ODS Style Template Paper 195-28 SAS with Style: Creating your own ODS Style Template Lauren Haworth, Genentech, Inc., South San Francisco, CA ABSTRACT Once you ve started using the Output Delivery System, you ll quickly

More information

Downloads: Google Chrome Browser (Free) - Adobe Brackets (Free) -

Downloads: Google Chrome Browser (Free) -   Adobe Brackets (Free) - Week One Tools The Basics: Windows - Notepad Mac - Text Edit Downloads: Google Chrome Browser (Free) - www.google.com/chrome/ Adobe Brackets (Free) - www.brackets.io Our work over the next 6 weeks will

More information

Programmazione Web a.a. 2017/2018 HTML5

Programmazione Web a.a. 2017/2018 HTML5 Programmazione Web a.a. 2017/2018 HTML5 PhD Ing.Antonino Raucea antonino.raucea@dieei.unict.it 1 Introduzione HTML HTML is the standard markup language for creating Web pages. HTML stands for Hyper Text

More information

AlbumEasy V3.9 Reference

AlbumEasy V3.9 Reference AlbumEasy V3.9 Reference Edited From The Albumeasy Help File By : Raymond King rayking@mweb.co.za http://www.thestampweb.com/ AlbumEasy V3.8 A Programme for Creating Custom Stamp Albums. INDEX 1. Workflow

More information

A Proposal to Add 2D Graphics Rendering and Display to C++

A Proposal to Add 2D Graphics Rendering and Display to C++ Document Number: P0267R5 Date: 2017-06-19 Revises: P0267R4 Reply to: Michael B. McLaughlin mikebmcl@gmail.com Audience: Herb Sutter Microsoft Inc. hsutter@microsoft.com Jason Zink jzink_1@yahoo.com Guy

More information

Chapter 3 Style Sheets: CSS

Chapter 3 Style Sheets: CSS WEB TECHNOLOGIES A COMPUTER SCIENCE PERSPECTIVE JEFFREY C. JACKSON Chapter 3 Style Sheets: CSS 1 Motivation HTML markup can be used to represent Semantics: h1 means that an element is a top-level heading

More information

ADDING CSS TO YOUR HTML DOCUMENT. A FEW CSS VALUES (colour, size and the box model)

ADDING CSS TO YOUR HTML DOCUMENT. A FEW CSS VALUES (colour, size and the box model) INTRO TO CSS RECAP HTML WHAT IS CSS ADDING CSS TO YOUR HTML DOCUMENT CSS IN THE DIRECTORY TREE CSS RULES A FEW CSS VALUES (colour, size and the box model) CSS SELECTORS SPECIFICITY WEEK 1 HTML In Week

More information

2. Write style rules for how you d like certain elements to look.

2. Write style rules for how you d like certain elements to look. CSS for presentation Cascading Style Sheet Orientation CSS Cascading Style Sheet is a language that allows the user to change the appearance or presentation of elements on the page: the size, style, and

More information

HTML/XML. HTML Continued Introduction to CSS

HTML/XML. HTML Continued Introduction to CSS HTML/XML HTML Continued Introduction to CSS Entities Special Characters Symbols such as +, -, %, and & are used frequently. Not all Web browsers display these symbols correctly. HTML uses a little computer

More information

Cascading Style Sheets Reference

Cascading Style Sheets Reference Background Cascading Style Sheets Reference http://www.w3schools.com/css/css_reference.asp Property Description Values IE F N W3C background background-attachment background-color background-image background-position

More information

Make a Website. A complex guide to building a website through continuing the fundamentals of HTML & CSS. Created by Michael Parekh 1

Make a Website. A complex guide to building a website through continuing the fundamentals of HTML & CSS. Created by Michael Parekh 1 Make a Website A complex guide to building a website through continuing the fundamentals of HTML & CSS. Created by Michael Parekh 1 Overview Course outcome: You'll build four simple websites using web

More information

HTML & CSS. SWE 432, Fall 2017 Design and Implementation of Software for the Web

HTML & CSS. SWE 432, Fall 2017 Design and Implementation of Software for the Web HTML & CSS SWE 432, Fall 2017 Design and Implementation of Software for the Web HTML: HyperText Markup Language LaToza Language for describing structure of a document Denotes hierarchy of elements What

More information

Tutorial 4: Creating Special Effects with CSS

Tutorial 4: Creating Special Effects with CSS Tutorial 4: Creating Special Effects with CSS College of Computing & Information Technology King Abdulaziz University CPCS-403 Internet Applications Programming Objectives Work with CSS selectors Create

More information

Introduction to Multimedia. MMP100 Spring 2016 thiserichagan.com/mmp100

Introduction to Multimedia. MMP100 Spring 2016 thiserichagan.com/mmp100 Introduction to Multimedia MMP100 Spring 2016 profehagan@gmail.com thiserichagan.com/mmp100 Troubleshooting Check your tags! Do you have a start AND end tags? Does everything match? Check your syntax!

More information

Pymaging Documentation

Pymaging Documentation Pymaging Documentation Release 0.0.0 Jonas Obrist February 22, 2016 Contents 1 About 1 2 User Documentation 3 2.1 Installation................................................ 3 2.1.1 Requirements..........................................

More information

Introduction to using HTML to design webpages

Introduction to using HTML to design webpages Introduction to using HTML to design webpages #HTML is the script that web pages are written in. It describes the content and structure of a web page so that a browser is able to interpret and render the

More information

CMPT 165 INTRODUCTION TO THE INTERNET AND THE WORLD WIDE WEB

CMPT 165 INTRODUCTION TO THE INTERNET AND THE WORLD WIDE WEB CMPT 165 INTRODUCTION TO THE INTERNET AND THE WORLD WIDE WEB Unit 3 Cascading Style Sheets (CSS) Slides based on course material SFU Icons their respective owners 1 Learning Objectives In this unit you

More information

Introduction to HTML & CSS. Instructor: Beck Johnson Week 2

Introduction to HTML & CSS. Instructor: Beck Johnson Week 2 Introduction to HTML & CSS Instructor: Beck Johnson Week 2 today Week One review and questions File organization CSS Box Model: margin and padding Background images and gradients with CSS Make a hero banner!

More information

Index. alt, 38, 57 class, 86, 88, 101, 107 href, 24, 51, 57 id, 86 88, 98 overview, 37. src, 37, 57. backend, WordPress, 146, 148

Index. alt, 38, 57 class, 86, 88, 101, 107 href, 24, 51, 57 id, 86 88, 98 overview, 37. src, 37, 57. backend, WordPress, 146, 148 Index Numbers & Symbols (angle brackets), in HTML, 47 : (colon), in CSS, 96 {} (curly brackets), in CSS, 75, 96. (dot), in CSS, 89, 102 # (hash mark), in CSS, 87 88, 99 % (percent) font size, in CSS,

More information

CSS Selectors. element selectors. .class selectors. #id selectors

CSS Selectors. element selectors. .class selectors. #id selectors CSS Selectors Patterns used to select elements to style. CSS selectors refer either to a class, an id, an HTML element, or some combination thereof, followed by a list of styling declarations. Selectors

More information

HTML TUTORIAL ONE. Understanding What XHTML is Not

HTML TUTORIAL ONE. Understanding What XHTML is Not HTML TUTORIAL ONE Defining Blended HTML, XHTML and CSS HTML: o Language used to create Web pages o Create code to describe structure of a Web page XHTM: o Variation of HTML o More strictly defines how

More information

HTML Summary. All of the following are containers. Structure. Italics Bold. Line Break. Horizontal Rule. Non-break (hard) space.

HTML Summary. All of the following are containers. Structure. Italics Bold. Line Break. Horizontal Rule. Non-break (hard) space. HTML Summary Structure All of the following are containers. Structure Contains the entire web page. Contains information

More information

Lecturer. Haider M. Habeeb. Second Year, First Course

Lecturer. Haider M. Habeeb. Second Year, First Course University of Babylon College of Information Technology Department of Information Networks Lecturer Haider M. Habeeb Second Year, First Course 2012-2013 HTML Attributes Attributes are another important

More information

Creating Web Pages with SeaMonkey Composer

Creating Web Pages with SeaMonkey Composer 1 of 26 6/13/2011 11:26 PM Creating Web Pages with SeaMonkey Composer SeaMonkey Composer lets you create your own web pages and publish them on the web. You don't have to know HTML to use Composer; it

More information

Table of Contents. MySource Matrix Content Types Manual

Table of Contents. MySource Matrix Content Types Manual Table of Contents Chapter 1 Introduction... 5 Chapter 2 WYSIWYG Editor... 6 Replace Text... 6 Select Snippet Keyword... 7 Insert Table and Table Properties... 8 Editing the Table...10 Editing a Cell...12

More information

Learning Objectives. Review html Learn to write a basic webpage in html Understand what the basic building blocks of html are

Learning Objectives. Review html Learn to write a basic webpage in html Understand what the basic building blocks of html are HTML CSCI311 Learning Objectives Review html Learn to write a basic webpage in html Understand what the basic building blocks of html are HTML: Hypertext Markup Language HTML5 is new standard that replaces

More information

**Method 3** By attaching a style sheet to your web page, and then placing all your styles in that new style sheet.

**Method 3** By attaching a style sheet to your web page, and then placing all your styles in that new style sheet. CSS Tutorial Part 1: Introduction: CSS adds style to tags in your html page. With HTML you told the browser what things were (e.g., this is a paragraph). Now you are telling the browser how things look

More information

Web Design and Development Tutorial 03

Web Design and Development Tutorial 03 Table of Contents Web Design & Development - Tutorial 03... 2 Using and Applying CSS to XHTML... 2 Conventions... 2 What you need for this tutorial... 2 Common Terminology... 3 Parent / Child Elements...

More information

HTML and CSS a further introduction

HTML and CSS a further introduction HTML and CSS a further introduction By now you should be familiar with HTML and CSS and what they are, HTML dictates the structure of a page, CSS dictates how it looks. This tutorial will teach you a few

More information

Cascade Stylesheets (CSS)

Cascade Stylesheets (CSS) Previous versions: David Benavides and Amador Durán Toro (noviembre 2006) Last revision: Manuel Resinas (october 2007) Tiempo: 2h escuela técnica superior de ingeniería informática Departamento de Lenguajes

More information

CSS. https://developer.mozilla.org/en-us/docs/web/css

CSS. https://developer.mozilla.org/en-us/docs/web/css CSS https://developer.mozilla.org/en-us/docs/web/css http://www.w3schools.com/css/default.asp Cascading Style Sheets Specifying visual style and layout for an HTML document HTML elements inherit CSS properties

More information

To link to an external stylesheet, the link element is placed within the head of the html page:

To link to an external stylesheet, the link element is placed within the head of the html page: CSS Basics An external style sheet is simply a text file (use BBEdit or Textwrangler) containing style rules, saved with the.css extension. It s best practice to keep style sheets for a site grouped within

More information

INTRODUCTION TO HTML5! HTML5 Page Structure!

INTRODUCTION TO HTML5! HTML5 Page Structure! INTRODUCTION TO HTML5! HTML5 Page Structure! What is HTML5? HTML5 will be the new standard for HTML, XHTML, and the HTML DOM. The previous version of HTML came in 1999. The web has changed a lot since

More information

Review Question 1. Which tag is used to create a link to another page? 1. <p> 2. <li> 3. <a> 4. <em>

Review Question 1. Which tag is used to create a link to another page? 1. <p> 2. <li> 3. <a> 4. <em> Introduction to CSS Review Question 1 Which tag is used to create a link to another page? 1. 2. 3. 4. Review Question 1 Which tag is used to create a link to another page? 1. 2.

More information

Assignments (4) Assessment as per Schedule (2)

Assignments (4) Assessment as per Schedule (2) Specification (6) Readability (4) Assignments (4) Assessment as per Schedule (2) Oral (4) Total (20) Sign of Faculty Assignment No. 02 Date of Performance:. Title: To apply various CSS properties like

More information

CMPT 165: More CSS Basics

CMPT 165: More CSS Basics CMPT 165: More CSS Basics Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University October 14, 2011 1 The Favorites Icon The favorites icon (favicon) is the small icon you see

More information

CSC 121 Computers and Scientific Thinking

CSC 121 Computers and Scientific Thinking CSC 121 Computers and Scientific Thinking Fall 2005 HTML and Web Pages 1 HTML & Web Pages recall: a Web page is a text document that contains additional formatting information in the HyperText Markup Language

More information

Cascading Style Sheet Quick Reference

Cascading Style Sheet Quick Reference Computer Technology 8/9 Cascading Style Sheet Quick Reference Properties Properties are listed in alphabetical order. Each property has examples of possible values. Properties are not listed if they are

More information

CSS Styles Quick Reference Guide

CSS Styles Quick Reference Guide Table 1: CSS Font and Text Properties Font & Text Properties Example(s) font-family Font or typeface font-family: Tahoma font-size Size of the font font-size: 12pt font-weight Normal or bold font-weight:

More information

CSS Cascading Style Sheets

CSS Cascading Style Sheets CSS Cascading Style Sheets site root index.html about.html services.html stylesheet.css images boris.jpg Types of CSS External Internal Inline External CSS An external style sheet is a text document with

More information

Tutorial 3: Working with Cascading Style Sheets

Tutorial 3: Working with Cascading Style Sheets Tutorial 3: Working with Cascading Style Sheets College of Computing & Information Technology King Abdulaziz University CPCS-665 Internet Technology Objectives Review the history and concepts of CSS Explore

More information

Creating Online Content for Pocket PC. Pocket Internet Explorer HTML Element Reference

Creating Online Content for Pocket PC. Pocket Internet Explorer HTML Element Reference Seite 1 von 120 Creating Online Content for Pocket PC Pocket Internet Explorer HTML Element Reference This reference specifies the HTML elements that are supported for Microsoft Windows Powered Pocket

More information

Markup Language SGML: Standard Generalized Markup Language. HyperText Markup Language (HTML) extensible Markup Language (XML) TeX LaTeX

Markup Language SGML: Standard Generalized Markup Language. HyperText Markup Language (HTML) extensible Markup Language (XML) TeX LaTeX HTML 1 Markup Languages A Markup Language is a computer language in which data and instructions describing the structure and formatting of the data are embedded in the same file. The term derives from

More information

recall: a Web page is a text document that contains additional formatting information in the HyperText Markup Language (HTML)

recall: a Web page is a text document that contains additional formatting information in the HyperText Markup Language (HTML) HTML & Web Pages recall: a Web page is a text document that contains additional formatting information in the HyperText Markup Language (HTML) HTML specifies formatting within a page using tags in its

More information

ID1354 Internet Applications

ID1354 Internet Applications ID1354 Internet Applications CSS Leif Lindbäck, Nima Dokoohaki leifl@kth.se, nimad@kth.se SCS/ICT/KTH What is CSS? - Cascading Style Sheets, CSS provide the means to control and change presentation of

More information

Basics of Web Design, 3 rd Edition Instructor Materials Chapter 2 Test Bank

Basics of Web Design, 3 rd Edition Instructor Materials Chapter 2 Test Bank Multiple Choice. Choose the best answer. 1. What element is used to configure a new paragraph? a. new b. paragraph c. p d. div 2. What element is used to create the largest heading? a. h1 b. h9 c. head

More information

Methods for configuring Cascading Style Sheets. Applying style to element name selectors. Style Rule Basics. CMPT 165: Cascading Style Sheets

Methods for configuring Cascading Style Sheets. Applying style to element name selectors. Style Rule Basics. CMPT 165: Cascading Style Sheets CMPT 165: Cascading Style Sheets Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University October 7, 2011 Methods for configuring Cascading Style Sheets There are 4 method to

More information

Dreamweaver Basics. Planning your website Organize site structure Plan site design & navigation Gather your assets

Dreamweaver Basics. Planning your website Organize site structure Plan site design & navigation Gather your assets Dreamweaver Basics Planning your website Organize site structure Plan site design & navigation Gather your assets Creating your website Dreamweaver workspace Define a site Create a web page Linking Manually

More information

Introduction to Web Design CSS Reference

Introduction to Web Design CSS Reference Inline Style Syntax: Introduction to Web Design CSS Reference Example: text Internal Style Sheet Syntax: selector {property: value; Example:

More information

Introduction to Web Design CSS Reference

Introduction to Web Design CSS Reference Inline Style Syntax: Introduction to Web Design CSS Reference Example: text Internal Style Sheet Syntax: selector {property: value; Example:

More information

By Ryan Stevenson. Guidebook #2 HTML

By Ryan Stevenson. Guidebook #2 HTML By Ryan Stevenson Guidebook #2 HTML Table of Contents 1. HTML Terminology & Links 2. HTML Image Tags 3. HTML Lists 4. Text Styling 5. Inline & Block Elements 6. HTML Tables 7. HTML Forms HTML Terminology

More information

Web Designing HTML5 NOTES

Web Designing HTML5 NOTES Web Designing HTML5 NOTES HTML Introduction What is HTML? HTML is the standard markup language for creating Web pages. HTML stands for Hyper Text Markup Language HTML describes the structure of Web pages

More information

HTML. Hypertext Markup Language. Code used to create web pages

HTML. Hypertext Markup Language. Code used to create web pages Chapter 4 Web 135 HTML Hypertext Markup Language Code used to create web pages HTML Tags Two angle brackets For example: calhoun High Tells web browser ho to display page contents Enter with

More information

CSS Tutorial Part 1: Introduction: A. Adding Style to a Web Page (3 options):

CSS Tutorial Part 1: Introduction: A. Adding Style to a Web Page (3 options): CSS Tutorial Part 1: Introduction: CSS adds style to tags in your html page. With HTML you told the browser what things were (e.g., this is a paragraph). Now you are telling the browser how things look

More information

Lesson 1 HTML Basics. The Creative Computer Lab. creativecomputerlab.com

Lesson 1 HTML Basics. The Creative Computer Lab. creativecomputerlab.com Lesson 1 HTML Basics The Creative Computer Lab creativecomputerlab.com What we are going to do today Become familiar with web development tools Build our own web page from scratch! Learn where to find

More information

The Benefits of CSS. Less work: Change look of the whole site with one edit

The Benefits of CSS. Less work: Change look of the whole site with one edit 11 INTRODUCING CSS OVERVIEW The benefits of CSS Inheritance Understanding document structure Writing style rules Attaching styles to the HTML document The cascade The box model CSS units of measurement

More information

COSC 2206 Internet Tools. CSS Cascading Style Sheets

COSC 2206 Internet Tools. CSS Cascading Style Sheets COSC 2206 Internet Tools CSS Cascading Style Sheets 1 W3C CSS Reference The official reference is here www.w3.org/style/css/ 2 W3C CSS Validator You can upload a CSS file and the validator will check it

More information

As we design and build out our HTML pages, there are some basics that we may follow for each page, site, and application.

As we design and build out our HTML pages, there are some basics that we may follow for each page, site, and application. Extra notes - Client-side Design and Development Dr Nick Hayward HTML - Basics A brief introduction to some of the basics of HTML. Contents Intro element add some metadata define a base address

More information

Client-Side Web Technologies. CSS Part II

Client-Side Web Technologies. CSS Part II Client-Side Web Technologies CSS Part II Topics Box model and related properties Visual formatting model and related properties The CSS Box Model Describes the rectangular boxes generated for elements

More information

HTML and CSS COURSE SYLLABUS

HTML and CSS COURSE SYLLABUS HTML and CSS COURSE SYLLABUS Overview: HTML and CSS go hand in hand for developing flexible, attractively and user friendly websites. HTML (Hyper Text Markup Language) is used to show content on the page

More information

CSS مفاهیم ساختار و اصول استفاده و به کارگیری

CSS مفاهیم ساختار و اصول استفاده و به کارگیری CSS مفاهیم ساختار و اصول استفاده و به کارگیری Cascading Style Sheets A Cascading Style Sheet (CSS) describes the appearance of an HTML page in a separate document : مسایای استفاده از CSS It lets you separate

More information

A Balanced Introduction to Computer Science, 3/E

A Balanced Introduction to Computer Science, 3/E A Balanced Introduction to Computer Science, 3/E David Reed, Creighton University 2011 Pearson Prentice Hall ISBN 978-0-13-216675-1 Chapter 2 HTML and Web Pages 1 HTML & Web Pages recall: a Web page is

More information

Dreamweaver CS3 Lab 2

Dreamweaver CS3 Lab 2 Dreamweaver CS3 Lab 2 Using an External Style Sheet in Dreamweaver Creating the site definition First, we'll set up the site and define it so that Dreamweaver understands the site structure for your project.

More information

APPLIED COMPUTING 1P01 Fluency with Technology

APPLIED COMPUTING 1P01 Fluency with Technology APPLIED COMPUTING 1P01 Fluency with Technology Cascading Style Sheets (CSS) APCO/IASC 1P01 Brock University Brock University (APCO/IASC 1P01) Cascading Style Sheets (CSS) 1 / 39 HTML Remember web pages?

More information

CSS. Lecture 16 COMPSCI 111/111G SS 2018

CSS. Lecture 16 COMPSCI 111/111G SS 2018 CSS Lecture 16 COMPSCI 111/111G SS 2018 No CSS Styles A style changes the way the HTML code is displayed Same page displayed using different styles http://csszengarden.com Same page with a style sheet

More information

CSS: Cascading Style Sheets

CSS: Cascading Style Sheets What are Style Sheets CSS: Cascading Style Sheets Representation and Management of Data on the Internet, CS Department, Hebrew University, 2007 A style sheet is a mechanism that allows to specify how HTML

More information

Cascading Style Sheets

Cascading Style Sheets 4 TVEZEWXYHMNR LSTVSKVEQY-RJSVQEXMOENITSHTSVSZ RETVSNIOXIQ RERGSZER Q^)ZVSTWO LSWSGM PR LSJSRHYEVS^TS XYLPEZR LSQ WXE4VEL] 4VELE)9-RZIWXYNIQIHSZE% FYHSYGRSWXM CSS Cascading Style Sheets Lukáš Bařinka barinkl@fel.cvut.cz

More information

Study Guide 2 - HTML and CSS - Chap. 6,8,10,11,12 Name - Alexia Bernardo

Study Guide 2 - HTML and CSS - Chap. 6,8,10,11,12 Name - Alexia Bernardo Study Guide 2 - HTML and CSS - Chap. 6,8,10,11,12 Name - Alexia Bernardo Note: We skipped Study Guide 1. If you d like to review it, I place a copy here: https:// people.rit.edu/~nbbigm/studyguides/sg-1.docx

More information

COPYRIGHTED MATERIAL. Contents. Chapter 1: Creating Structured Documents 1

COPYRIGHTED MATERIAL. Contents. Chapter 1: Creating Structured Documents 1 59313ftoc.qxd:WroxPro 3/22/08 2:31 PM Page xi Introduction xxiii Chapter 1: Creating Structured Documents 1 A Web of Structured Documents 1 Introducing XHTML 2 Core Elements and Attributes 9 The

More information

FRONTPAGE STEP BY STEP GUIDE

FRONTPAGE STEP BY STEP GUIDE IGCSE ICT SECTION 15 WEB AUTHORING FRONTPAGE STEP BY STEP GUIDE Mark Nicholls ICT lounge P a g e 1 Contents Introduction to this unit.... Page 4 How to open FrontPage..... Page 4 The FrontPage Menu Bar...Page

More information

8a. Cascading Style Sheet

8a. Cascading Style Sheet INFS 2150 Introduction to Web Development 8a. Cascading Style Sheet 1 Objectives Concepts of cascading style sheets (CSS). 3 ways of using CSS: inline styles, embedded styles, and external style sheet.

More information

Parashar Technologies HTML Lecture Notes-4

Parashar Technologies HTML Lecture Notes-4 CSS Links Links can be styled in different ways. HTML Lecture Notes-4 Styling Links Links can be styled with any CSS property (e.g. color, font-family, background, etc.). a { color: #FF0000; In addition,

More information

GoSquared Equally Rounded Corners Equally Rounded Corners -webkit-border-radius -moz-border-radius border-radius Box Shadow Box Shadow -webkit-box-shadow x-offset, y-offset, blur, color Webkit Firefox

More information

CSS: The Basics CISC 282 September 20, 2014

CSS: The Basics CISC 282 September 20, 2014 CSS: The Basics CISC 282 September 20, 2014 Style Sheets System for defining a document's style Used in many contexts Desktop publishing Markup languages Cascading Style Sheets (CSS) Style sheets for HTML

More information

It is possible to create webpages without knowing anything about the HTML source behind the page.

It is possible to create webpages without knowing anything about the HTML source behind the page. What is HTML? HTML is the standard markup language for creating Web pages. HTML is a fairly simple language made up of elements, which can be applied to pieces of text to give them different meaning in

More information

Welcome Please sit on alternating rows. powered by lucid & no.dots.nl/student

Welcome Please sit on alternating rows. powered by lucid & no.dots.nl/student Welcome Please sit on alternating rows powered by lucid & no.dots.nl/student HTML && CSS Workshop Day Day two, November January 276 powered by lucid & no.dots.nl/student About the Workshop Day two: CSS

More information

Web Design and Implementation

Web Design and Implementation Study Guide 3 - HTML and CSS - Chap. 13-15 Name: Alexia Bernardo Due: Start of class - first day of week 5 Your HTML files must be zipped and handed in to the Study Guide 3 dropbox. Chapter 13 - Boxes

More information

3.1 Introduction. 3.2 Levels of Style Sheets. - HTML is primarily concerned with content, rather than style. - There are three levels of style sheets

3.1 Introduction. 3.2 Levels of Style Sheets. - HTML is primarily concerned with content, rather than style. - There are three levels of style sheets 3.1 Introduction - HTML is primarily concerned with content, rather than style - However, tags have presentation properties, for which browsers have default values - The CSS1 cascading style sheet specification

More information

CSS Lecture 16 COMPSCI 111/111G SS 2018

CSS Lecture 16 COMPSCI 111/111G SS 2018 No CSS CSS Lecture 16 COMPSCI 111/111G SS 2018 Styles Astyle changes the way the HTML code is displayed Same page displayed using different styles Same page with a style sheet body font-family: sans-serif;

More information

Text and Layout. Digital Multimedia, 2nd edition Nigel Chapman & Jenny Chapman Chapter 11. This presentation 2004, MacAvon Media Productions

Text and Layout. Digital Multimedia, 2nd edition Nigel Chapman & Jenny Chapman Chapter 11. This presentation 2004, MacAvon Media Productions Text and Layout Digital Multimedia, 2nd edition Nigel Chapman & Jenny Chapman Chapter 11 This presentation 344 345 Text in Graphics Maximum flexibility obtained by treating text as graphics and manipulating

More information

- The CSS1 specification was developed in CSSs provide the means to control and change presentation of HTML documents

- The CSS1 specification was developed in CSSs provide the means to control and change presentation of HTML documents 3.1 Introduction - The CSS1 specification was developed in 1996 - CSS2 was released in 1998 - CSS3 is on its way - CSSs provide the means to control and change presentation of HTML documents - CSS is not

More information

Web Site Design and Development Lecture 5

Web Site Design and Development Lecture 5 Web Site Design and Development Lecture 5 CS 0134 Fall 2018 Tues and Thurs 1:00 2:15PM CSS CSS stands for Cascading Style Sheets. These style sheets define the look and layout of your HTML elements. A

More information

Table Basics. The structure of an table

Table Basics. The structure of an table TABLE -FRAMESET Table Basics A table is a grid of rows and columns that intersect to form cells. Two different types of cells exist: Table cell that contains data, is created with the A cell that

More information

Module 2 (VII): CSS [Part 4]

Module 2 (VII): CSS [Part 4] INTERNET & WEB APPLICATION DEVELOPMENT SWE 444 Fall Semester 2008-2009 (081) Module 2 (VII): CSS [Part 4] Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

More information

CS7026 CSS3. CSS3 Graphics Effects

CS7026 CSS3. CSS3 Graphics Effects CS7026 CSS3 CSS3 Graphics Effects What You ll Learn We ll create the appearance of speech bubbles without using any images, just these pieces of pure CSS: The word-wrap property to contain overflowing

More information

Dreamweaver Tutorial #2

Dreamweaver Tutorial #2 Dreamweaver Tutorial #2 My web page II In this tutorial you will learn: how to use more advanced features for your web pages in Dreamweaver what Cascading Style Sheets (CSS) are and how to use these in

More information