0% found this document useful (0 votes)
37 views88 pages

We Blab Manual

Uploaded by

Subbu Buddu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views88 pages

We Blab Manual

Uploaded by

Subbu Buddu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/320556418

Web Applications Development Lab [Lab Manual]

Book · October 2017

CITATIONS READS
0 5,019

1 author:

Asma'a Khtoom
Al-Balqa' Applied University
7 PUBLICATIONS   27 CITATIONS   

SEE PROFILE

Some of the authors of this publication are also working on these related projects:

Internet Development Programming View project

All content following this page was uploaded by Asma'a Khtoom on 22 October 2017.

The user has requested enhancement of the downloaded file.


9/2/2017

Web Applications
Development Lab
[Lab Manual]

Instructor. Asma’a Khtoom


BAU UNIVERSITY
Lab (1) Web Applications Development
HTML Paragraph and Text Formatting
 Objectives:

1- How to install Notepad++ and WAMP server.

2- Learning HTML Tags

 Installing WAMPServer

Go to the following website http://www.wampserver.com/en/

 Download WmpServer 2.4 (32 bit) into your desktop

 Install this software into your desktop

 By doing so, you install the following software: Apache : 2.4.4 MySQL :
5.6.12 PHP : 5.4.16 PHPMyAdmin : 4.0.4 SqlBuddy : 1.3.3 XDebug : 2.2.3

 Instructions to make WampServer functioning properly:

 If the “W” icon is red or yellow, then this means that the software is not
properly configured. Red icon indicates that all services are put offline. Yellow
icon indicates that some services are offline. Green icon means that all
services are online.

 To turn those services on or off, click on the “W” icon once. You should see
the next pop up menu.

Using this window, you should be able to start all services, stop all services or
restart all services. Or you can put the server on the offline mode.

 You may need to disable the IIS webserver on your machine. To do so:

1. Go to “Control Panel”

2. Then go to “Administrative tools”

3. Then go to “Internet Information Services (IIS) Manager”

4. Disable the IIS Server.

Instructor: Asma’a Khtoom. Page |1


 Installing Notepad++:

We will be using this text editor for coding in PHP and html.

 Go to the following website http://notepad-plus-plus.org/download

 Download and install the latest version of Notepad++ into your local machine.

 Viewing the WWW root and Showing files extensions under Windows

The WWW root is the folder where you will be saving your
html and php project files. The path to this folder is
C:\wamp\www, use your Windows Explorer to view the
contents of this folder.

Later in this lab, you will be creating html and php file for
your lab tasks. Those must carry the extensions “.html” and
“.php”.

 HTML Basics

1. All HTML documents must start with a document type declaration: <!DOCTYPE html>.
2. The HTML document itself begins with <html> and ends with </html>.
3. The visible part of the HTML document is between <body> and </body>.

 Try This
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

Instructor: Asma’a Khtoom. Page |2


 Tasks:

[Task1]. HTML Page Paragraphs using <p> tag

1. Use the Windows Notepad++ to type the following html code and save it in a file named
“testing_html.html”.

2. Store this file under the following path into your machine: C:\wamp\www\lab1

3. To edit the file using Notepad++, right click on the file icon and choose “Edit with Notepad++”.

4. Write the next tags in your file:

<html>

<body>

<p>Welcome to Web Lab.</p>

<p>Second Semester 2017.</p>

<p>Instructor Asma Khtoom.</p>

</body> </html>

5. To preview the newly created html file do the following:

a. Click once on the WampServer icon on the Windows taskbar.

b. Choose “localhost” from the menu.

c. You show be able to see the “lab1” folder under “Your Project” in the default localhost page.

d. Navigate inside the folder to view its contents.

e. Click on the project file you would like to preview.

[Task2]. HTML Heading using <h1>,<h2>,…<h6> tags


HTML headings are defined with the <h1> to <h6> tags.

<h1> defines the most important heading. <h6> defines the least important heading, try this code:

<!DOCTYPE html>

<html>

<body>

Instructor: Asma’a Khtoom. Page |3


<h1>This is heading 1</h1>

<h2>This is heading 2</h2>

<h3>This is heading 3</h3>

<h4>This is heading 4</h4>

<h5>This is heading 5</h5>

<h6>This is heading 6</h6>

</body>

</html>

[Task3]. HTML Line Breaks tags

The HTML <br> element defines a line break.

The <br> tag is an empty tag, which means that it has no end tag.

Use <br> if you want a line break (a new line) without starting a new paragraph, try next code:

<!DOCTYPE html>

<html>

<body>

<p>This is<br>a paragraph<br>with line breaks</p>

</body>

</html>

Instructor: Asma’a Khtoom. Page |4


[Task4]. HTML <pre> Element

The HTML <pre> element defines preformatted text. The text inside a <pre> element is displayed in a
fixed-width font (usually Courier), and it preserves both spaces and line breaks:

<!DOCTYPE html>

<html>

<body>

<p>The pre tag preserves both spaces and line breaks:</p>

<pre>

My Bonnie lies over the ocean.

My Bonnie lies over the sea.

My Bonnie lies over the ocean.

</pre>

</body>

</html>

[Task5]. HTML Formatting Elements

HTML uses elements like <b> and <i> for formatting output, like bold or italic text.

Formatting elements were designed to display special types of text:

 <b> - Bold text


 <i> - Italic text
 <u> - underlined text
 <strike>-strike through over text
 <sub> - Subscript text
 <sup> - Superscript text

Try this:

Instructor: Asma’a Khtoom. Page |5


<!DOCTYPE html>

<html>

<body>

<p>This text is normal.</p>

<p><b>This text is bold.</b></p>

<p><i>This text is italic</i></p>

<p>This is <sub>subscripted</sub> text.</p>

<p>This is <sup>superscripted</sup> text.</p>

<p>This is a <u>parragraph</u>.</p>

<p>Version2.0 is <strike>not yet available!</strike> </p>

<p> <b><i>This text is bold and italic</i></b></p>

</body>

</html>

[Task6]. HTML Character Entities

Some characters are reserved in HTML. If you use the less than (<) or greater than (>) signs in your text,
the browser might mix them with tags. Character entities are used to display reserved characters in
HTML.

Instructor: Asma’a Khtoom. Page |6


A character entity looks like this: &entity_name; OR &#entity_number; To display a less than sign (<)
we must write: &lt; or &#60;

Non-breaking Space

A common character entity used in HTML is the non-breaking space: &nbsp; or &#160;

A non-breaking space is a space that will not break into a new line. Two words separated by a non-
breaking space will stick together (not break into a new line).

Examples:

 <p> 10 &nbsp; km/h </p>

If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text,
you can use the &nbsp; character entity.

© entity name = &copy;

Write the correct code to print:


Copyright © 2017 by Jene Adam

For(i=0;i < 20; i++)

Cout<<i;

[Task7]. HTML <hr> Tag

Use the <hr> tag to draw horizontal line. Try the next code:

<!DOCTYPE html>

<html>

<body>

<h1>HTML</h1>

<p>HTML is a language for describing web pages.</p>

<hr>

<h1>CSS</h1>

<p>CSS defines how to display HTML elements.</p></body></html>

Instructor: Asma’a Khtoom. Page |7


Assignments:
Write the appropriate code to view the next page.

Instructor: Asma’a Khtoom. Page |8


Lab (2) Web Applications Development
HTML Lists and Images
 Objectives:

1. Inserting Images into a Web Page


 Image src attribute.
 Other img Element Attributes (alt, width and height attributes.)

2. Creating Lists
 Ordered Lists
 Unordered Lists
 Definition Lists
 Nesting Lists

 Displaying Images on a Web Page

In HTML, images (Gif,JPG, PNG) are defined with the <img> tag.The <img> tag is empty, it contains
attributes only, and does not have a closing tag. The src attribute specifies the URL of the image:

General: <img src="url" alt="some_text" width="width "height="height">

 Tasks:

[Task1]. Display images from web site

<html>

<body>

<img src="http://www.w3schools.com/images/w3schools_green.jpg">

</body>

</html>

[Task2]. Display images from the same folder of the web page

<html><body>

<img src="html.gif">

</body> </html>

Instructor: Asma’a Khtoom. 1


[Task3]. Display images from another folder of the web page

<html>

<body>

<img src="/images/html.gif">

</body>

</html>

[Task4]. Image alt, width and height attributes

 The alt attribute provides an alternate text for an image, if the user for some reason cannot view it.
 You can use the width and height attributes to specify the width and height of an image in pixels.

<html>

<body>

<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">

</body>

</html>

 Adding Lists to a Web Page

There are three basic types of HTML lists: ordered list, unordered list and definition list.

[Task5]. The ordered list in HTML

The ordered list which is created by the ol Element that begins with the <ol> tag and ends with a
closing </ol> tag. The attributes required: type attribute and the start attribute.
<html> <body>

<p><b>My Favorite Drinks :< /b></p>

<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

</body>

</html>

Instructor: Asma’a Khtoom. 2


 Type Attribute can take one of the next values:

Type Description
type="1" The list items will be numbered with numbers (default)
type="A" The list items will be numbered with uppercase letters
type="a" The list items will be numbered with lowercase letters
type="I" The list items will be numbered with uppercase roman numbers
type="i" The list items will be numbered with lowercase roman numbers

Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Uppercase Letters:

<ol type="A">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Lowercase Letters:

<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Uppercase Roman Numbers:

<ol type="I">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Lowercase Roman Numbers:

<ol type="i">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

Instructor: Asma’a Khtoom. 3


 HTML <ol> start Attribute: define the start value of the list.

<html><body>

<ol start="50">

<li>Coffee</li>

<li>Tea</li>

<li>Milk</li>

</ol>

<ol type="I" start="50">

<li>Coffee</li>

<li>Tea</li>

<li>Milk</li>

</ol>

</body> </html>

[Task6]. Unordered list in HTML

 The unordered list which is created by the ul Element that begins with the <ul> tag and
ends with </ul>. The attributes required: just the type attribute.
<html><body>

<h2>An unordered HTML list</h2>

<ul>

<li>Coffee</li>

<li>Tea</li>

<li>Milk</li>

</ul>

</body></html>

Instructor: Asma’a Khtoom. 4


 In unordered list, Type Attribute can take one of the next values:

Disc:
<ul type="disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

Circle:

<ul type="circle">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

Square:
<ul type="square">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

None:

<ul type="none">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

[Task7]. The definition list in HTML

 The definition list: The list of terms and their meanings is called a definition list. This list is
created by the dl Element that starts with the <dl> and ends with </dl>. Inside this element
two elements are used. The <dt> element which goes in front of each term to be defined and a
<dd> element that is used in front of each definition.
<html> <body>

<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl> </body></html>

Instructor: Asma’a Khtoom. 5


[Task8]. The nested list in HTML

<h2>A Nested List</h2>


A Nested List
<ul>
 Coffee <li>Coffee</li>
 Tea <li>Tea
o Black tea <ul type="circle">
o Green tea
 Milk <li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>

Assignments:

1. Write the required code to create the following output: 2. Observe the output of the following piece of code:

<html>

<body>

<h3>Vegetables</h3>

<ul>

<li>Cucumbers</li>

<li>Carrots:

<ul>

<li>Orange Carrot</li>

<li>White Carrot</li>

</ul>

</li>

<li>Spinach</li> </ul>

</body>

</html>

Instructor: Asma’a Khtoom. 6


Lab (3) Web Applications Development
HTML Links
 Objectives:

1. Learn how to Creating Links in HTML


 The a Element and the href Attribute
 The target Attribute
 Going from one Location into another within the Same Web Page
 Going from a Location in a Page to a Specific Location in another Page
 Linking to E-mail Addresses
 Image Maps
 Absolute and Relative URLs

 HTML Links

HTML links are hyperlinks. You can click on a link and jump to another document. A link
does not have to be text. It can be an image or any other HTML element.

 HTML Links - Syntax

In HTML, links are defined with the <a> tag:

<a href="url">link text</a>

href attribute specifies the destination address (http://www.w3schools.com/html/) of the link.

The link text is the visible part, clicking on the link text will send you to the specified address.

Try this:

<html>

<body>

<p><a href="http://www.w3schools.com/html/">Visit our HTML tutorial</a></p>

</body>

</html>

Instructor: Asma’a Khtoom. 1


 Absolute and relative Links
1. An absolute URL points to another web site ex. href="http://www.yahoo.com” A
full web address
2. A relative URL points to a file within a web site without http://www.... Such as:
<a href="html_images.asp">HTML Images</a>
Or ex. href="/themes/theme.css" if the page in a folder in the same web site.

 The target Attribute

The target attribute specifies where to open the linked document.

The target attribute can have one of the following values:

 _blank - Opens the linked document in a new window or tab


 _self - Opens the linked document in the same window/tab as it was clicked (this is
default)

This example will open the linked document in a new browser window/tab:

Try this
<a href="http://www.bau.edu.jo/" target="_blank">Visit BAU!</a>

<a href="http://www.bau.edu.jo/" target="_self">Visit BAU!</a>

 Going from one Location into another within the Same Web Page

<html> <body>

<p><a href="#C4">Jump to Chapter 4</a></p>

<h2>Chapter 1</h2>

<p>This chapter explains ba bla bla</p>

<h2>Chapter 2</h2>

<p>This chapter explains ba bla bla</p>

<h2>Chapter 3</h2>
Instructor: Asma’a Khtoom. 2
<p>This chapter explains ba bla bla</p>

<h2 id="C4">Chapter 4</h2>

<p>This chapter explains ba bla bla</p>

<h2>Chapter 5</h2>

<p>This chapter explains ba bla bla</p>

<h2>Chapter 6</h2>

<p>This chapter explains ba bla bla</p>

</body>

</html>

 Image as Link
Try this
<a href=" http://www.bau.edu.jo/">

<img src="smiley.gif" alt="BAU University" width="42 " height="42 " ">

</a>

 Image Maps

<area shape ="rect|circle|polygon" coords="value">

 coords Attribute Values

Value Description

x1,y1,x2,y2 Specifies the coordinates of the


left, top, right, bottom corner of
the rectangle (for shape="rect")

x,y,radius Specifies the coordinates of the


circle center and the radius (for
shape="circle")

Instructor: Asma’a Khtoom. 3


Try this

<html>

<body>

<p>Click on the sun or on one of the planets to watch it closer:</p>

<img src="planets.gif" width="145" height="126" alt="Planets"


usemap="#planetmap">

<map name="planetmap">

<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">

<area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">

<area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">

</map>

</body></html>

 Linking to E-mail Addresses


Try this

<html><body>

<p>This is an email link:

<a href="mailto:asmakhtoom@yahoo.com?Subject=Hello again">SendMail</a>

</p></body></html>

Instructor: Asma’a Khtoom. 4


 Homework:

Q1 .Write the code to view the next page.

You should create four pages:

Home page : include image and welcome message

News page: include nested lists (orderd and unordered list) about any news.

Contact: include an email link

About: contain paragraph about you (name,id,mobile number,university name)

Q2. Write the code to view the next page. Each link open location as follow:
Pictures: open your computer picture folder.

Projects: open html page contain definition list of 3 project.

Social: open html page contain three ordered list with three images about social media sites.

Instructor: Asma’a Khtoom. 5


Lab (4) Web Applications Development
HTML Tables
 Objectives:

 Creating HTML Tables


 Learn the different attributes of tables such as: caption, colspan, rowspan and others.
 Create Frames and use it in your HTML page.

 Defining an HTML Table

An HTML table is defined with the <table> tag. Each table row is defined with the <tr> tag. A table
header is defined with the <th> tag. By default, table headings are bold and centered. A table
data/cell is defined with the <td> tag.

<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>

<tr>
<td>Asma</td>
<td>Mohammad</td>
<td>33</td>
</tr>

<tr>
<td>Ahmad</td>
<td>Naji</td>
<td>46</td>
</tr>
</table>

 Note: The <td> elements are the data containers of the table.
They can contain all sorts of HTML elements; text, images, lists, other tables, etc.

Instructor: Asma’a Khtoom. 1|Page


 Tasks:

1. Double Border Table, Coloring and width

<html>

<head>

<style>

table, th, td { border: solid;

border-width: 3px;

border-color : red;}

th { color : green;}

td { color : blue;}

</style>

</head>

<body>

……… write the code of your table here.

</body>

</html>

2. Single Border Table

Ex. <head>

<style> table, th, td {

border: solid ;

border-collapse: collapse; //single line border

border-width: 3px;

border-color : red;}

th { color : green;}

td { color : blue;} </style> </head>

Instructor: Asma’a Khtoom. 2|Page


3. Table Cell Padding and cell spacing

 Cell padding specifies the space between the cell content and its borders.
 The cellspacing attribute specifies the space, in pixels, between cells.

<table cellpadding="40" cellspacing=”30”>

……

</table>

Or try this

<table border="3" bordercolor="red" bgcolor="green" cellspacing="5"


cellpadding="3">

4. Table caption and cell coloring using bgcolor


 The <caption> tag defines a table caption. The <caption> tag must be inserted immediately
after the <table> tag. Note: You can specify only one caption per table.

 bgcolor attribute allow you to give a color to the cell or to the row.

 <tr bgcolor=”blue”>

 <th bgcolor=”red” >

<table>
<caption>Student Marks</caption>

<tr>
<th bgcolor=”red” >Name</th>
<th bgcolor=”red” >Mark</th>
</tr>
<tr>
<td>Ali</td>
<td>30</td>
</tr>
</table>

Instructor: Asma’a Khtoom. 3|Page


5. align Attribute
The align attribute specifies the horizontal alignment of the content in a cell.

<table >

<tr>

<th>Month</th>

<th>Savings</th>

</tr>

<tr>

<td>January</td>

<td align="left">$100</td>

</tr>

<tr>

<td>February</td>

<td align="center">$80</td>

</tr> </table>

6. valign Attribute
The valign attribute specifies the vertical alignment of the content in a cell.

Try this

<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td valign="bottom">January</td>
<td valign="bottom">$100</td>
</tr>
</table>

Instructor: Asma’a Khtoom. 4|Page


7. rowspan and colspan Attributes

To combine /merge adjacent cells to create larger cell for data.

 rowspan: This attribute specifies the number of rows a cell should merged.
 colspan: This attribute specifies the number of columns a cell should merged.

Example1: rowspan attribute

<table>

<tr>

<th>Month</th>

<th>Savings</th>

<th>Savings for holiday!</th>

</tr>

<tr>

<td>January</td>

<td>$100</td>

<td rowspan="2">$50</td>

</tr>

<tr>

<td>February</td>

<td>$80</td>

</tr>

</table>

Example2: colspan attribute

<table>

<tr>
<td colspan="2">Sum: $180</td>

</tr>

</table>

Instructor: Asma’a Khtoom. 5|Page


 Write code for each:

1. A table that has a cell with an image and text in its content.

2. A table that has a cell with a link in its content.

3. A table that has a cell with a table in its content.

 Defining an HTML iframe element

The <iframe> tag specifies an inline frame. An inline frame is used to


embed another document within the current HTML document.

1. iframe Attributes

Attribute Value Description

src url Specifies the address of the document to embed

height pixels Specifies the height of an <iframe>

width pixels Specifies the width of an <iframe>

scrolling yes Specifies whether or not to display scrollbars


no
auto
name text Specifies the name of an <iframe>

Task. Create 3 html files : mm.html , bb.html and cc.html , write the next code in each one:

1. mm.html

<p> Hello</p> <br/>

<img src: ".........."/> <br/>

<iframe src=”bb.html” width=”60” height=”70” name=”myfr”></iframe>

&nbsp; &nbsp;

<a href=”cc.html” target=”myfr”>Change</a>

Instructor: Asma’a Khtoom. 6|Page


2. bb.html
<p>Welcome</p>
<img src=……/>

3. cc.html
<h1> Hello with iframes</h1>

 Homework:

Q1. Observe the output of the following piece of code:

<html>

<body>

<table border="3" bordercolor="blue" bgcolor="orange" cellspacing="5"


cellpadding="3">

<tr>

<td align="center" colspan="3" bgcolor="yellow" >MY DAILY MENU</td>

</tr>

<tr>

<td rowspan="3">M<br>o<br>n<br>d<br>a<br>y</td>

<td valign="top"><b>Breakfast</b></td>

<td>Orange juice<br>Toast<br>Black coffee</td>

</tr>

<tr>

<td valign="top"><b>Lunch</b></td>

<td>Tuna sandwich<br>Apple</td>

</tr>

Instructor: Asma’a Khtoom. 7|Page


<tr>

<td valign="top"><b>Dinner</b></td>

<td>Hamburger steak<br>Mashed potatoes<br>Green beans<br>Jello</td>

</tr>

</table>

</body>

</html>

Q2.Write the required code to create the following output:

Table1.

2.

Table2.

Instructor: Asma’a Khtoom. 8|Page


Lab (5) Web Applications Development
HTML Forms
 Objectives:

 To understand the using of HTML Forms

 To learn how to create forms, forms methods and other attributes.

Before starting your lab:


create text file called action.php and write the next code in it:

<html> <body>

<?php

echo "hello";

?>

</body></html>

 The <form> Element

The HTML <form> element defines a form that is used to collect user input. An HTML
form contains form elements. Form elements are different types of input elements, like
text fields, checkboxes, radio buttons, submit buttons, and more.

<html>
<body>

<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>

<p>If you click the "Submit" button, the form-data will be sent to a page called
"/action_page.php".</p></body>
</html>

Instructor: Asma’a Khtoom. Page |1


Form Attributes

Attribute usage
Action Attribute The action attribute defines the action to be performed when
the form is submitted
Specifies the HTTP method (GET or POST) to be used when
Method Attribute
submitting the form data.

Each input field must have a name attribute to be submitted. If


Name Attribute
the name attribute is omitted, the data of that input field will
not be sent at all.

enctype Attribute specifies how the form-data should be encoded when


submitting it to the server. can be used only if method="post".

1. Action attribute

Normally, the form data is sent to a web page on the server when the user clicks on the
submit button. In the example above, the form data is sent to a page on the server
called "/action_page.php". This page contains a server-side script that handles the form
data:

<form action="/action_page.php">

If the action attribute is omitted, the action is set to the current page.

2. Method Attribute

The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data:

<form action="/action_page.php" method="get">

when GET is used, the submitted form data will be visible in the page address
field:

/action_page.php?firstname=Mickey&lastname=Mouse

or:

<form action="/action_page.php" method="post">

GET must NOT be used when sending sensitive information! GET is best suited for
short, non-sensitive, amounts of data, because it has size limitations too.

Always use POST if the form data contains sensitive or personal information. The
POST method does not display the submitted form data in the page address field.
POST has no size limitations, and can be used to send large amounts of data.

Instructor: Asma’a Khtoom. Page |2


3. Enctype method

Value Description

Default. All characters are encoded before sent (spaces


application/x-www-form-
are converted to "+" symbols, and special characters are
urlencoded
converted to ASCII HEX values)

No characters are encoded. This value is required when


multipart/form-data
you are using forms that have a file upload control

Spaces are converted to "+" symbols, but no special


text/plain
characters are encoded

 The <input> Element

The <input> element is the most important form element. The <input> element can be
displayed in several ways, depending on the type attribute.

Type Description
text Defines a one-line text input field
radio Defines a radio button (selecting one of many choices)
submit Defines a submit button (for submitting the form)
checkbox Defines a checkbox (selecting many choices)
password Defines a password field (characters are masked)
Button Defines a clickable button
reset Defines a reset button (resets all form values to default values)
image Defines an image as the submit button
file Defines a file-select field and a "Browse..." button (for file uploads)
hidden Defines a hidden input field

Instructor: Asma’a Khtoom. Page |3


 Text Input

<input type="text"> defines a one-line input field for text input:

Try this.

The code The output


<form>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</form>

 Radio Button Input

<input type="radio"> defines a radio button. Radio buttons let a user select ONE of a
limited number of choices.

Try this.

<form>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>

The output:

Instructor: Asma’a Khtoom. Page |4


 Checkbox Input

Try this. And draw the output.

The code output


<html>
<body>

<form action="/action_page.php" method="get">

<input type="checkbox" name="vehicle"


value="Bike"> I have a bike<br>

<input type="checkbox" name="vehicle" value="Car"


checked> I have a car<br>

<input type="submit" value="Submit">


</form>

</body>
</html>

 The Submit Button

<input type="submit"> defines a button for submitting the form data to a form-
handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form's action attribute:

Try this.

The Code The output

<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>

 File
<html><body>

<form action="/action_page.php">
Select a file: <input type="file" name="img">

Instructor: Asma’a Khtoom. Page |5


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

</body></html>

6. hidden

<html>
<body>

<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
<input type="hidden" name="country" value="Norway">
<input type="submit" value="Submit">
</form>

<p>Notice that the hidden field above is not shown to a user.</p>

</body>
</html
7. image submit

<html>
<body>

<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="image" src="img_submit.gif" alt="Submit" width="48"
height="48">
</form>

<p><b>Note:</b> The input type="image" sends the X and Y coordinates of


the click that activated the image button.</p>

</body>
</html>

8. Password

<html><body>

<form action="/action_page.php">

Email: <input type="text" name="email"><br>

Password: <input type="password" name="pwd" maxlength="8"><br>

Instructor: Asma’a Khtoom. Page |6


<input type="submit">

</form>

</body></html>

9. Reset button

<form action="/action_page.php">

Email: <input type="text" name="email"><br>

Pin: <input type="text" name="pin" maxlength="4"><br>

<input type="reset" value="Reset">

<input type="submit" value="Submit">

</form>

10. Buttons

<form>

<input type="button" value="Click me" >

</form>

 textarea Element

The <textarea> tag defines a multi-line text input control.


The textarea Element Attributes
 rows Attribute
 cols Attribute

<html>
<body>

<form action="/action_page.php">
<textarea name="message" rows="10" cols="30">The cat
was playing in the garden.</textarea>
<br>
<input type="submit">
</form>

</body>
</html>

Instructor: Asma’a Khtoom. Page |7


 select and option elements

 The <select> element defines a drop-down list:

<form action="/action_page.php">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br><br>
<input type="submit">
</form>

 The <option> elements define an option that can be selected.

By default, the first item in the drop-down list is selected.

To define a pre-selected option, add the selected attribute to the


option:

<option value="fiat" selected>Fiat</option>

 The <fieldset> Element

The <fieldset> element is used to group related data in a form.

The <legend> element defines a caption for the <fieldset> element.

Try this.

The Code Output


<form action="/action_page.php">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>

Instructor: Asma’a Khtoom. Page |8


 Home Work

Q1. Design the next page.

Q2. Design the next page.

Instructor: Asma’a Khtoom. Page |9


Lab (6) Web Applications Development
PHP Basics
 Objectives:

 To understand the basics of php languages.

 Basic PHP Syntax

PHP is a server- side language which means that PHP script will run on the web server and
after execution the result will be sent to the browser as xhtml.

PHP Syntax:

 <?php ………….?>

 Each line code must end with ;


 The file saved with .php extension.

 Case-Sensitivity in PHP

 PHP is case sensitive in: variable names


 PHP is not case sensitive in: function names, keywords and classes names

 Comments in PHP

1. Single line comment:


//…………………………………….
#.................................

2. Multiple line comment


/*………………..
………………..*/

Instructor: Asma’a Khtoom. 1|Page


 Outputting Data to the browser

1. print statement:
int print(string);
Is used to print a single string and can contain html tags, the ( ) are optional.
Always return 1.

Task1. Write the next code and determine what the output is?

The code The output

<?php
print "<hr>";
print "<p><b>BAU University</b></p>";
print "hello";
print "Welcome";
?>

Task2. Write the php code to print the following:

2. echo statements:
void echo(st1,st2,st3,……….);
 Is used to output one or more string and return nothing. Can contain
html tags.
 If it used to print single string the ( ) are optional.
 If it used to print more than one string don’t use ( ).

Instructor: Asma’a Khtoom. 2|Page


Task3. Write the next code and determine what the output is?

The code The output

<?php
echo ("<hr>");
echo ("<p><b>BAU University</b></p>");
echo "hello<br/>";
echo "One",”Two”,”Three”;
?>

 Variables in PHP

1. PHP Data Types


You don’t have to determine the data type of a variable when it is declared.
PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL

2. Declaring Variables.
A variable starts with the $ sign, followed by the name of the variable.
When you assign a text value to a variable, put quotes around the value.

Task4. Write the next code and determine what the output is?

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
$z= true;
$w=null;

echo $txt;
echo "<br>";
echo $x;
echo "<br>";

Instructor: Asma’a Khtoom. 3|Page


echo "$x"; // it will not be used as string ,it is ………………………
echo "<br>";

echo $y;
echo "<br>";
echo $z;
echo "<br>";
echo $w;

?>

3. Constants Declaration.

Constants are like variables except that once they are defined they cannot be
changed or undefined.

A valid constant name starts with a letter or underscore (no $ sign before the
constant name) to create a constant, use the define() function.

Syntax

define(name, value, case-insensitive)

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false

Example1. creates a constant with a case-sensitive name:

<?php Output
// case-sensitive constant name
define("GREETING", "Welcome to BAU!");
echo GREETING;
Echo "GREETING"; // not as variable it will print the string
?>

Example2.creates a constant with a case-insensitive name:

<?php Output
// case-insensitive constant name
define("GREETING", "Welcome to BAU!", true);
echo greeting;
?>

Instructor: Asma’a Khtoom. 4|Page


Constants are Global

Constants can be used across the entire function.

<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
echo GREETING;
}
myTest();
?>

 Concatenation in PHP

You can concat two values together using the dot ( . )


Example:

$txt2 = "WEB Lab";


echo "Study PHP at " . $txt2 . "<br>";

 Functions in PHP

1. Creating and calling functions

Syntax

function functionName() {
code to be executed;
}

 A user defined function declaration starts with the word "function":


 A function name can start with a letter or underscore (not a number)
 Function names are NOT case-sensitive

Example1. Function without parameters


Output
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

Instructor: Asma’a Khtoom. 5|Page


Example2. Function with parameters

<?php Output
function familyName($fname) {
echo "$fname Nsour.<br>";
}
familyName("Ahmad");
familyName("Abdullah");
familyName("Leen");
familyName("Tamara");
familyName("Noor");
?>

Example3. Function with parameters

<?php
function familyName($fname, $year) {
echo "$fname Al-Abadi. Born in $year <br>";
}
familyName("Ayman", "1975");
familyName("Jumana", "1978");
familyName("Fadi", "1983");
?>
Output

Example4. Function with parameters

<?php Output
function countNum($n) {
echo "$n . <br>";
}
for($i=1; $i<=10 ; $i++)

countNum($i);

?>

Example5. PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:

Instructor: Asma’a Khtoom. 6|Page


<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); //if there is no default it will cause error.
setHeight(135);
setHeight(80);
?>
Output

Example6. PHP Functions - Returning values


<?php Output
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?

 var_dump() function

The PHP var_dump() function returns the data type and value:

Output
<?php

$x = 5985;

var_dump($x);

?>

Instructor: Asma’a Khtoom. 7|Page


 Variables Scope in PHP

1. Local scope

A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:

Example

<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
?>
Output

2. Global scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:

Example1:

$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>

Output

Instructor: Asma’a Khtoom. 8|Page


 Using Global variables in Functions

Method1. The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example2:
Output
<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; //?>

Method2. PHP also stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable. This array is also accessible from within functions
and can be used to update global variables directly.

Example3:

<?php Output
$x = 5;
$y = 10;

function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; //
?>

3. Static scope

Normally, when a function is completed/executed, all of its variables are deleted.


However, sometimes we want a local variable NOT to be deleted. We need it for a
further job. To do this, use the static keyword when you first declare the variable:

Instructor: Asma’a Khtoom. 9|Page


Example:

<?php Output
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
?>

Note: The variable is still local to the function.

4. Parameter scope
The parameter is local to function.

Example:
Output
<?php
function mm($value) {
$value=$value*10;
return $value;}

mm(2);
echo value;// error
?>

 Arrays in PHP

1. Indexed Arrays

Arrays with a numeric index .There are two ways to create indexed arrays:

1. The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");

or

2. the index can be assigned manually:

Instructor: Asma’a Khtoom. 10 |


Page
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

Example1.

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2]
. ".";
?>
Output

 The count Function


Get The Length of an Array - The count() Function

Example2.
Output
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>

 Loop through an Indexed Array

To loop through and print all the values of an indexed array, you could use for loop.

Example3.
Output
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>

Example3.using for each loop


Output

Instructor: Asma’a Khtoom. 11 |


Page
<?php
$age = array("35","37","43");

foreach($age as $x) {
echo $x; echo "<br>";}?>

2. Associative Arrays

Associative arrays are arrays that use named keys that you assign to them. There are
two ways to create an associative array:

1. $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

2. $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

The named keys can then be used in a script; key can be number or string

The value can be of any type.

Example. $color=array(1=>”Red”,”b”=>”blue”,”g”=>”green”);

Example1.

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Output

 Foreach loop through an Associative Array

To loop through and print all the values of an associative array, you could use a
foreach loop.

Example2.

<?php Output
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {


Instructor: Asma’a Khtoom. 12 |
Page
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

 Sort Functions for Arrays in PHP

PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

1. Sort Array in Ascending Order - sort()

To sorts the elements of the $cars array in ascending alphabetical order:

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

To sorts the elements of the $numbers array in ascending numerical order:

Example

<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>

2. Sort Array in Descending Order - rsort()

To sorts the elements of the $cars array in descending alphabetical order:

Example

<?php
$cars = array("Volvo", "BMW", "Toyota");

Instructor: Asma’a Khtoom. 13 |


Page
rsort($cars);
?>

To sorts the elements of the $numbers array in descending numerical order:

Example

<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>

3. Sort Array (Ascending Order), According to Value - asort()

To sorts an associative array in ascending order, according to the value:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>

4. Sort Array (Ascending Order), According to Key - ksort()

To sorts an associative array in ascending order, according to the key:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>

5. Sort Array (Descending Order), According to Value - arsort()

To sorts an associative array in descending order, according to the value:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>

Instructor: Asma’a Khtoom. 14 |


Page
6. Sort Array (Descending Order), According to Key - krsort()

To sorts an associative array in descending order, according to the key:

Example

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>

Instructor: Asma’a Khtoom. 15 |


Page
Lab (7) Web Applications Development
PHP Basics
 Objectives:

 To introduce different functions in PHP

 PHP empty Function

The empty() function is used to check whether a variable is empty or not.

Syntax
empty(var_name)

Return value
FALSE if var_name has a non-empty and non-zero value.

List of empty things :


 "0" (0 as a string)
 0 (0 as an integer)
 "" (an empty string)
 NULL
 FALSE
 "" (an empty string)
 array() (an empty array)
 $var_name; (a variable declared but without a value in a class)
Example:

<?php
$ivar1=0;
$istr1='Learning empty';
if (empty($ivar1))
{
echo '$ivar1'." is empty or 0. <br />";
}
else
{
echo '$ivar1'." is not empty or 0. <br />";

Instructor: Asma’a Khtoom. 1|Page


}
if (empty($istr1))
{
echo '$istr1'." is empty or 0. <br />";
}
else
{
echo '$istr1' ." string is not empty or 0. <br />";
}
?>
Output:

 String Functions

1. PHP strip_tags Function

The strip_tags() function strips a string from HTML, XML, and PHP
tags. all tags will be removed.

<?php
echo strip_tags("Hello <b>world!</b>");
?>

<?php
echo strip_tags("Hello <b><i>world!</i></b>","<b>");
?>
Output:

Instructor: Asma’a Khtoom. 2|Page


2. PHP stripslashes Function

Remove the backslash:

<?php
echo stripslashes("Who\'s Peter Griffin?");
?>
Output:

3. PHP trim Function

Remove characters from both sides of a string ("He" in "Hello" and


"d!" in "World"):

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>

Output:

4. PHP strpos Function

finds the position of the first occurrence of a string inside another


string.

<?php
echo strpos("I love php, I love php too!","php");
?>
Output:

Instructor: Asma’a Khtoom. 3|Page


5. PHP str_split Function

The str_split() function splits a string into an array.

<?php
print_r(str_split("Hello"));// print_r(string): Return an
array containing the keys:

?>
Output:

<?php
print_r(str_split("Hello",3));
?>
Output:

6. PHP str_replace Function


function replaces some characters with some other characters in
a string. It is case-sensitive search.
<html>
<body>

<?php
echo str_replace("world","Peter","Hello world!");
?>

<p>In this example, we search for the string "Hello


World!", find the value "world" and then replace the value
with "Peter".</p>
</body>
</html>
Output:

Instructor: Asma’a Khtoom. 4|Page


Ex2. Using str_replace() with an array and a count
variable:

<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
Output:

7. PHP str_ireplace Function

Function replaces some characters with some other characters in a


string. This function is case-insensitive.

<html>
<body>

<?php
$arr= array("blue","red","green","yellow");
print_r(str_ireplace("RED","pink",$arr,$i)); //Case-
insensitive
echo "<br>" . "Replacements:$i";
?>

</body>
</html>
Output:

Instructor: Asma’a Khtoom. 5|Page


8. PHP htmlspecialchars Function

Converts some predefined characters to HTML entities.

The predefined characters are:

 & (ampersand) becomes &amp;


 " (double quote) becomes &quot;
 ' (single quote) becomes &#039;
 < (less than) becomes &lt;
 > (greater than) becomes &gt;

Example1. Convert the predefined characters "<" (less than) and ">" (greater
than) to HTML entities:

<?php
$str = "This is some <b>bold</b> text.";
echo htmlspecialchars($str);
?>

Output:

The HTML output of the code above will be (View Source):

<!DOCTYPE html>
<html>
<body>
This is some &lt;b&gt;bold&lt;/b&gt; text.
</body>
</html>

Instructor: Asma’a Khtoom. 6|Page


Lab (8) Web Applications Development
Form Handling in PHP
 Objectives:

 How to handle a form data.


 Know php global variables
 How to validate form using php

 PHP Global Variables - Superglobals

1. PHP $_SERVER: $_SERVER is a PHP super global variable which holds


information about headers, paths, and script locations.
 $_SERVER['REQUEST_METHOD']: Returns the request method used to
access the page (such as POST).
 $_SERVER['PHP_SELF']: Returns the filename of the currently executing
script.

2. PHP $_REQUEST: is used to collect data after submitting an HTML form.

3. PHP $_POST: is widely used to collect form data after submitting an


HTML form with method="post".
4. PHP $_GET: can also be used to collect form data after submitting an
HTML form with method="get".

 Form Handling

Example1.
Part1. Create this web page.

c.html

<html><head>

<title>Php contact form</title>

</head> <body>

<form name="contact" method="post" action="one.php">

Instructor: Asma’a Khtoom. 1|


Page
Name:<input type="text" size=25 name="uname" /><br/>
Email:<input type="text" size=25 name="email" /><br/>
Phone:<b><input type="text" size=25 name="phone" /><br/>
Message:<textarea name="message" rows="5" cols="35"></textarea><br/>
<input type="submit" value="Send" name="send"/>
</form>

</body></html>

Part2. Create php file called “one.php” in www root to hold the data sent by submit
button. To display the submitted data you could simply echo all the variables.

<?php

$name= $_POST['uname'];

echo "PHP file received the Name". " ". $name; ?>

<br>

Your email address is: <?php echo $_POST["email"]; ?>

Output:

Example 2:
Modify the one.php file as follows:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST")

$name= $_POST['uname'];

else

$name= $_GET['uname'];

echo "PHP file received the Name". " ". $name; ?>

Instructor: Asma’a Khtoom. 2|


Page
Example 3:
Modify the one.php file as follows:

<?php

$name=$_REQUEST['uname'];

echo $name; ?>

Task1: Write a code to check if the user enter the name or not. If the name entered print
it, if not ask the user to enter it.

Task2. Design a form to enter the user name and age, then when you submit the form
the output like the next one appeared in anew page.

Welcome Asma’a!

You are 34 years old.

Instructor: Asma’a Khtoom. 3|


Page
 Form Validation

Create the next form first in a "test_form.php" file.

PHP Form Validation Example


* required field.

Name: *

Password: *

Gender: Female Male *

Submit

You’re Input:

 Validation rules for the form above are as follows:


Name Required Must only contain letters and whitespace
Password Must consist of more than 8 characters.
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one

Instructor: Asma’a Khtoom. 4|


Page
Example1:

<html>

<body>

<?php

$nameErr = "";

$passErr = "" ;

$name = "";

$pass = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")

{ if (empty($_POST["name"]))

$nameErr = "Name is required";

else

$name= $_POST['name'];

if (empty($_POST["pass"]))

$passErr = "password is required";

else

{ $p = $_POST['pass'];

if(strlen($p)>8)

$pass = $p;

else

$passErr ="Password must be greater than 8"; }}


?>

Instructor: Asma’a Khtoom. 5|


Page
<h2>PHP Form Validation Example</h2>

<form method="post"

action="<?php echo $_SERVER["PHP_SELF"];?>">

Name: <input type="text" name="name" value="<?php echo


$name;?>"/>

<font color="red">*<?php echo $nameErr;?></font></p>

Password: <input type="password" name="pass"/>

<font color="red">*<?php echo $passErr;?></font></p>

<input type="submit" name="submit" value="Send" />

</form>

<?php

echo "<h2>Your Input:</h2>";

echo $name."<br/>";

echo $pass;?>

</body>

</html>

Example2
Validate that the name and password must only contain letters and whitespace.

You should do three things:

1. Converts special characters to HTML entities using htmlspecialchars() function.


2. Strip unnecessary characters (extra space, tab, newline) from the user input data (with
the PHP trim() function)
3. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)

Instructor: Asma’a Khtoom. 6|


Page
Assume we have the following form in a page named "test_form.php".

Create a function that will do all the checking for us (which is much more convenient
than writing the same code over and over again).

We will name the function myTest ().

<html><body>

<?php

$nameErr = "";

$passErr = "";

$name = "";

$pass = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")

{ if (empty($_POST["name"]))

$nameErr = "Name is required";

else

$name= myTest( $_POST['name']);

if (empty($_POST["pass"]))

$passErr = "password is required";

else

{ $p = myTest($_POST['pass']);

if(strlen($p)>8)

$pass = $p;

else

$passErr ="Password must be greater than 8";}}

Instructor: Asma’a Khtoom. 7|


Page
function myTest($data)

{ $data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data; } ?>

<h2>PHP Form Validation Example</h2>

<font color="red"> * required field.</font>

<form method="post"

action="<?php echo($_SERVER["PHP_SELF"];?>">

Name: <input type="text" name="name" value="<?php echo


$name;?>"/>

<font color="red">*<?php echo $nameErr;?></font>

Password: <input type="password" name="pass"/>

<font color="red">*<?php echo $passErr;?></font></p>

<input type="submit" name="submit" value="Send" />

</form>

<?php

echo "<h2>Your Input:</h2>";

echo $name."<br/>";

echo $pass;?>

</body> </html>

Instructor: Asma’a Khtoom. 8|


Page
Example 3

Add a gender to the above form and validate if it is checked or


not.
isset() function: The isset () function is used to check whether a
variable is set or not.

<html> <body>

<?php

$nameErr = "";

$genderErr = "" ;

$name = "";

$gender = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")

if (empty($_POST["name"]))

$nameErr = "Name is required";

else

$name= myTest( $_POST['name']);

if (empty($_POST["gender"]))

$genderErr = "Gender is required";

else

$gender = myTest($_POST["gender"]);
}

function myTest($data)

{ $data = trim($data);

$data = stripslashes($data);

$data = htmlspecialchars($data);

Instructor: Asma’a Khtoom. 9|


Page
return $data; }?>

<h2>PHP Form Validation Example</h2>

<font color="red"> * required field.</font>

<form method="post"

action="<?php echo $_SERVER["PHP_SELF"];?>">

Name: <input type="text" name="name" value="<?php echo


$name;?>"/>

<font color="red"> *<?php echo $nameErr;?></font><br>

Gender:

<input type="radio" name="gender" <?php if (isset($gender)


&& $gender=="female") echo "checked";?> value="female"
/>Female

<input type="radio" name="gender" <?php if


(isset($gender) && $gender=="male") echo "checked";?>
value="male" />Male

<font color="red"> * <?php echo $genderErr;?> </font>


<br>

<input type="submit" name="submit" value="Send" />

</form>

<?php

echo "<h2>Your Input:</h2>";

echo $name."<br/>";

echo $gender;?>

</body>

</html>

Instructor: Asma’a Khtoom. 10 |


Page
HomeWork

Q1. Design and implement a php application that accepts two integer numbers from the
current user through. Those represent the number of rows and the number of columns in a
table. The php code should return back a web page that displays the table with the number
of rows and columns requested.

Instructor: Asma’a Khtoom. 11 |


Page
Lab (9) Web Applications Development

PHP Sessions

 Objectives:

 To understand the concept of PHP Sessions

 Example

In the example below, we will create a simple page-views counter. The isset() function
checks if the "views" variable has already been set. If "views" has been set, we can
increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:

vv.php

<?php

session_start();

if(isset($_SESSION['views']))

$_SESSION['views']= $_SESSION['views']+1;

else

$_SESSION['views']= 1;

echo "Views=". $_SESSION['views'];

?>

<html>

<body>Hello there</body>

</html>

The first time you run this script on a freshly opened browser the if statement will
fail because no session variable views would have been stored yet. However, if you
refreshed the page the if statement would be true and the counter would increment by
one. Each time you reran this script you would see an increase in views by one.

Instructor: Asma’a Khtoom. 1|Page


Example:

First, create the following PHP File:

mypage.php

<?php

// this starts the session

session_start();

// this sets variables in the session

$_SESSION['color']='red';

$_SESSION['size']='small';

$_SESSION['shape']='round';

print "Done";

?>

Now we are going to make a second page. We again will start with session_start()(we
need this on every page) - and we will access the session information we set on our first
page. Notice we aren't passing any variable; they are all stored in the session.

mypage2.php

<?php

session_start();

echo "Our color value is ".$_SESSION['color'];

echo " Our size value is ".$_SESSION['size'];

echo " Our shape value is ".$_SESSION['shape']; ?>

Instructor: Asma’a Khtoom. 2|Page


You can also store an array within the session array. Go back to our
mypage.php file and edit it slightly to do this:

<?php
session_start();
// makes an array
$colors=array('red', 'yellow', 'blue');
// adds it to our session
$_SESSION['color']=$colors;
$_SESSION['size']='small';
$_SESSION['shape']='round';
print "Done"; ?>

Now run this on mypage2.php to show our new information:

<?php
session_start();
//echo a single entry from the array
echo $_SESSION['color'][2]; ?>

--------------------------------------------------------------------------------------------------------

Notes:
<?php
// you have to open the session to be able to modify or remove
it
session_start();

// to change a variable, just overwrite it


$_SESSION['size']='large';

//you can remove a single variable in the session


unset($_SESSION['shape']);

// or this would remove all the variables in the session, but


not the session //itself
session_unset();

// this would destroy the session variables


session_destroy();
?>

By default, a session lasts until the user closes the browse

Instructor: Asma’a Khtoom. 3|Page


Lab (10) Web Applications Development

Creating a Database

 Objectives:

 To understand the concept of database and database management systems.


 To use SQL to create and drop tables and to retrieve and modify data.

 Database Creation

 Open the Sql Console.


 No Password is required.
 Then create the next database. myinfo

1. Create a Database using MySQL


create database myinfo;

2. Select a database to work with


Before working with a particular database, you must tell MySQL which database you want to
work with by using the USE statement.

use myinfo;

3. Create a Table in your Database


create table personal (personID int not null,
firstName varchar(20) not null,
lastName varchar(20) not null,

city varchar(30) not null,

phone1 varchar(15) not null,

phone2 varchar(15),

dob date default '0000-00-00');

3. Filling the Table with Data


After that, the empty table can be filled with data with the INSERT INTO statement.

insert into personal values(1, 'Ben' , 'Storm' , 'Mexico', '0796324432', "", "");

Instructor: Asma’a Khtoom. 1|Page


insert into personal values( 2, 'Kate' , 'Moon' , 'Madrid', '0775255332', null , null);

insert into personal values( 3, 'Kim', 'Stone', 'Milan', '0796324477', "", "");

insert into personal values(4, 'Tom', 'Steven', 'Milan', '0796324444', "", "");

insert into personal (personID, city, firstName, lastName, phone1, dob)


values

(5, 'Algeria', 'Salma', 'Moon', '0744246639', '2002-04-16');

4. Querying, Updating and Deleting Records in MySQL

A. select * from personal;

B. select firstName,lastName from personal where City LIKE 'm%';

C. select * from personal WHERE lastName LIKE '%sto%';

D. select * from personal WHERE lastName LIKE '__o%';

E. select firstName,lastName from personal WHERE phone2 is


null;

F. select concat(firstName, ' ', lastName) as FullName from


personal WHERE city in ('Milan', 'Jordan');

G. select DISTINCT lastName from personal;

H. select * from personal ORDER BY firstName;

I. select * from personal ORDER BY firstName desc;

J. select * from personal ORDER BY firstName desc limit 2;

K. select * from personal ORDER BY firstName ASC limit 0,3;

Instructor: Asma’a Khtoom. 2|Page


L. Create another table in the current database called Orders:

personID orderID OrderDate

1 10308 1996-09-18

2 10309 1996-09-19

4 10310 1996-09-20

SELECT Orders.OrderID, personal.firstName, personal.lastName,


Orders.OrderDate FROM Orders INNER JOIN personal
ON Orders.personID = personal.personID;

M. update personal set phone1 = '0794442266' where personID= 2;

N. delete from personal where firstName = 'Kim';

5. Displaying Databases
The SHOW DATABASE statement displays all databases in the MySQL Database Server.

SHOW DATABASES;

Example:
create table St (ID int not null, Name varchar(20) not null, Age int not null,
UNIQUE (ID));

insert into St values (1, 'Ben', 23);

insert into St values ( 3, 'Kate' , 40);

insert into St values ( 4, 'John' , 45);

insert into St values ( 5, 'Kate' , 30);

insert into St values ( 6, 'Kate' , 35);

insert into St values ( 7, 'Kate' , 20);

insert into St values ( 8, 'Kate' , 18);

Instructor: Asma’a Khtoom. 3|Page


insert into St values ( 9, 'Kate' , 14);

A. SELECT * FROM St WHERE Age BETWEEN 20 AND 35;

B. SELECT * FROM St WHERE (Age BETWEEN 20 AND 35) AND ID IN (1,7);

6. The DROP TABLE Statement


To delete a table the syntax is:

DROP TABLE table_name;

7. The TRUNCATE TABLE Statement

If we only want to delete the data inside the table, and not the table itself, then we need to
use the TRUNCATE TABLE statement:

TRUNCATE TABLE table_name;

Instructor: Asma’a Khtoom. 4|Page


Lab (11) Web Applications Development
Databases with SQL and PHP

 Objectives:

 To understand the concept of database and database management systems.


 To use SQL to create and drop tables and to retrieve and modify data.

 Database Creation

 Create database called Persons.


 Create Table called contacts like this:

ID (PK) FirstName LastName PhoneNumber Email


integer (varchar) (varchar) (varchar) (varchar)

 Insert three records in your table


 Use the database in the next php code.

 Create the main page of the user interface (index.html)

<html>

<head><title>Persons: Main Page </title></head>

<body>

<h1>Persons Information Application </h1>

<p> Welcome to my first Web Application </p>

<p> Next is the main menu of this Application

<ul>

<li><a href="./index.html">Home page </a></li>

<li><a href="./show_all.php">Show all contacts </a>

</li>

</ul></p>

</body>

</html>

Instructor: Asma’a Khtoom. 1|Page


 Creating the first page: Showing all contacts (show_all.php)

<html>

<head><title>Persons: Show All Contacts</title></head>

<body><h1>Persons Application: All my contacts </h1>

<p>Next is a alist of all my contacts </p>

<?php

$con=mysqli_connect("localhost","root","","Persons");

// Check connection

if (mysqli_connect_errno()) {

echo "Failed to connect to MySQL: " . mysqli_connect_error(); }

else{

echo "Connected successfully";

$result = mysqli_query($con,"SELECT * FROM contacts");

while($row = mysqli_fetch_array($result)) {

echo $row['FirstName'] . " " . $row['LastName']; echo "<br>";

mysqli_close($con);

?>

<br /><hr /><p> Go back to <a href="./index.html">Home page </a></li></p>

</body>

</html>

Instructor: Asma’a Khtoom. 2|Page


 Display the Result in an HTML Table

<html>

<head><title>Persons: Show All Contacts</title></head>

<body><h1>Persons Application: All my contacts </h1>

<p>Next is a alist of all my contacts </p>

<?php

$con=mysqli_connect("localhost","root","","Persons");

if (mysqli_connect_errno()) { // Check connection

echo "Failed to connect to MySQL: " . mysqli_connect_error(); }

else{

echo "Connected successfully"; }

$result = mysqli_query($con,"SELECT * FROM contacts");

echo "<table border='1'>

<tr>

<th>Firstname</th>

<th>Lastname</th>

<th>PhoneNumber</th>

</tr>";

while($row = mysqli_fetch_array($result))

echo "<tr>";

echo "<td>" . $row['FirstName'] . "</td>";

echo "<td>" . $row['LastName'] . "</td>";

echo "<td>" . $row['PhoneNumber'] . "</td>";

echo "</tr>"; }

echo "</table>";

mysqli_close($con); ?>

<br /><hr /><p> Go back to <a href="./index.html">Home page </a></li></p>

</body></html>

Instructor: Asma’a Khtoom. 3|Page


 PHP MySQL The Where Clause

$result = mysqli_query($con,"SELECT * FROM contacts WHERE FirstName='Leen'");

 PHP MySQL Order By Keyword

$result = mysqli_query($con,"SELECT * FROM contacts ORDER BY lastname");

 PHP MySQL Update

mysqli_query($con,"UPDATE contacts SET PhoneNumber ='0776227278' WHERE


FirstName='Asma' AND LastName='Khtoom'");

 PHP MySQL Delete

mysqli_query($con,"DELETE FROM contacts WHERE LastName='Ayyash'");

Instructor: Asma’a Khtoom. 4|Page


 Insert Data from a Form into a Database

Example:

We will create an HTML form that can be used to add new records to the "Persons"
table.

<html>
<body>

<form name="ff" method="post" action="insert.php" >


Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

insert.php File:

<?php

$con=mysqli_connect("localhost","root","","Persons");

// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];

$sql="INSERT INTO Persons (FirstName, LastName, Age)


VALUES ('$firstname', '$lastname', $age)";

if (!mysqli_query($con, $sql))
die('Error: ' . mysqli_error($con));

echo "1 record added";

mysqli_close($con);
?>

Instructor: Asma’a Khtoom. 5|Page


 Display the Result in an XHTML Table

<?php

$con=mysqli_connect("example.com","rick","abc123","mydb");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
else
{$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>

<tr><th>Firstname</th><th>Lastname</th></tr>";

while($row = mysqli_fetch_array($result))

{ echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>"; }

echo "</table>";}

mysqli_close($con);
?>

Instructor: Asma’a Khtoom. 6|Page


Lab (12) Web Applications Development
Databases with PHP
 Objectives:

 To understand the concept of database and database management systems.


 To use PHP to create and drop tables and to retrieve and modify data.

 SQL Queries using PHP

1. Create database using PHP code.


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Instructor: Asma’a Khtoom. 1|Page


2. Create a MySQL Table Using MySQLi PHP

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Instructor: Asma’a Khtoom. 2|Page


3. Insert Data into MySQL
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

4. Insert Multiple Records into MySQL


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";

if ($conn->multi_query($sql) === TRUE) {


echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}$conn->close();
?>

Instructor: Asma’a Khtoom. 3|Page


5. Select Data from a MySQL Database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. "
" . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

Code lines to explain from the example above:

 First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a
variable called $result.
 Then, the function num_rows() checks if there are more than zero rows returned.
 If there are more than zero rows returned, the function fetch_assoc() puts all the results into
an associative array that we can loop through.
 The while() loop loops through the result set and outputs the data from the id, firstname and
lastname columns.

Instructor: Asma’a Khtoom. 4|Page


6. Delete Data from a MySQL Table
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>

7. Update Data in a MySQL Table


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

Instructor: Asma’a Khtoom. 5|Page

View publication stats

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy