You are on page 1of 79

University of Zimbabwe Computer Science Department

Compiled By Zanamwe N

@2012

Page 1 of 79

Basics of a Web Page and Web Site Design A Website should ideally incorporate: Information about the entity that it has been built for Text, Graphics, Photo and Multimedia as or when required Simplicity in presenting the matter A layout that facilitates easy access to all the information Web development Tools
Compiled By Zanamwe N @2012 Page 2 of 79

The following are the tools that are required to build a web site: 1. Hardware for the Web server 2. An operating system 3. Web server software 4. A database management system if you want to develop a database driven site. 5. A scripting language(s) 6. Text editors Some of these choices will be dependent on the others. For example, not all operating systems will run on all hardware, not all scripting languages can connect to all databases, and so on. Text Editors There a lot of text editors which can be used in web development, however in this course we will use Dreamweaver CS4 Markup languages Markup languages are mainly required for performing typical formatting functions like: Setting margins for the Page Enhancing the look by changing Font Settings Adding special effects to the text and so on Evolution of Markup languages First introduced in 1980 Main objective was to ensure consistent display of documents It was named SGML or Standard Generalized Markup Language HTML has evolved from SGML Hyper-Text Mark-up Language (HTML) Is a client side scripting language Guidelines for writing HTML Documents Tags are enclosed within a Left Bracket < and a Right Bracket > These Brackets differentiate the Tags from the rest of the Text Opening Tag is denoted as <> and Closing Tag is denoted as </> Example of this : <h1> for beginning a heading and </h1> for closing it Tag names, though not case-sensitive should be written in lower case

Compiled By Zanamwe N

@2012

Page 3 of 79

1. The HEADER Section Contains information about the current document Includes information like the Title and the Keywords The text contained within the <TITLE> Tag is displayed on the Title Bar of Browser The <META> Tag contains the Keywords that describe the content of the Page <HTML> <HEAD> <META name=Author content=Zanamwe> <TITLE> University of Zimbabwe </TITLE> </HEAD> </HTML>

What goes between the HEAD tags <HEAD> <TITLE>HTML tags Basics - Web Page Help</TITLE> <META NAME="Description" CONTENT="Web page help, HTML help and information, links to help and information> <META NAME="KeyWords" CONTENT="help, how-to, HTML, web page help, HTML help."> <META NAME="Author" CONTENT="Roxanne M. Flanagan"> </HEAD> 2. The BODY Section Contains the matter that is to be displayed on the Page
Compiled By Zanamwe N @2012 Page 4 of 79

Enclosed within the <BODY> and </BODY> Tags <HTML> <HEAD> <META name=Generator content=PHP <TITLE> My Home Page </TITLE> </HEAD> <BODY> <H1> This is the First Heading </H1> <P> This Page is about HTML </P> </BODY> </HTML> <BODY TEXT="#000000" BGColor #CAD7AA" LINK="#000000" ALINK="#000040" VLINK="#FF0000" BACKGROUND="ImageName.jpg"> The <DIV> tag Used for applying Alignment and Style characteristics to only a section of the Document <HTML> <HEAD></HEAD> <BODY> <DIV ALIGN=RIGHT> <H1>Aligning a block of text to the Right</H1> </DIV> <DIV ALIGN=CENTER> <H1>This is how you center-align the Text</H1> </DIV> </BODY> </HTML> Horizontal line (HR) It can be added to a HTML document using the <HR> tag The Syntax is as below : <BODY> <HR> Paragraph Specification <HR> </BODY> Horizontal line - Attributes Width: The Width of the Line can be specified in terms of Percentage of the Page Width Size: The Thickness of the Line can be specified in terms of Pixels IMG tag
Compiled By Zanamwe N @2012 Page 5 of 79

Images play a major role in enhancing the Look of a page The Look on its part, attracts the users to visit and explore the Page Images put into Web pages are called Inline Images Images are mainly used as Buttons, Bullets, Photographs, and Banners etc. Most common formats are JPEG and GIF Images for a Page should be in the same Folder as the HTML document The <IMG> Tag is used to incorporate an Image into the document

IMG tag - attributes SRC: Used to specify the name of the Image/ Places an image within your document, review relative vs. absolute links. image attributes <IMG SRC=IMAGE1.GIF> BORDER: This attribute adds a Border around the Image <IMG SRC=IMAGE1.GIF ALIGN=MIDDLE BORDER=2> img src="filename">---Places an image within your document, review relative vs. absolute links. image attributes align=top, middle, bottom---align text with picture's top, middle, or bottom eg. <IMG SRC=IMAGE1.GIF ALIGN=MIDDLE> align=left, right---place picture on left or right and wrap text around it width, height=---in pixels or percentage, dimensions of picture can be altered (be careful with the ratio if using pixels) alt=---description of the picture so that text-only browsers know what it is border=---in pixels, border around the picture vspace, hspace=---in pixels, empty space around picture

FORMATTING: Indentation There is no standard way to indent the first line of a paragraph. Style sheets may provide a way to do that in the future, but, then you'd also have to wait until a majority of browsers could "view" style sheets before it's a good idea to use them. However, the special character [ &nbsp; ] (non-breaking space) forces a space break, and can be used when you really, really, really, want to force a web browser to show: extra blank space. Like this.
Compiled By Zanamwe N @2012 Page 6 of 79

Just use as many &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; as you need, to create the effect you want.

Marquee tag The marquee tag is a non-standard HTML mark-up element type which causes text to scroll up, down, left or right. Attributes Align: Uses the same syntax as the img tag. Behavior: Allows the user to set the behavior of the marquee to one of three different types: o Scroll - DEFAULT. Scrolls the text from right-to-left, and restarts at the right side of the marquee when it has reached the left side. Text disappears when looping finishes. o Slide - Same as Scroll except that the text stays there after the loop(s) if a loop(s) is set. o Alternate - Text 'bounces' from the left side of the box to the right side. Loops are counted by each time it reaches the other end; a loop of 1 would be the same as Slide. <marquee behavior="alternate">This text will bounce from left to right</marquee> Bgcolor: Sets the background color of the marquee. <marquee bgcolor="blue">This marquee's background color will be blue.</marquee> Direction: Sets the direction of the marquee box to either left-to-right, right-to-left, upto-down and down-to-up. Later browsers added support for a movie credit style bottom-up and top-down values. <marquee direction="right">This text will scroll from left to right.</marquee> Width: This sets how wide the marquee should be. <marquee width="100px">This marquee is only a hundred pixels wide!</marquee> Loop: This sets how many times the marquee should 'Loop' its text. <marquee loop="2">You will only see this text twice before it stops playing.</marquee> Scrollamount: This is how many pixels the text moves between 'frames', in pixels. <marquee scrollamount="10">This text will move ten pixels per 'frame'</marquee> Scrolldelay: This sets the amount of time, in milliseconds, between 'frames'. <marquee scrolldelay="1000">This would be so slow, you'd get no sense of animation.</marquee> <marquee scrolldelay="1">This would be so fast, you couldn't see it!</marquee> Ordered Lists Numbered <ol> <li>List item 1</li>
Compiled By Zanamwe N @2012 Page 7 of 79

<li>List item 2</li> <li>List item 3</li> <li>List item 4</li> </ol> Capital Letters <ol type="A"> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> <li>List item 4</li> </ol> Capital Letters Special Start <ol type="A" start="3"> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> <li>List item 4</li> </ol> Lowercase Roman Numerals <ol type="i"> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> <li>List item 4</li> </ol> Capital Roman Numerals <ol type="I"> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> <li>List item 4</li> </ol> Capital Roman Numerals Special Start <ol type="I" start="7"> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li>
Compiled By Zanamwe N @2012 Page 8 of 79

<li>List item 4</li> </ol> Unordered lists Example 1:<br> <br> <ul type=square> <li>List item 1</li> <li>List item 2</li> </ul> <br> Example 2:<br> <ul type="disc"> <li>List item 1</li> <li>List item 2</li> <ul type="circle"> <li>List item 3</li> <li>List item 4</li> </ul> </ul> Email Link <a href="mailto:nbzanamwe@gmail.com">Email Zanamwe</a> Creates: Email Zanamwe To make a combination of words AND a graphic a link ... <a href="mailto: nbzanamwe@gmail.com"> <img src="mailslot.gif" border=0 height=11 width=32>Email Zanamwe</a> Linking/Jumping to another page on YOUR site .... You don't need to put in the entire URL - just the html page name within your site. <a href="index.html">BACK TO THE FIRST PAGE</a> Linking/Jumping to someone else's page - you DO need the full URL .... <a href="http://www.google.com/"> Google</a>

HTML TABLES A table consists of a start tag <TABLE> and end tag </TABLE>. Between these, it is build up from a series of rows, which have a start tag <TR> and an end tag </TR>. Inside those, there are a
Compiled By Zanamwe N @2012 Page 9 of 79

number of columns, or cells, each with a start tag <TD> and end tag </TD>. The browser will not render the table until it has entirely loaded. The basic structure of a table might look like the following HTML fragment: <TABLE BORDER="1"> <TR> <TD>Row 1, Cell 1</TD> <TD>Row 1, Cell 2</TD> </TR> <TR> <TD>Row 2, Cell 1</TD> <TD>Row 2, Cell 2</TD> </TR> </TABLE> You will have noticed that I have introduced the BORDER attribute to be sure that the border is shown ("0" can be used to force the border to be invisible). You can control the width that the table is supposed to take up by using the WIDTH attribute. The value for the WIDTH attribute can be presented as a percentage of the available block or as a discrete value, in pixels. So, to create a table that has three columns, two of 25% and one of 50%, you would use HTML such as: <TABLE WIDTH="100%" border=1 > <TR> <TD WIDTH="25%"> </TD> <TD WIDTH="50%"> </TD> <TD WIDTH="25%"> </TD> </TR> </TABLE> Note that this example has specified that the entire table will take up 100% of the available width, and that each column width is specified in terms of the total width, and not the table width. I do not advise mixing pixel and percentage widths, because experience has shown that browsers do not always render tables in the same way. For example: <TABLE WIDTH="640"> <TR> <TD WIDTH="25%"> </TD> </TR> <TR> <TD WIDTH="50%"> </TD> </TR> <TR> <TD WIDTH="25%"> </TD>
Compiled By Zanamwe N @2012 Page 10 of 79

</TR> </TABLE> In this example, you might assume that the browser is clever enough to spot that you want the first column to measure 25% of the available 640 pixels that you have specified as the total width of the table. However, browsers might not always render this in the same way, and instead choose to use a value that is equal to 25% of the total document width rather than the 640 pixels that is use for the width of the table. Naturally, if you want to center the table, you can enclose it in <CENTER> and </CENTER> tags. This is a common approach for a newsletter style Web page, where you would like the content to appear in the center, in columns divided (like a blog) between the navigation, advertising content, and main article text. There are also a few tricks that you can use to add, for example, a row that spans the whole table width, regardless of the number of columns. This is very useful for creating headers (banners or navigation strips) or footers. For example, if you want to design something like this:

<TABLE WIDTH="600"> <TR> <TD COLSPAN="3" VALIGN="BOTTOM"> <CENTER> <H1>Banner Would Go Here</H1> [ Home | Latest Blog | About Us. . . ] </CENTER> </TD> </TR>
Compiled By Zanamwe N @2012 Page 11 of 79

<TR> <TD WIDTH="150" VALIGN="TOP"> &nbsp;&nbsp;Menu<BR/> &nbsp;&nbsp;&nbsp;Sub-menu<BR/> </TD> <TD WIDTH="300"> <!- - An empty paragraph to space it out, with a double line break - -> <BR /><BR /> <P>This is where all the glorious content would go, if we actually had any.</P> <P>Instead, weve put in this wonderful placeholder that is more original than the fake Latin that most people use instead of real text.</P> <!- - An empty paragraph to space it out, with a double line break - -> <BR /><BR /> </TD> <TD WIDTH="150"> <CENTER> Sample<BR/>Advertising<BR/>Here<BR/> </CENTER> </TD> </TR> <TR> <TD COLSPAN="3" VALIGN="BOTTOM"> <CENTER> <I>Copyright Statement, privacy statement, perhaps an additional menu here...</I> </CENTER> </TD> </TR> </TABLE> I have introduced a number of interesting attributes in this HTML fragment, all of which are vital in laying out the page properly. Firstly, the COLSPAN attribute allows you to create cells that span several columns. This is used in the header (banner and menu strip) as well as the footer (copyright statement). You can only span as many columns as are available in the table. If a larger number is used, the results are probably going to vary wildly between browsers. Next, I have used the VALIGN attribute to make sure that the vertical alignment is correct for the various cells that contain less content than the calculated cell height. The browser decides the cell height, and sometimes (as in the advertising pane) the content will not be as large (in
Compiled By Zanamwe N @2012 Page 12 of 79

height) as the entire column. The default behavior of browsers seems to be to center the content. So, to prevent this happening for content that you want to be aligned otherwise, you can specify a VALIGN value of: TOP, CENTER, BOTTOM Cells can also be aligned horizontally, using the ALIGN attribute, although it is deprecated. Instead, I have chosen to use the <CENTER> tag to center the content where appropriate. The CELLSPACING and CELLPADDING attributes are used in the <TABLE> tag to set the space between cells (spacing) and the inside margins (padding). You could have used this to introduce whitespace in the previous fragment if, for example, the left menu items began to creep towards the main content.

HTML Forms Forms are a vital tool for the webmaster to receive information from the web surfer, such as: their name, email address, credit card, etc. A form will take input from the viewer and depending on your needs; you may store that data into a file, place an order, gather user statistics, register the person to your web forum, or maybe subscribe them to your weekly newsletter. Text Fields Before we teach you how to make a complete form, let's start out with the basics of forms. Input fields are going to be the meat of your form's sandwich. The <input> has a few attributes that you should be aware of. type - Determines what kind of input field it will be. Possible choices are text, submit, and password. name - Assigns a name to the given field so that you may reference it later. size - Sets the horizontal width of the field. The unit of measurement is in blank spaces. maxlength - Dictates the maximum number of characters that can be entered. HTML Code: <form method="post" action="mailto:youremail@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"> </form>

Input Forms:

Compiled By Zanamwe N

@2012

Page 13 of 79

Name: Password:

ss ****

Do not use the password for security purposes. The data in the password field is not encrypted and is not secure in any way. HTML Form Email Now we will add the submit functionality to your form. Generally, the button should be the last item of your form and have its name attribute set to "Send" or "Submit". Name defines what the label of the button will be. Here is a list of important attributes of the submit: In addition to adding the submit button, we must also add a destination for this information and specify how we want it to travel to that place. Adding the following attributes to your <form> will do just this. method - We will only be using the post functionality of method, which sends the data without displaying any of the information to the visitor. action - Specifies the URL to send the data to. We will be sending our information to a fake email address. HTML Code: <form method="post" action="mailto:youremail@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"><br /> <input type="submit" value="Send"> </form> Email Forms: Name: Password:
Send

Simply change the email address to your own and you will have set up your first functional form! HTML Radio Buttons Radio buttons are a popular form of interaction. You may have seen them on quizzes, questionnaires, and other web sites that give the user a multiple choice question. Below are a couple attributes you should know that relate to the radio button.
Compiled By Zanamwe N @2012 Page 14 of 79

value - specifies what will be sent if the user chooses this radio button. Only one value will be sent for a given group of radio buttons (see name for more information). name - defines which set of radio buttons that it is a part of. Below we have 2 groups: shade and size. HTML Code: <form method="post" action="mailto:nzanamwe@science.uz.ac.zwm"> What kind of shirt are you wearing? <br /> Shade: <input type="radio" name="shade" value="dark">Dark <input type="radio" name="shade" value="light">Light <br /> Size: <input type="radio" name="size" value="small">Small <input type="radio" name="size" value="medium">Medium <input type="radio" name="size" value="large">Large <br /> <input type="submit" value="Email Myself"> </form> Radios: What kind of shirt are you wearing? Shade: Size:
Email Myself

Dark Small

Light Medium Large

HTML Drop Down Lists Drop down menus are created with the <select> and <option> tags. <select> is the list itself and each <option> is an available choice for the user. HTML Code: <form method="post" action="mailto:youremail@email.com"> College Degree? <select name="degree"> <option>Choose One</option> <option>Some High School</option> <option>High School </option> <option>Some College</option> <option>Bachelor's Degree</option> <option>Doctorate</option> <input type="submit" value="Email Yourself">
Compiled By Zanamwe N @2012 Page 15 of 79

</select> </form>

Drop Down Lists: College Degree?


Bachelor's Degree
Email Yourself

HTML Selection Forms Yet another type of form, a highlighted selection list. This form will post what the user highlights. Basically just another type of way to get input from the user. The size attribute selects how many options will be shown at once before needing to scroll, and the selected option tells the browser which choice to select by default. HTML Code: <form method="post" action="mailto:nbzanamwe@gmail.com"> Musical Taste <select multiple name="music" size="4"> <option value="emo" selected>Emo</option> <option value="metal/rock" >Metal/Rock</option> <option value="hiphop" >Hip Hop</option> <option value="ska" >Ska</option> <option value="jazz" >Jazz</option> <option value="country" >Country</option> <option value="classical" >Classical</option> <option value="alternative" >Alternative</option> <option value="oldies" >Oldies</option> <option value="techno" >Techno</option> </select> <input type="submit" value="Email Yourself"> </form> Selection Forms: Musical Taste
Emo Metal/Rock Hip Hop Ska

Email Yourself

Compiled By Zanamwe N

@2012

Page 16 of 79

CASCADING STYLE SHEETS (CSS) CSS are text files, or special text in a HTML file, which allows you to specify styles, formatting, and positioning of HTML objects. Cascading Multiple styles can overlap in order to specify a range of style from a whole web site down to a unique element. Which style gets applied pertains to the rules of CSS cascading logic. Style CSS deals specifically with the presentation domain of designing a web page. Style gives an item its distinctive look or feel. For text it could be what font is used, what color, size, or spacing. It also applies to other HTML objects such as links, images, backgrounds, margins and borders. Sheet Normally, CSS is a file separate from the HTML file linked to the HTML file through its <head> (exceptions apply). Benefits of using CSS Some of the benefits to using CSS are more consistency, better layout and visual design, plus easier HTML coding. Also you can do things with style sheets that could never be done before.

Consistency: This would apply for larger sites, and many different developers A siteglobal style sheet could be set up, which all pages would refer to. This sheet could include the look and feel you want for the complete site. Each page would maintain the same attributes throughout the site. The ability to change one item, on one page can change the same attribute on your whole site. Easier coding: No more elaborate tables, and complicated HTML. This will also greatly benefit the large multi-contributor web environments. The HTML code using style sheets is much simpler. The code reverts back to what it was in the early simple days. Just using header tags (H1, H2, ...), and paragraph tags with style sheets can produce a rich document, with the help of a SPAN and DIV tag here and there. Rich design and layout: Cascading Style Sheets bring professional layout and design control to HTML documents. Here's a brief listing of what you can do with style sheets that you could only do with an elaborate work around, or not at all. o exact positioning of elements o font control (size, color, family) o white space control, margins, leading o background control (placement, repeat, ...)
@2012 Page 17 of 79

Compiled By Zanamwe N

also, CSS reduce workload by centralizing commands for visual appearance instead of scattered throughout the HTML doc, reduce page download size. CSS Syntax A CSS rule has two main parts: a selector, and one or more declarations:

Another example:

Selectors The selector chooses elements to apply a declared style. The selector is normally the HTML element you want to style. Each declaration consists of a property and a value. The property is the style attribute you want to change. Each property has a value. CSS declarations always end with a semicolon, and declaration groups are surrounded by curly brackets Selector types: 1. Element Selectors: selects all elements of a specific type (<body>, <h1>, <p>, etc.) 2. Class Selectors : selects all elements that belong to a given class.
Compiled By Zanamwe N @2012 Page 18 of 79

3. ID Selectors: selects a single element thats been given a unique id. 4. Pseudo Selectors : combines a selector with a user activated state(:hover, :link, :visited) Examples of Element Selectors p {color:red; text-align:center;} To make the CSS more readable, you can put one declaration on each line, like this: Example 1 p { color:red; text-align:center; } Finds all HTML elements of type <p> and makes the text color red and align text to the center. Example 2 h1{ color: blue; } Finds all elements of type <h1> and makes the text color blue. CSS Comments Comments are used to explain your code, and may help you when you edit the source code at a later date. Comments are ignored by browsers. A CSS comment begins with "/*", and ends with "*/", like this: /*This is a comment*/ p { text-align:center; /*This is another comment*/ color:black; font-family:arial; } The id Selector The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute of the HTML element, and is defined with a "#". The style rule below will be applied to the element with id="para1":
Compiled By Zanamwe N @2012 Page 19 of 79

Example #para1 { text-align:center; color:red; } Do NOT start an ID name with a number! It will not work in Mozilla/Firefox. The class Selector The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements. This allows you to set a particular style for any HTML elements with the same class. The class selector uses the HTML class attribute, and is defined with a "." In the example below, all HTML elements with class="center" will be center-aligned: Example .center {text-align:center;}

You can also specify that only specific HTML elements should be affected by a class. In the example below, all p elements with class="center" will be center-aligned: Example p.center {text-align:center;}

Do NOT start a class name with a number! This is only supported in Internet Explorer. When a browser reads a style sheet, it will format the document according to it. Pseudo-Selectors Apply styles to a user activated state of an element. If used, must be declared in a specific order in the style sheet. General Purpose Pseudo-Selectors include: a:hover - Element with mouse over

Specific to hyperlinks (and/or buttons) a:active - A link or button that is currently being clicked on. a:link - A link that has NOT been visited yet. a: visited - A link that HAS been visited. Grouping Selectors
Compiled By Zanamwe N @2012 Page 20 of 79

Lets say you want to apply the same style to several different selectors. Dont repeat the style use a comma!! Syntax: sel1, sel2, sel3 (Remember the comma to group several different selectors) Example: h1, .legs, #snout{ font-size: 20pt; } Finds all elements of type <h1>, all elements with class=legs and the single element whose id = snout then makes their font-size 20pt.

Three Ways to Insert CSS There are three ways of inserting a style sheet: External style sheet Internal style sheet Inline style External Style Sheet An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> An external style sheet can be written in any text editor. The file should not contain any html tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is shown below: hr {color:sienna;} p {margin-left:20px;} body {background-image:url("images/back40.gif");} Do not leave spaces between the property value and the units! "margin-left:20 px" (instead of "margin-left:20px") will work in IE, but not in Firefox or Opera. Alternatively,
Compiled By Zanamwe N @2012 Page 21 of 79

<style type="text/css"> @import url(mystyle.css) </style> Internal Style Sheet An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section of an HTML page, by using the <style> tag, like this: <head> <style type="text/css"> hr {color:sienna;} p {margin-left:20px;} body {background-image:url("images/back40.gif");} </style> </head> Inline Styles An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method sparingly! To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left margin of a paragraph: <p style="color:sienna; margin-left:20px"> This is a paragraph. </p> CSS Text text formatting This text is styled with some of the text formatting properties. The heading uses the text-align, text-transform, and color properties. The paragraph is indented, aligned, and the space between characters is specified. The underline is removed from the "Try it yourself" link. Text Color The color property is used to set the color of the text. The color can be specified by: name - a color name, like "red" RGB - an RGB value, like "rgb(255,0,0)" Hex - a hex value, like "#ff0000" The default color for a page is defined in the body selector. Example body {color:blue;} h1 {color:#00ff00;} h2 {color:rgb(255,0,0);}

Compiled By Zanamwe N

@2012

Page 22 of 79

For W3C compliant CSS: If you define the color property, you must also define the backgroundcolor property. Text Alignment The text-align property is used to set the horizontal alignment of a text. Text can be centered, or aligned to the left or right, or justified. When text-align is set to "justify", each line is stretched so that every line has equal width, and the left and right margins are straight (like in magazines and newspapers). Example h1 {text-align:center;} p.date {text-align:right;} p.main {text-align:justify;}

Text Decoration The text-decoration property is used to set or remove decorations from text. The textdecoration property is mostly used to remove underlines from links for design purposes: Example a {text-decoration:none;}

It can also be used to decorate text: Example h1 {text-decoration:overline;} h2 {text-decoration:line-through;} h3 {text-decoration:underline;} h4 {text-decoration:blink;} It is not recommended to underline text that is not a link, as this often confuses users. Text Transformation The text-transform property is used to specify uppercase and lowercase letters in a text. It can be used to turn everything into uppercase or lowercase letters, or capitalize the first letter of each word. Example p.uppercase {text-transform:uppercase;} p.lowercase {text-transform:lowercase;} p.capitalize {text-transform:capitalize;}
Compiled By Zanamwe N @2012 Page 23 of 79

Text Indentation The text-indentation property is used to specify the indentation of the first line of a text. Example p {text-indent:50px;} CSS Font CSS Font Families In CSS, there are two types of font family names: generic family - a group of font families with a similar look (like "Serif" or "Monospace") font family - a specific font family (like "Times New Roman" or "Arial") Generic family Serif Sans-serif Monospace Font family Times New Roman Georgia Arial Verdana Courier New Lucida Console Description Serif fonts have small lines at the ends on some characters "Sans" means without - these fonts do not have the lines at the ends of characters All monospace characters have the same width

Font Family The font family of a text is set with the font-family property. The font-family property should hold several font names as a "fallback" system. If the browser does not support the first font, it tries the next font. Start with the font you want, and end with a generic family, to let the browser pick a similar font in the generic family, if no other fonts are available. Note: If the name of a font family is more than one word, it must be in quotation marks, like font-family: "Times New Roman". More than one font family is specified in a comma-separated list: Example p{font-family:"Times New Roman", Times, serif;}

Font Style The font-style property is mostly used to specify italic text. This property has three values: normal - The text is shown normally italic - The text is shown in italics oblique - The text is "leaning" (oblique is very similar to italic, but less supported) Example
Compiled By Zanamwe N @2012 Page 24 of 79

p.normal {font-style:normal;} p.italic {font-style:italic;} p.oblique {font-style:oblique;} CSS Links Links can be styled in different ways. Styling Links Links can be style with any CSS property (e.g. color, font-family, background-color). Special for links are that they can be styled differently depending on what state they are in. The four links states are: a:link - a normal, unvisited link a:visited - a link the user has visited a:hover - a link when the user mouses over it a:active - a link the moment it is clicked Example a:link {color:#FF0000;} /* unvisited link */ a:visited {color:#00FF00;} /* visited link */ a:hover {color:#FF00FF;} /* mouse over link */ a:active {color:#0000FF;} /* selected link */

When setting the style for several link states, there are some order rules: a:hover MUST come after a:link and a:visited a:active MUST come after a:hover Background Color The background-color property specifies the background color for links: Example a:link {background-color:#B2FF99;} a:visited {background-color:#FFFF85;} a:hover {background-color:#FF704D;} a:active {background-color:#FF704D;}

Compiled By Zanamwe N

@2012

Page 25 of 79

Joomla "Jumla" is the Swahili word for "all together" and was the inspiration for the name Joomla! The Joomla! project is one of the biggest content management systems worldwide, backed by a global community. Joomla! 2.5 is the sucessor of Joomla! 1.5. It is a long term release and represents the state of the art for the Joomla! project from January 2012 to July 2013. It lets you create unique websites in your own language. Even if you are not a specialist :-) How to Install Joomla 2.5 Manually (valid for Joomla 1.7/1.6 too) In order to complete the manual Joomla 2.5 installation, follow the steps listed below: Step 1. Create a MySQL database and add a user to it. Step 2. Download the archive file with the latest stable version of Joomla 2.5 from the official web site. Store it in a folder on your local computer and extract the archive. Step 3. Upload all the content from this local folder to the directory on the server where Joomla 2.5 will be stored. Step 4. Open the URL of the newly-uploaded Joomla script. If the content is uploaded in the main web directory, use http://localhost. In case you have uploaded it in a subdirectory, open http://localhost/joomla. Replace the domain and the directory names with the corresponding ones for your web site. Step 5. The Joomla installation page will be loaded:

There you can select the language for the installation. It will be valid only during the installation. Once completed Joomla will be switched back to English. In order to follow easier the next steps of the tutorial it is recommended that you choose "English". Step 6. On the next page Joomla will check whether the system requirements are met on the server. If one or more are not met, a corresponding message will be shown.

Compiled By Zanamwe N

@2012

Page 26 of 79

Step 7. After you make sure that all system requirements are met, proceed by clicking on the Next button from the top right menu. On the next page you should read and accept Joomla's license.

Again, click Next to continue. Step 8. Here you have to enter the MySQL details for the new Joomla 2.5 installation. Use the ones set in Step 1. In the following screenshot you can find example entries and explanations for these fields:

Compiled By Zanamwe N

@2012

Page 27 of 79

Step 9. Next, you can set your File Transfer Protocol (FTP) configuration. Keep the default settings and click Next to proceed.

Step 10. On the current page the main Joomla 2.5 configuration should be defined. Specify your site name, meta description and keywords, admin user, email and password.

Compiled By Zanamwe N

@2012

Page 28 of 79

Click on Next to proceed. Important: In this example we will not use the Install Sample Data feature because it may cause confusion and require time to remove all the data populated later. Step 11. In the last page of the installation wizard you will receive a confirmation that Joomla 2.5 has been successfully installed.

In order to access your new Joomla 2.5 web site you must delete the installation directory. This can be done with your FTP client. Well done! Your Joomla website is now installed.
Compiled By Zanamwe N @2012 Page 29 of 79

First steps in Joomla 2.5 (valid for Joomla 1.7 and 1.6 too) Once you have installed Joomla your first steps in administering the application should be logging in the admin area and creating your first pages. The simplest page in Joomla is called an article and that's where you put content such as text and images. This tutorial contains detailed instructions on the following topics: Logging in the Joomla admin area (valid for Joomla 1.7 and 1.6 too) First, in order to build your web site you will have to log into the administrator area. This can be achieved by opening the corresponding URL in your web browser: http://localhost/administrator Next, you have to enter the admin login details which have been set during the installation:

Creating articles in Joomla After entering the Joomla administrator area, you can check the featured articles (the ones that are included in the sample data or created by you) published on the front page through Content->Featured Articles.

Compiled By Zanamwe N

@2012

Page 30 of 79

You can edit them, create new ones, remove existing from the front page, delete, publish and unpublish articles. If you have installed the Sample Data, before adding new articles you can delete the sample ones. Select them and click on the Trash button. Then remove the menu links to the sample articles from Menus->Main Menu. After this you can add a new category from Content->Category Manager->Add New Category.

For example, you can put Test as the new category Title . The other options can be left blank or you can set their values as per your personal preferences. Click on the Save button to add your new category. Next, navigate to Content->Article Manager->Add New Article.

Compiled By Zanamwe N

@2012

Page 31 of 79

Only the Title field is mandatory. Enter the article title. You can also select your category from the corresponding drop-down menu. Change the article State to Published. If you want to show it on the front page, set the Featured value to Yes. Once you are ready with the settings you can proceed with the actual article content. Use the included text editor to type the article text, to include images or to directly edit the HTML code.

Under the text editor area you can set the permissions for the different user groups regarding your article. You can also adjust the settings in the Publishing Options , Article Options, Metadata Options menus.

Compiled By Zanamwe N

@2012

Page 32 of 79

You can hover your mouse pointer over the options labels and get a brief description of each one of them. Once you are ready, Save the article and check it on the front end. You can always edit the existing articles from the Joomla admin area->Content->Article Manager. How to Link Articles in Joomla 2.5 (valid for Joomla 1.7 and 1.6 too) In this part of our Joomla tutorial we will learn how to link articles to the web site menus. The tutorial is written for Joomla 2.5 but the same steps should be taken if you are using Joomla 1.7 or even 1.6. To make your articles and the corresponding pages accessible, you should set links to them. This can be completed by including these links in the web site menus. Open your Joomla admin area->Menus->Main Menu.

Click on the New button.


Compiled By Zanamwe N @2012 Page 33 of 79

Choose the Menu Item Type from the corresponding dialog. If you want to link a standard article pick the Single Article option.

Then enter the link title in the Menu Title field and select the corresponding article which will be linked through the Select Article functionality.

Save the changes and view the new menu item located on your frontend. How to publish your article on the home page? In order to make one of your articles the home page for the web site, navigate to the Joomla admin area->Menus->Main Menus. Select the article and click on the Home icon.

Compiled By Zanamwe N

@2012

Page 34 of 79

The change of the default home page article will be confirmed with the following message: One menu item successfully set to home If you want to remove the old home page article, select it and click on the Trash button. Contact Us page in Joomla 2.5 (valid for Joomla 1.7 and 1.6 too) Once you start your web site, you will probably want to allow your visitors to contact you. This way they will be able to provide important feedback to the webmaster. For this purpose you need to set a Contact Us page with an online contact form. Open your Joomla admin area and navigate to Components->Contacts->Categories .

Click on the New button and enter the details of your new contacts category. Only the Title value is required. You can also set the preferred configuration for the rest of the options.
Compiled By Zanamwe N @2012 Page 35 of 79

Save the changes and return to Components->Contacts->Contacts. Click on the New icon to begin the setup of your Contact us page.

Enter the required values in the corresponding fields. Review the options listed in the right part of the page and set them per your needs. In order to receive a copy of the contact form inquiries, enter a valid e-mail in the Contact Options list.

Compiled By Zanamwe N

@2012

Page 36 of 79

Save the Contact Us page setup and navigate to Menus->Main Menu to publish it. Click on Add New Menu Item.

Define the menu item type from the corresponding dialog.

Compiled By Zanamwe N

@2012

Page 37 of 79

Enter the Menu Title value and select the contact in the right part of the page by clicking on the Change Contact button. Review and set the other options that are not mandatory per your requirements. Save the new menu item and check it on the front end.

1. Downloading and upload templates Download templates as zipped files Go to extensions Then go to extensions manager and upload and install your templates 2. Changing Templates Go to extensions Then choose template manager and then click on the styles tab Then either check the check box before the template that u want and click on the make default option or just go to the default column and then click on the set default icon 3. Changing logo, site description, colour, title Go to extensions Then choose template manager and then click on the styles tab Under the styles column choose the style that you want by just clicking it or tick the check box before the style that you want and then click on the edit option A dialog box opens then under the advanced options section set the logo, color etc Click on the Save and close button OR

Compiled By Zanamwe N

@2012

Page 38 of 79

Go to C:\wamp\www\Test\templates\ Then choose the template that you are using eg: business4\images Look for a file named logo.png and rename it to something else eg logo1.png Copy the image that you want to use for your logo and place it in this folder and rename it to logo.png

OR Go to extensions Then choose template manager and then click on the templates tab Click on the template that you are using Under style sheets click on Edit css/template.css Then look for the following section: /* Logo Image ---*/ h1 .logo { width: 298px; background:url(../images/za.jpg) no-repeat;height:75px; display: block;} Then change the image name to the name of the desired image which must have been saved in the C:\wamp\www\Test\templates\: business4\images folder.

4. View module positions Go to extensions Then choose template manager and then click on the styles tab Then go to options and then choose the enabled button Click on the Save and close button Click on the view site link and append the following to the URL: Index.php?tp=1

5. Change the Footer Go to extensions Go to Template manager and then click on the Templates tab Click on the link for the template you are using Choose the edit main page template option (index.php) Go to the footer section and modify the footer OR Go to extensions Choose module manager Click on the new icon
@2012 Page 39 of 79

Compiled By Zanamwe N

Choose custom html Note that the position must be footer and can use an image for your footer or text or even both. OR Go to extensions Choose module manager Click on the new icon Choose footer Note that the position must be footer and it adds a default footer 6. Categories Web pages (articles) are classified into categories The procedure is to create categories first then create articles To create categories go to Content then choose Category Manager To create an article go to Content then choose Article Manager 7. Menus Menus creates a page and control layout of the page. They link to a new page and instruct the page how articles should appear. Create an article and link it by going to menus To create a menu from scratch, go to menus and then click menu manager and create a menu After creating your menu go to menus and choose the menu you would have created and add menu items Your menu will not appear on your website until you assign it a module position 8. Modules To create a module: go to Extensions then choose module manager click new choose menu specify the name of the menu and choose its position click the save and close button and view your site It is also possible to create custom HTML modules: go to Extensions then choose module manager click new Choose Custom HTML
@2012 Page 40 of 79

Compiled By Zanamwe N

9. Banner Rotators To add banner rotators: Go to components Create category Create clients- who is advertising Create a banner Create a module and give the banner a module position o go to Extensions then o choose module manager o choose banner o create a banner For rotation add more than one banner in a category and banner should not be sticky 10. Newsfeeds Go to components Choose Newsfeeds Create category Create news feed Go to menus and add a menu item and select the type of newsfeeds Go to module manager and create a module position and set to a position 11. Featured Articles Go to content Then choose featured article and create article 12. Contact us Form Go to components choose contact us create category and contact link it to a menu

PHP and MySQL Web Development What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a powerful server-side scripting language for creating dynamic and interactive
Compiled By Zanamwe N @2012 Page 41 of 79

websites. PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software (OSS) PHP is free to download and use PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP. PHP is perfectly suited for Web development and can be embedded directly into the HTML code. The PHP syntax is very similar to Perl and C. PHP is often used together with Apache (web server) on various operating systems. It also supports ISAPI and can be used with Microsoft's IIS on Windows

What is a PHP File? PHP files may contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml" What is MySQL? MySQL is a small database server MySQL is ideal for small and medium applications MySQL supports standard SQL MySQL compiles on a number of platforms MySQL is free to download and use

PHP + MySQL PHP combined with MySQL are cross-platform (means that you can develop in Windows and serve on a Unix platform) Why PHP? Some of PHPs main competitors are Perl, Microsoft Active Server Pages (ASP), Java Server Pages (JSP), and Allaire ColdFusion. In comparison to these products, PHP has many strengths, including the following: 1. High performance 2. Interfaces to many different database systems 3. Built-in libraries for many common Web tasks 4. Low cost 5. Ease of learning and use 6. Portability 7. Availability of source code Where to Start?
Compiled By Zanamwe N @2012 Page 42 of 79

Install an Apache server on a Windows or Linux machine Install PHP on a Windows or Linux machine Install MySQL on a Windows or Linux machine

Note: The easiest alternative is to just download a server that integrates the above three tools known as WampServer if you are using a windows operating system or LAMP if you are using a Linux box. Alternatively, you can download XAMPP which includes Perl in addition to the three tools. PHP Tag Styles There are actually four different styles of PHP tags we can use: 1. XML style <?php echo '<p>Order processed.</p>'; ?> It is the preferred tag style to use with PHP 3 and 4.The server administrator cannot turn it off, so you can guarantee it will be available on all servers. This style of tag can be used with XML (Extensible Markup Language) documents. 2. Short style <? echo '<p>Order processed.</p>'; ?> This style of tag is the simplest and follows the style of an SGML (Standard Generalized Markup Language) processing instruction. To use this type of tag which is the shortest to typeyou either need to enable short_tags in your config file, or compile PHP with short tags enabled. 3. SCRIPT style <script language='php'> echo '<p>Order processed.</p>'; </script> It can be used if you are using an HTML editor that gives you problems with the other tag styles. 4. ASP style <% echo '<p>Order processed.</p>'; %> This style of tag is the same as used in Active Server Pages (ASP). It can be used if you have enabled the ASP tags configuration setting. You might want to use this style of tag if you are using an editor that is geared toward ASP or if you already program in ASP. PHP Statements We tell the PHP interpreter what to do by having PHP statements between our opening and closing tags. In this example, we used only one type of statement: echo '<p>PHP is Funny.</p>'; Whitespace Browsers ignore white space in both HTML and PHP. It is recommended to use white space
Compiled By Zanamwe N @2012 Page 43 of 79

since it improves readability of the code. For example: echo 'Hypertext '; echo ' Preprocessor '; and echo 'Hypertext '; echo ' Preprocessor '; are equivalent but the first version is easier to read. Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another. There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World". Comments in PHP In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>

PHP Identifiers Identifiers are the names of variables, functions and classes. There are some simple rules about identifiers: 1. Identifiers can be of any length and can consist of letters, numbers, underscores, and dollar signs. However, you should be careful when using dollar signs in identifiers. 2. Identifiers cannot begin with a digit. 3. In PHP, identifiers are case sensitive. $name is not the same as $Name. Trying to use these interchangeably is a common programming error. Function names are an exception to this ruletheir names can be used in any case. 4. A variable can have the same name as a function. This is confusing however, and should be avoided. Also, you cannot create a function with the same name as another function name.

Compiled By Zanamwe N

@2012

Page 44 of 79

Data Types in PHP PHP supports the following data types: 1. IntegerUsed for whole numbers 2. DoubleUsed for real numbers 3. StringUsed for strings of characters 4. BooleanUsed for true or false values 5. ArrayUsed to store multiple data items of the same type (see Chapter 3) 6. ObjectUsed for storing instances of classes 7. NULL-used for variables that have not been given a value, unset, given the specific value NULL 8. Resource- used for storing results of built-in functions such as database functions PHP Variables Variables are used for storing values, such as numbers, strings or function results, so that they can be used many times in a script. All variables in PHP start with a $ sign symbol. Variables may contain strings, numbers, or arrays. Below, the PHP script assigns the string "Hello World" to a variable called $txt: <html> <body> <?php $txt="Hello World"; echo $txt; ?> </body> </html>

Concatenation Operator To concatenate two or more variables together, use the dot (.) operator: <html> <body> <?php $txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2 ; ?> </body> </html> The output of the script above will be: "Hello World 1234".
Compiled By Zanamwe N @2012 Page 45 of 79

Variable Naming Rules Rules for naming variables: The first character must be a letter or an underscore "_" A variable can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ ) A Variable containing more than one word should be separated with underscore ($my_string), or with capitalization ($myString) Type Strength PHP is a very weakly typed language in the sense that variables can hold more than one type of data and the variable type is determined by the value assigned to it. For example: If we create $total and $amount, their initial types are determined, as follows: $total = 0; $amount = 0.00; Because we assigned 0, an integer, to $total this is now an integer type variable. Similarly, $amount is now of type double. We could now add a line to our script as follows: $amount = 'PHP'; The variable $amount would then be of type string. Type Casting This concept is used to change the data type of variable to another data type. You simply put the temporary type in brackets in front of the variable you want to cast. For example, we could have declared the two variables above using a cast. $total = 10; $amount = (double)$total; The second line means Take the value stored in $total, interpret it as a double, and store it in $amount. The $amount variable will be of type double. The cast variable does not change types, so $total remains of type integer. Variable Variables Variable variables enable us to change the name of a variable dynamically. The way these work is to use the value of one variable as the name of another. For example, we could set $var = 'age'; We can then use $$var in place of $age. For example, we can set the value of $age: $$var = 24; This is exactly equivalent to $age = 24; PHP Constants A constant stores a value such as a variable, but its value is set once and then cannot be changed elsewhere in the script.
Compiled By Zanamwe N @2012 Page 46 of 79

You can define these constants using the define function: define('DAYS_IN_A_WEEK', 7); The convention is to express constants in uppercase. You can the print the value of the constant by saying: Echo 'DAYS_IN_A_WEEK; Note constant names are not preceded by a $ sign symbol. Scope of PHP Variables The term scope refers to the places within a script where a particular variable is visible. The four types of scope in PHP are as follows: 1. Built-in superglobal variables are visible everywhere within a script. 2. Global variables declared in a script are visible throughout that script, but not inside functions. 3. Variables used inside functions are local to the function. 4. Variables used inside functions that are declared as global refer to the global variable of the same name. PHP Superglobals $GLOBALS Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $_SERVER Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated). $_GET Variables provided to the script via HTTP GET. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated). $_POST Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated). $_COOKIE Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated). $_FILES Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information. $_ENV Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated). $_REQUEST
Compiled By Zanamwe N @2012 Page 47 of 79

Variables provided to the script via any user input mechanism, and which therefore cannot be trusted. Note: when running on the command line, this will not include the argv and argc entries; these are present in the $_SERVER array. $_SESSION Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session handling functions section for more information. PHP Forms A very powerful feature of PHP is the way it handles HTML forms! PHP Form Handling The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts. Look at the following example of an HTML form: <html> <body> <form action="welcome.php" method="POST"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> The example HTML page above contains two input fields and a submit button. When the user fills in this form and hits the submit button, the "welcome.php" file is called. The "welcome.php" file looks like this: <html> <body> Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old! </body> </html> A sample output of the above script may be: Welcome John. You are 28 years old! Here is how it works: The $_POST["name"] and $_POST["age"] variables are automatically set for you by PHP. The $_POST contains all POST data. Note: If the method attribute of the form is GET, then the form information will be set in $_GET instead of $_POST. PHP $_GET The $_GET variable in PHP are used to receive data from HTTP GET.
Compiled By Zanamwe N @2012 Page 48 of 79

The $_GET Variable The $_GET variable is an array of variables sent by HTTP GET. The HTTP GET method adds the variables to the URL of the current page. The names of the form fields are the ID keys in the $_GET array When using HTTP GET, variable values may not exceed 100 characters. Example <form action="welcome.php" method="GET"> Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> <input type="submit" /> </form> The URL of the new page could then be: www.w3schools.com/welcome.php?name=peter&age=37; Variables are marked with a question mark "?" in the URL. The welcome.php page would then have to use the $_GET variable to use the variables: Welcome <?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! Why use $_GET? When using the $_GET variable the variables are displayed to the user in the URL. So it should not be used to send passwords or sensitive information. However, because the variables are displayed in the URL, it is possible to bookmark or link to the new page. This can be very useful in some cases. The $_REQUEST Variable The $_REQUEST variable contains the contents of $_GET, $_POST, and $_COOKIE. $_REQUEST can be used to get the result from both HTTP GET and HTTP POST. Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!

PHP $_POST The $_POST variable in PHP are used to receive data from HTTP POST. The $_POST Variable The $_POST is an array of variables sent by HTTP POST. Unlike HTTP GET, variables sent with HTTP POST will not be seen by the user, and has no length limit. The names of the form fields are the keys in the $_POST array Example <form action="welcome.php" method="POST">
Compiled By Zanamwe N @2012 Page 49 of 79

Enter your name: <input type="text" name="name" /> Enter your age: <input type="text" name="age" /> <input type="submit" /> </form> The welcome.php page would then have to use the $_POST variable to use the variables: Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old! Why use $_POST? Variables sent with HTTP POST are not shown in the URL Variables have no length limit However, because the variables are not displayed in the URL, it is not possible to bookmark or link to the new page. The $_REQUEST Variable The $_REQUEST variable contains the contents of $_GET, $_POST, and $_COOKIE. $_REQUEST can be used to get the result from both HTTP GET and HTTP POST. Example Welcome <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old!

PHP Operators Operators are symbols that you can use to manipulate values and variables by performing an operation on them. Operands are arguments being operated upon Arithmetic Operators Operator Description + Addition * / % Subtraction Multiplication Division Modulus (division remainder)

Example $x=2 $x +2 $x =2 5-$x $x =4 $x *5 15/5 5/2 5%2 10%8 10%2 $x =5 $x ++


@2012

Result 4 3 20 3 2.5 1 2 0 $x =6
Page 50 of 79

++

Increment

Compiled By Zanamwe N

--

Decrement

$x =5 $x --

$x =4

Assignment Operators Operator Example = $x =$y += $x +=$y -= $x -=$y *= $x *=$y /= $x/=$y %= $x%=$y .= $x.= $y

Is The Same As $x =$y $x =$x +$y $x =$x -$y $x =$x *$y $x=$x/$y $x=$x%$y $x = $x.$y

Comparison Operators Operator Description == is equal to != or <> is not equal > is greater than < is less than >= is greater than or equal to <= is less than or equal to === Is identical to Logical Operators Operator Description && or and and || / or or ! not

Example 5==8 returns false 5!=8 returns true 5>8 returns false 5<8 returns true 5>=8 returns false 5<=8 returns true $a===$b

Example x=6 , y=3 : (x < 10 && y > 1) returns true x=6, y=3 :(x==5 || y==5) returns false x=6, y=3 : !(x==y) returns true

References The reference operator & (ampersand) can be used in conjunction with assignment. Normally when one variable is assigned to another, a copy is made of the first variable and stored elsewhere in memory. For example, $a = 5; $b = $a; These lines of code make a second copy of the value in $a and store it in $b. If we subsequently change the value of $a, $b will not change:
Compiled By Zanamwe N @2012 Page 51 of 79

$a = 7; // $b will still be 5 You can avoid making a copy by using the reference operator, &. For example, $a = 5; $b = &$a; $a = 7; // $a and $b are now both 7 Bitwise Operators The bitwise operators enable you to treat an integer as the series of bits used to represent it. They are rarely used in PHP. Operator & | ~ ^ << >> Name bitwise AND bitwise OR bitwise NOT bitwise XOR left shift right shift Use Result $a & $b Bits set in $a and $b are set in the result $a | $b Bits set in $a or $b are set in the result ~$a Bits set in $a are not set in the result and vice versa $a ^ $b Bits set in $a or $b but not in both are set in the result $a << $b Shifts $a left $b bits $a >> $b Shifts $a right $b bits

1. Testing Variable Status PHP has several ways to test the status of a variable. The first of these is isset(), which has the following prototype: bool isset(mixed var); This function takes a variable name as argument and returns true if it exists and false otherwise. You can wipe a variable out of existence by using its companion construct, unset(). This has the following prototype: void unset(mixed var); This gets rid of the variable it is passed and returns true. Finally there is empty().This checks to see if a variable exists and has a non-empty, non-zero value and returns true or false accordingly. It has the following prototype: boolean empty(mixed var); Lets look at an example using these. $x=10; echo isset($x);
Compiled By Zanamwe N @2012 Page 52 of 79

echo isset($y); echo empty($x); echo empty($y); The variable $x should return true from isset() whereas the variable $y does not exist, so it will generate a false result from isset() and a true result from empty(). 2. Re-interpreting Variables You can achieve the equivalent of casting a variable by calling a function. The three functions that can be useful for this are int intval(mixed var); float doubleval(mixed var); string strval(mixed var); Each of these accepts a variable as input and returns the variables value converted to the appropriate type. Break Break ends execution of the current for, foreach while, do..while or switch structure. Break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. $arr = array ('one', 'two', 'three', 'four', 'stop', 'five'); while (list (, $val) = each ($arr)) { if ($val == 'stop') { break; /* You could also write 'break 1;' here. */ } echo "$val<br>\n"; } /* Using the optional argument. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br>\n"; break 1; /* Exit only the switch. */ case 10: echo "At 10; quitting<br>\n"; break 2; /* Exit the switch and the while. */ default: break; } }
Compiled By Zanamwe N @2012 Page 53 of 79

Continue Continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the beginning of the next iteration. Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of. while (list ($key, $value) = each ($arr)) { if (!($key % 2)) { // skip odd members continue; } do_something_odd ($value); } $i = 0; while ($i++ < 5) { echo "Outer<br>\n"; while (1) { echo "&nbsp;&nbsp;Middle<br>\n"; while (1) { echo "&nbsp;&nbsp;Inner<br>\n"; continue 3; } echo "This never gets output.<br>\n"; } echo "Neither does this.<br>\n"; } Return If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file. If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in the configuration file, then that script file's execution is ended. Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required--in fact, it is more common to leave them out than to use them, although it doesn't matter one way or the other. Control Structures 1. Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
Compiled By Zanamwe N @2012 Page 54 of 79

if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true

The If...Else Statement If you want to execute some code if a condition is true and another code if a condition is false, use the if....else statement. Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html> If more than one line should be executed when a condition is true, the lines should be enclosed within curly braces: <html> <body> <?php $x=10; if ($x==10) { echo "Hello<br />"; echo "Good morning<br />"; } ?> </body> </html>
Compiled By Zanamwe N @2012 Page 55 of 79

The ElseIf Statement If you want to execute some code if one of several conditions are true use the If_Else statement with ElseIf Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html> PHP Switch Statement The Switch statement in PHP is used to perform one of several different actions based on one of several different conditions. The Switch Statement If you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code. Syntax switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2;
Compiled By Zanamwe N @2012 Page 56 of 79

break; default: code to be executed if expression is different from both label1 and label2; } Example This is how it works: A single expression (most often a variable) is evaluated once The value of the expression is compared with the values for each case in the structure If there is a match, the code associated with that case is executed After a code is executed, break is used to stop the code from running into the next case The default statement is used if none of the cases are true <html> <body> <?php $x=1; switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html>

PHP Looping Looping statements in PHP are used to execute the same block of code a specified number of times. Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to perform this. In PHP we have the following looping statements: while - loops through a block of code if and as long as a specified condition is true
Compiled By Zanamwe N @2012 Page 57 of 79

do...while - loops through a block of code once, and then repeats the loop as long as a special condition is true for - loops through a block of code a specified number of times foreach - loops through a block of code for each element in an array

The while Statement The while statement will execute a block of code if and as long as a condition is true. Syntax while (condition) code to be executed; Example The following example demonstrates a loop that will continue to run as long as the variable i is less than, or equal to 5. i will increase by 1 each time the loop runs: <html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> The do...while Statement The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true. Syntax do { code to be executed; } while (condition); Example The following example will increment the value of i at least once, and it will continue incrementing the variable i while it has a value of less than 5:
Compiled By Zanamwe N @2012 Page 58 of 79

<html> <body> <?php $i=0; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<5); ?> </body> </html> The for Statement The for statement is used when you know how many times you want to execute a statement or a list of statements. Syntax for (initialization; condition; increment) { code to be executed; } Note: The for statement has three parameters. The first parameter is for initializing variables, the second parameter holds the condition, and the third parameter contains any increments required to implement the loop. If more than one variable is included in either the initialization or the increment section, then they should be separated by commas. The condition must evaluate to true or false. Example The following example prints the text "Hello World!" five times: <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> </body> </html> The foreach Statement
Compiled By Zanamwe N @2012 Page 59 of 79

Loops over the array given by the parameter. On each loop, the value of the current element is assigned to $value and the array pointer is advanced by one - so on the next loop, you'll be looking at the next element. Syntax foreach (array as value) { code to be executed; } Example The following example demonstrates a loop that will print the values of the given array: <html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html> Formatting Strings Youll often need to tidy up user strings (typically from an HTML form interface) before you can use them. Trimming Strings: chop(), ltrim(), and trim() The first step in tidying up is to trim any excess whitespace from the string. Although this is never compulsory, it can be useful if you are going to store the string in a file or database, or if youre going to compare it to other strings. PHP provides three useful functions for this purpose. Well use the trim() function to tidy up our input data as follows: $name=trim($name); $email=trim($email); $feedback=trim($feedback); The trim() function strips whitespace from the start and end of a string, and returns the resulting string. The characters it strips by default are newlines and carriage returns (\n and \r), horizontal and vertical tabs (\t and \v), end of string characters (\0), and spaces. You can also pass it a second parameter containing a list of characters to strip instead of this default list. Depending on your particular purpose, you might like to use the ltrim() or chop() functions instead. They are both similar to trim(), taking the string in question as a parameter and returning the formatted string. The difference between these three is that trim() removes
Compiled By Zanamwe N @2012 Page 60 of 79

whitespace from the start and end of a string, ltrim() removes whitespace from the start (or left) only, and chop() removes whitespace from the end (or right) only. Formatting Strings for Presentation PHP has a set of functions that you can use to reformat a string in different ways. Using HTML Formatting: the nl2br() Function The nl2br() function takes a string as parameter and replaces all the newlines in it with the XHTML <br /> tag (or the HTML <br> tag in versions prior to 4.0.5).This is useful for echoing a long string to the browser. For example, we use this function to format the customers feedback in order to echo it back: <p>Your feedback (shown below) has been sent.</p> <p><? echo nl2br($mailcontent); ?> </p> Remember that HTML disregards plain whitespace, so if you dont filter this output through nl2br(), it will appear on a single line (except for newlines forced by the browser window). See example below.

Formatting a String for Printing So far, we have used the echo language construct to print strings to the browser. PHP also supports a print() construct, which does the same thing as echo, but returns a value (true or false, denoting success). Using PHPs nl2br() function improves the display of long strings within HTML. Both of these techniques print a string as is.You can apply some more sophisticated formatting using the functions printf() and sprintf().These work basically the same way, except that printf() prints a formatted string to the browser and sprintf()returns a formatted string. The prototypes for these functions are string sprintf (string format [, mixed args...]) void printf (string format [, mixed args...]) The first parameter passed to both these functions is a format string that describes the basic shape of the output with format codes instead of variables. The other parameters are variables that will be substituted in to the format string. For example, using echo, we used the variables we wanted to print inline, like this:
Compiled By Zanamwe N @2012 Page 61 of 79

echo "Total amount of order is $total."; To get the same effect with printf(), you would use printf ("Total amount of order is %s.", $total); The %s in the format string is called a conversion specification. This one means replace with a string. In this case, it will be replaced with $total interpreted as a string. If the value stored in $total was 12.4, both of these approaches will print it as 12.4. The advantage of printf() is that we can use a more useful conversion specification to specify that $total is actually a floating point number, and that it should have two decimal places after the decimal point, as follows: printf ("Total amount of order is %.2f", $total); You can have multiple conversion specifications in the format string. If you have n conversion specifications, you will usually have n arguments after the format string. Each conversion specification will be replaced by a reformatted argument in the order they are listed. For example, printf ("Total amount of order is %.2f (with shipping %.2f) ", $total, $total_shipping); Here, the first conversion specification will use the variable $total, and the second will use the variable $total_shipping. Each conversion specification follows the same format, which is %['padding_character][-][width][.precision]type All conversion specifications start with a % symbol. If you actually want to print a % symbol, you will need to use %%. The padding_character is optional. It will be used to pad your variable to the width you have specified. An example of this would be to add leading zeroes to a number like a counter. The - symbol is optional. It specifies that the data in the field will be left-justified, rather than right-justified, the default. The width specifier tells printf() how much room (in characters) to leave for the variable to be substituted in here. The precision specifier should begin with a decimal point. It should contain the number of places after the decimal point you would like displayed. The final part of the specification is a type code. A summary of these is shown below Conversion Specification Type Codes Type Meaning b Interpret as an integer and print as a binary number. c Interpret as an integer and print as a character. d Interpret as an integer and print as a decimal number. f Interpret as a double and print as a floating point number. o Interpret as an integer and print as an octal number. s Interpret as a string and print as a string. x Interpret as an integer and print as a hexadecimal number with lowercase letters for the digits a-f. X Interpret as an integer and print as a hexadecimal number with uppercase letters for
Compiled By Zanamwe N @2012 Page 62 of 79

the digits A-F. Changing the Case of a String You can also reformat the case of a string. For example, If we start with the string, $name =Zanamwe, we can change its case with several functions. The effect of these functions is summarized below. The first column shows the function name, the second describes its effect, the third shows how it would be applied to the string $name, and the last column shows what value would be returned from the function.

Function strtoupper() strtolower() ucfirst() ucwords()

Description Turns string to uppercase Turns string to lowercase Capitalizes first character of string if its alphabetic Capitalizes first character of each word in the string that begins with an alphabetic character

Use $name strtoupper($name) strtolower($name) ucfirst($name) ucwords($name)

Value Zanamwe ZANAMWE zanamwe Zanamwe Zanamwe

Using require() The following code is stored in a file named reusable.php: <?php echo 'Here is a very simple PHP statement.<br />'; ?> The following code is stored in a file called main.php: <?php echo 'This is the main file.<br />'; require( 'reusable.php' ); echo 'The script will end now.<br />'; ?> If you load reusable.php, it probably wont surprise you when Here is a very simple PHP statement. appears in your browser. If you load main.php, something a little more interesting happens. A file is needed to use a require() statement. In the preceding example, we are using the file named reusable.php. When we run our script, the require() statement require( 'reusable.php' );
Compiled By Zanamwe N @2012 Page 63 of 79

is replaced by the contents of the requested file, and the script is then executed. This means that when we load main.php, it runs as though the script were written as follows: <?php echo 'This is the main file.<br />'; echo 'Here is a very simple PHP statement.<br />'; echo 'The script will end now.<br />'; ?> When using require() you need to note the different ways that filename extensions and PHP tags are handled. Using include() The statements require() and include() are almost identical. The only difference between them is that when they fail, the require() construct will give a fatal error, while the include() construct will only give a warning. HOW WEB DATABASE ARCHITECTURES WORK 1. A users Web browser issues an HTTP request for a particular Web page. For example, the user might have requested a search for all the products being offered by a certain company, using an HTML form. The search results page is called product.php. 2. The Web server receives the request for product.php, retrieves the file, and passes it to the PHP engine for processing. 3. The PHP engine begins parsing the script. Inside the script is a command to connect to the database and execute a query (perform the search for products). PHP opens a connection to the MySQL server and sends on the appropriate query. 4. The MySQL server receives the database query, processes it, and sends the results a list of productsback to the PHP engine. 5. The PHP engine finishes running the script that will usually involve formatting the query results nicely in HTML. It then returns the resulting HTML to the Web server. 6. The Web server passes the HTML back to the browser, where the user can see the list of products she requested. The Basic Steps in Querying a Database from the Web In any script used to access a database from the Web, you will follow some basic steps: 1. Check and filter data coming from the user. 2. Set up a connection to the appropriate database. 3. Query the database. 4. Retrieve the results. 5. Present the results back to the user. Setting Up a Connection We use this line in our script to connect to the MySQL server:
Compiled By Zanamwe N @2012 Page 64 of 79

@ $db = mysql_pconnect('localhost', root, 'mypass'); We have used the mysql_pconnect() function to connect to the database. This function has the following prototype: resource mysql_pconnect( [string host [:port] [:/socketpath] [, string user [, string password]]] ); You will pass it the name of the host on which the MySQL server is running, the username to login as, and the password of that user. All of these are optional, and if you dont specify them, the function uses some sensible defaultslocalhost for the host, the username that the PHP process runs as, and a blank password. The function returns a link identifier to your MySQL database on success (which you ought to store for further use) or false on failure. The result is worth checking as none of the rest of code will work without a valid database connection. We have done this using the following code: if (!$db) { echo 'Error: Could not connect to database. Please try again later.'; exit; } An alternative function that does almost the same thing as mysql_pconnect() is mysql_connect().The difference is that mysql_pconnect() returns a persistent connection to the database. A normal connection to the database will be closed when a script finishes execution, or when the script calls the mysql_close() function. A persistent connection remains open after the script finishes execution and cannot be closed with the mysql_close() function. Choosing a Database to Use You will remember that when we are using MySQL from a command line interface, we need to tell it which database we plan to use with a command such as use products; We also need to do this when connecting from the Web. We perform this from PHP with a call to the mysql_select_db() function, which we have done in this case as follows: mysql_select_db('students'); // here we assuming that you created a database called students. The mysql_select_db() function has the following prototype: bool mysql_select_db(string database, [resource database_connection] ); It will try to use the database called database. You can also optionally include the database link you would like to perform this operation on (in this case $db), but if you dont specify it,the last opened link will be used. If you dont have a link open, the default one will be opened as if you had called mysql_connect(). Querying the Database To actually perform the query, we can use the mysql_query() function. Before doing this, however, its a good idea to set up the query you want to run:
Compiled By Zanamwe N @2012 Page 65 of 79

$query = "select * from registration where ".$searchtype." like '%".$searchterm."%'"; In this case, we are searching for the user-input value ($searchterm) in the field the user specified ($searchtype).You will notice that we have used like for matching rather than equal its usually a good idea to be more tolerant in a database search. Its important to realize that the query you send to MySQL does not need a semicolon on the end of it, unlike a query you type into the MySQL monitor. We can now run the query: $result = mysql_query($query); The mysql_query() function has the following prototype: resource mysql_query(string query, [resource database_connection] ); You pass it the query you want to run, and optionally, the database link (again, in this case $db). If not specified, the function will use the last opened link. If there isnt one, the function will open the default one as if you had called mysql_connect(). This function returns a result identifier (that allows you to retrieve the query results) on success and false on failure. You should store this (as we have in this case in $result) so that you can do something useful with it. Retrieving the Query Results A variety of functions are available to break the results out of the result identifier in different ways. The result identifier is the key to accessing the zero, one, or more rows returned by the query. In our example, we have used two of these: mysql_num_rows() and mysql_fetch_array(). The function mysql_num_rows() gives you the number of rows returned by the query. You should pass it the result identifier, like this: $num_results = mysql_num_rows($result); Its useful to know thisif we plan to process or display the results, we know how many there are and can now loop through them: for ($i=0; $i <$num_results; $i++) { // process results } In each iteration of this loop, we are calling mysql_fetch_array().The loop will not execute if no rows are returned. This is a function that takes each row from the resultset and returns the row as an associative array, with each key an attribute name and each value the corresponding value in the array:
Compiled By Zanamwe N @2012 Page 66 of 79

$row = mysql_fetch_array($result); Given the associative array $row, we can go through each field and display them appropriately, for example: echo '<br />studentid: '; echo stripslashes($row['studentid']); As previously mentioned, we have called stripslashes() to tidy up the value before displaying it. There are several variations on getting results from a result identifier. Instead of an associative array, we can retrieve the results in an enumerated array with mysql_fetch_row(), as follows: $row = mysql_fetch_row($result); The attribute values will be listed in each of the array values $row[0], $row[1], and so on. You could also fetch a row into an object with the mysql_fetch_object() function: $row = mysql_fetch_object($result); You can then access each of the attributes via $row->title, $row->author, and so on. Each of these approaches fetches a row at a time.The other approach is to access a field at a time using mysql_result(). For this, you must specify the row number (from zero to the number of rows[ms]1) as well as the field name. For example, $row = mysql_result($result, $i, 'studentid'); You can specify the field name as a string (either in the form "studentid" or "registration. studentid ") or as a number (as in mysql_fetch_row()).You shouldnt mix use of mysql_result() with any of the other fetching functions. The row-oriented fetch functions are far more efficient than mysql_result(), so in general you should use one of those. Disconnecting from the Database You can use mysql_close(database_connection); to close a nonpersistent database connection. This isnt strictly necessary because they will be closed when a script finishes execution anyway. Putting New Information in the Database Inserting new items into the database is remarkably similar to getting items out of the database. You follow the same basic stepsmake a connection, send a query, and check the results. In this case, the query you send will be an INSERT rather than a SELECT. Although this is all very similar, it can sometimes be useful to look at an example.
Compiled By Zanamwe N @2012 Page 67 of 79

Below is example code that shows how to create a form with three buttons labeled Save, Open and Search and some functionality for each button. Save this file as studentregister.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Student Registration</title> </head> <font size="-1"> <form action="student_register_input.php" method="post"> <div align="center"><strong>Student Registration Form </strong></div> <table width="79%" border="0" cellspacing="3" cellpadding="3"> <tr> <td width="16%" ><div align="left">Student ID</div></td> <td width="26%"><input type="text" name="sid" id="sid" /></td> <td width="31%" align="right"><div align="right">First Name</div></td> <td width="27%"><div align="right"><input type="text" name="fn" id="fn" /> </div></td> </tr> <tr> <td><div align="left">Surname</div></td> <td> <input type="text" name="sn" id="sn" /></td> <td align="right"><div align="right">Date of Birth</div></td> <td> <div align="right"> <input type="text" name="dob" id="dob" /> </div></td> </tr> <tr> <td><div align="left">Gender</div></td> <td> <input type="radio" name="gender" value="radio" id="gender_0" /> Male <input type="radio" name="gender" value="radio" id="gender_1" /> Female </td> <td align="right"><div align="right">Degree</div></td>
Compiled By Zanamwe N @2012 Page 68 of 79

<td> <div align="right"> <input type="text" name="degree" id="degree" /> </div></td> </tr> <tr> <td><div align="left">Address:</div></td> <td><input type="text" name="address" id="address" /></td> <td align="right"><div align="right">Cellphone:</div></td> <td><div align="right"> <input type="text" name="cellphone" id="cellphone" /> </div></td> </tr> <tr> <td><div align="left">E-mail</div></td> <td><input type="text" name="email" id="email" /></td> <td align="right"><div align="right">Department</div></td> <td><div align="right"> <input type="text" name="dept" id="dept" /> </div></td> </tr> <tr> <td><label> <input type="submit" name="button" id="button" value="Save" name="save" /> </label></td> <td><input type="submit" name="button2" id="button2" value="Open" name="open" /></td> <td align="right"><input type="submit" name="button3" id="button3" value="Search" name="search" /></td> </tr> </table> </form>

</html>

The above code produces the form below if interpreted by a browser.

Compiled By Zanamwe N

@2012

Page 69 of 79

Student Registration Form

Student ID Surname Gender Address: E-mail

First Name Date of Birth Degree Cellphone: Department

Male

Female

Save

Open

Search

Establish database connections by creating a file called connections.php and save the code below: <?php @$dbh = mysql_pconnect("localhost","root",""); $db = mysql_select_db("student");
Compiled By Zanamwe N @2012 Page 70 of 79

?> Again we are making the assumption that you created a database called student with no password. The file connections.php must be included in each and every file that interacts with the database. Save the file below as student_register_input.php. This file is responsible for executing the appropriate code when the user clicks any of the three buttons. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <?php include('connections.php'); if(isset($_POST['save'])) { $sid =$_POST['sid']; $fn= $_POST['fn']; $sn= $_POST['sn']; $dob = $_POST['dob']; $gender = $_POST['gender']; $degree = $_POST['degree']; $address = $_POST['address']; $cellphone = $_POST['cellphone']; $email = $_POST['email']; $dept = $_POST['dept']; $insertq = "INSERT INTO registration VALUES('$sid', '$fn', '$sn', '$dob', '$gender', '$degree', '$address', '$cellphone', '$email', '$dept')"; mysql_query($insertq);} elseif(isset($_POST['open']) ) {
Compiled By Zanamwe N @2012 Page 71 of 79

$retrieveq = "SELECT * FROM registration"; $result = mysql_query($retrieveq); $num = mysql_num_rows($result); echo "<table width='100%' border='1' cellspacing='0' >"; echo "<tr>"; echo "<td>Student ID</td>"; echo "<td>First Name</td>"; echo "<td>Surname</td>"; echo "<td>Date of Birth</td>"; echo "<td>Gender</td>"; echo "<td>Degree</td>"; echo "<td>Address</td>"; echo "<td>Cellphone</td>"; echo "<td>Email</td>"; echo "<td>Department</td>"; echo "</tr>"; for($x=0; $x <$num; $x++) { $rows = mysql_fetch_array($result); echo "<td>".$rows[0]."</td>"; echo "<td>".$rows[1]."</td>"; echo "<td>".$rows[2]."</td>"; echo "<td>".$rows[3]."</td>"; echo "<td>".$rows[4]."</td>"; echo "<td>".$rows[5]."</td>"; echo "<td>".$rows[6]."</td>"; echo "<td>".$rows[7]."</td>"; echo "<td>".$rows[8]."</td>"; echo "<td>".$rows[9]."</td>"; echo "</tr>"; } echo "</table> "; } elseif(isset($_POST['search'])) { header("location:studentsearch.php");
Compiled By Zanamwe N @2012 Page 72 of 79

<body> </body> </html> As for the search button, when it is clicked a form called studentsearch.html is opened and below is the code for this form. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> <form action="studentsearch.php" method="post" target="_blank"> <table width="57%" border="0" cellspacing="2" cellpadding="1"> <tr> <td>Search By</td> <td> <select name="searchby"> <option> Student ID</option> <option>Surname </option> <option> Cellphone</option> <option>Department </option> </select> </td> <td>Search Value</td> <td><input type="text" name="searchitem"></td> <td><input type="submit" value="Search"></td> </tr> </table> </form> </body> </html> When the search button for this form is clicked the following code is executed:
Compiled By Zanamwe N @2012 Page 73 of 79

Save this as studentsearch.php <?php include ('connections.php'); $item = $_POST['searchby']; $sql; if($item=="Student ID") { $si = $_POST['searchitem']; $sql = "SELECT * FROM `registration` WHERE studentid = '$si'"; } elseif($item=="Surname") {$si = $_POST['searchitem']; $sql = "SELECT * FROM `registration` WHERE surname = '$si'"; } elseif($item=="Cellphone") {$si = $_POST['searchitem']; $sql = "SELECT * FROM `registration` WHERE cellphone = '$si'"; } elseif($item=="Department") {$si = $_POST['searchitem']; $sql = "SELECT * FROM `registration` WHERE department = '$si'"; } $result = mysql_query($sql) or die(mysql_error()); $numrows = mysql_num_rows($result); if ($numrows>0) { echo "<table width='100%' border='1' cellspacing='0' cellpadding='1'> "; echo "<tr>"; echo "<td>Student ID</td>"; echo "<td>First Name</td>"; echo "<td>Surname</td>"; echo "<td>Date of Birth</td>"; echo "<td>Gender</td>"; echo "<td>Degree</td>"; echo "<td>Address</td>"; echo "<td>Cellphone</td>";
Compiled By Zanamwe N @2012 Page 74 of 79

echo "<td>Email</td>"; echo "<td>Department</td>"; echo "</tr>"; for($x=0; $x<$numrows; $x++) { $rows = mysql_fetch_array($result); echo "<tr>"; echo "<td>".$rows[0]."</td>"; echo "<td>".$rows[1]."</td>"; echo "<td>".$rows[2]."</td>"; echo "<td>".$rows[3]."</td>"; echo "<td>".$rows[4]."</td>"; echo "<td>".$rows[5]."</td>"; echo "<td>".$rows[6]."</td>"; echo "<td>".$rows[7]."</td>"; echo "<td>".$rows[8]."</td>"; echo "<td>".$rows[9]."</td>"; } echo "</table>";

} else { echo "Record not found try again"; } } ?> <form action="studentsearch.php" method="post" target="_blank"> <table width="57%" border="0" cellspacing="2" cellpadding="1"> <tr> <td>Search By</td> <td> <select name="searchby"> <option> Student ID</option> <option>Surname </option> <option> Cellphone</option> <option>Department </option> </select> </td> <td>Search Value</td>
Compiled By Zanamwe N @2012 Page 75 of 79

<td><input type="text" name="searchitem"></td> <td><input type="submit" value="Search"></td> </tr> </table> </form>

</body> </html> One significant difference between using INSERT and SELECT is in the use of mysql_affected_rows(). In the previous script, we used mysql_num_rows() to determine how many rows were returned by a SELECT. When you write queries that change the database such as INSERTs, DELETEs, and UPDATEs, you should use mysql_affected_rows() instead

PHP Upload File You can use PHP to allow your users to upload a file to the server. To allow users to upload a file to the server, you first need to provide a form for them to specify which file they want to upload. Once they click the submit button of the form, the action page is called. This is the page that needs to contain the PHP code to process the uploaded file. The Input Form Before a user can upload a file, you need to provide them with an interface that allows them to select a file and initiate the upload. The following code is an example of an input form. There are a couple of important things to note about this code: The action attribute points to a .php file. This is the file that will process the uploaded file. There is an attribute called enctype, and its value is multipart/form-data. One of the input fields has type="file" . <html> <head> <title>PHP File Upload Example</title> </head> <body> <form enctype="multipart/form-data" method="post" action="uploadFile.php"> <input type="file" name="fileToUpload" /><br /> <input type="submit" value="Upload File" />
Compiled By Zanamwe N @2012 Page 76 of 79

</form> </body> </html> The Action Page Once the user uploads a file, the file is uploaded into a temporary directory on the server. If you don't move the file it will disappear. Therefore, your action page needs to move the file to another location where it can stay as long as you want it to. Whenever a file is uploaded, you can find out certain information about the file including its name, type, size, as well as the name of the temporary file on the server. These details are made available to you via a PHP array called $_FILES. Displaying Details of the Uploaded File This code simply displays the details of the uploaded file. It doesn't move the file to another location - we'll get to that next. For now, you can use this code in conjunction with the above input form to demonstrate what happens when you upload a file to the server. Notice the PHP $_FILES array which contains info about the file. Note that we also divide the file size by 1024 in order to convert it into kb. (Ignore any carriage returns in this example - each table row should be on one line). echo "<table border=\"1\">"; echo "<tr><td>Client Filename: </td> <td>" . $_FILES["fileToUpload"]["name"] . "</td></tr>"; echo "<tr><td>File Type: </td> <td>" . $_FILES["fileToUpload"]["type"] . "</td></tr>"; echo "<tr><td>File Size: </td> <td>" . ($_FILES["fileToUpload"]["size"] / 1024) . " Kb</td></tr>"; echo "<tr><td>Name of Temporary File: </td> <td>" . $_FILES["fileToUpload"]["tmp_name"] . "</td></tr>"; echo "</table>"; The above code results in something like this: Client Filename: File Type: File Size: Water lilies.jpg image/jpeg 81.830078125 Kb

Name of Temporary File: C:\WINDOWS\TEMP\php48B2.tmp Moving the Temp File As mentioned, if we want to keep the file on the server, we need to move it to another location (of our choice). The following code demonstrates how to move the file from the temporary location. move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "C:/upload/" . $_FILES["fileToUpload"]["name"]);
Compiled By Zanamwe N @2012 Page 77 of 79

Checking for Errors The $_FILES array includes an item for any errors that may result from the upload. This contains an error code. If there are no errors, the value is zero ( 0 ). You check this value within an "If" statement. If the value is greater than zero, you know an error has occurred and you can present a user friendly message to the user. Otherwise you can processing the file. if ($_FILES["fileToUpload"]["error"] > 0) { echo "Apologies, an error has occurred."; echo "Error Code: " . $_FILES["fileToUpload"]["error"]; } else { move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "C:/upload/" . $_FILES["fileToUpload"]["name"]); } Restricting File Type/Size Letting your users upload files to your server can be very risky. If you're not careful, you could get users uploading all sorts of files - perhaps including harmful executables etc. You could also find one day that you've run out of disk space because some users have been uploading enormous files. You can restrict the file types and file sizes by using an "if" statement. If the file type and size are acceptable, processing can continue, otherwise, display a message to the user. Important Note: This doesn't prevent the temp file from being created. The file needs uploaded to the server before PHP can find out the file size and type. This simply prevents the file from being moved to your "permanent" location - hence the file should disappear and (hopefully) not become a problem. In any case, I recommend that you install good anti-virus software before allowing users to upload files to your server. if (($_FILES["fileToUpload"]["type"] == "image/gif") || ($_FILES["fileToUpload"]["type"] == "image/jpeg") || ($_FILES["fileToUpload"]["type"] == "image/png" ) && ($_FILES["fileToUpload"]["size"] < 10000)) { move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "C:/upload/" . $_FILES["fileToUpload"]["name"]); } else
Compiled By Zanamwe N @2012 Page 78 of 79

{ echo "Files must be either JPEG, GIF, or PNG and less than 10,000 kb"; }

Compiled By Zanamwe N

@2012

Page 79 of 79

You might also like