 
INTERNET

PROGRAMMING

BASICS

MRS.D.ANURADHA M.E.,

P.HARIPRASATH

S.GOKULAMUTHAN

ACKNOWLEDGEMENT

### PREFACE

Writing a book is a not an easy task at all. It requires more magnitude and kind co-operation from many, for its successful completion. We wish to express our sincere thanks to all those who were involved in motivating us to produce this book.

We would like to give our sincere thanks to our honourable **Founder and Chairman, Col. Dr. JEPPIAAR, M.A., B.L., Ph.D.,** for his sincere endeavour in educating us in his premier institution.

We would like to express our deep gratitude to our beloved **Secretary and Correspondent, Dr. P. CHINNADURAI, M.A., M.Phil., Ph.D.,** for his enthusiastic motivation which helped us a lot in completing this book and our sincere thanks to our dynamic **Directors, Mrs. C. VIJAYA RAJESWARI and Mr. C. SAKTHI KUMAR, M.E., M.Phil.,** for providing us with the necessary facilities to complete this book.

We wish to express gratefulness to our **Principal, Dr. K. MANI, M.E., Ph.D.,** for his encouragement and sincere guidance. We wish to convey our special thanks and gratitude to the **Head of the Department, Dr. Mrs. S. MURUGAVALLI, M.E., Ph.D.,** for their encouragement and valuable suggestions without which we would not have completed the project successfully.

MRS.D.ANURADHA, M.E.,

P.HARIPRASATH

S.GOKULAMUTHAN

CHAPTER 01  
REVIEW OF HYPERTEXT MARKUP LANGUAGE

HTML is the markup language that is used for designing the web-page. HTML refers to Hypertext Markup Language is the language which is used for the purpose of creating web pages. HTML doesn't require any software installations to work on. It is very simple to use and also effective language for creating web pages. Before working with the PHP Concepts, we should know some clear ideas about the Hypertext Markup Language.

Needs of HTML:

The following points illustrate the various uses of the HTML language.

  * HTML is the basic language in which it containscollection of different mark up's for creating web pages.

  * It is the basic tool that any web designer to know in order to create a website.

  * HTML provides basics for web creation.We can create the static web pages using HTML.

Types of Web pages:

Generally there are two vast classifications on web pages. They are,

  * Static Web Pages

  * Dynamic Web Pages

Static Web Pages:

Static webpages are defined as the web pages which are created by HTML documents. The static webpages cannot use any server side scripts. They are just used for showing the tag contents to the user who opens it.

Static webpages are very easy to create and also there is no additional computing language skills required to create such kind of pages rather than the HTML.

The above diagram illustrates the static web page mechanism. The Markup document is stored in the server whereas when the client request for service then it will provide it. The service is nothing but showing the tags as a web page.

Advantages of Static Web Pages:

  * It is very easy to create.

  * Static web pages are not complex because they don't have any scripting language implementation.

  * They are applicable for contents which are static.

Disadvantages of Static Web Pages:

  * Static web pages doesn't store or retrieve any data.

  * It shows the same information to the all users.

  * There is no any security or authentication mechanism.

  * Since it displays only the same information it is not effective at all.

Dynamic Web Pages:

Dynamic Web Pages are the converse of the static web pages. Using the Dynamic Web pages we can handle the server side scripts as well as client side scripts. There are two different parts of dynamic web page. They are,

  1. Server Side DWP

  2. Client Side DWP

In the server side dynamic web pages, the creations of dynamic webpages aretaken by the control of application server because they will validate the scripts. Validation of scripts will be performed by this server side DWP.

In case of client side dynamic web page, it will provide an outlook to the user. The client side DWP is essential for the end-user; one can interact with the server side DWP using this client side DWP.

Mechanism:

The dynamic web pages follow the mechanism of client/server. Whenever a client is requesting for the page or anything the server will validates the request. If the request is valid, then it will return the corresponding result or else it just simply throws error to the user terminal.

Web Application:

  * In the above concept, we studied about how the web pages are distinguished. Is there is any difference between a webpage and a web application? Yes! There is a difference between them.

  * We can create a web page that may be of dynamic or static web page. It is simply said to be as a web page.

  * If we create a dynamic web page, we can't interact with it without any html scripts; hence we need a static web page also for establishing the client/server mechanism.

  * The client server mechanism established by using the collective structures of dynamic and static web page is called as "web application".

  * If there is no client/server mechanism with interaction then it is just called as web page and not a web application.

  * Typically a web application should have three components they are database, web server and a Graphical User Interface.

Scripting:

  * In C, if we write a program then it is called as coding or programming because they are actually coded. But for the designing of web-pages they are not coded but they are scripted.

  * There are some pre-defined scripts and tags available; by using these scripts and tags, we can implement the web-page.If we need client/server mechanism then two types of scripting is essential. They are,

    * Server Side Scripting

    * Client Side Scripting

Server Side Scripting:

  * Server Side Scripting was performed by the programming languages like PHPand Ruby etc.

  * They are used to check the request which is arrived from the client side and after validating it will execute the relevant things.

  * They use the CGI in order to build the dynamic web pages.

  * The main usage of PHP is establishing database connectivity.

Client Side Scripting:

  * It is the page which is going to request the server. The scripting for this client page will be implemented by HTML.

  * It provides a screen or a window for the user to interact with the dynamic side so that the client/server mechanism was established.

Server and Client Side Scripting Languages:

SERVER SIDE SCRIPTING LANGUAGES | CLIENT SIDE SCRIPTING LANGUAGUES

---|---

Perl | HTML

PHP | CSS

Python | Javascript

Phases of Web Designing:

There are various different phases involved in the creation of the web page. They are,

  1. Analysis and Planning.

  2. Design.

  3. Development and Testing.

  4. Search Engine Optimization.

  5. Maintenance and Updation.

Phase :I Analysis and Planning

  * This is the first phase for web designing. The procedure of creating website should be very sensitive one.

  * Analysis phase is the major phase that deals with what we are going to implement.

  * The main theme of the web page to be created will be identified by this phase.

  * Analysis phase is used to understand the concept of page to be developed.

  * In the analysis phase, the web developer will conduct a meet in which the customer who requires the website will be interacted. Various pre-defined questions are asked to the customer in order to identify their requirements.

  * If you're creating webpage for your own usage, then in this phase you should think over what is the main theme of the page, what are the requirements to create the page etc.

  * The content of the page, main themes will be planned in this phase.

Phase II: Design

  * Developing the map of the website is the major activity in this phase.

  * Using the gathered requirements, the map or structural schema of the webpage will be identified.

  * The design phase identifies what is the client side scripting language and the server side scripting language that suits for the particular application domain.

Site Map:

  * Site map is the collective structure of web-pages that are organized based on some particular logic.

  * Even we can simply say that site map is the logical view of a menu.

  * The site map makes us to understand the flow over a web-page.

  * The main page or first page of the website is called as Home Page. From the web page, the site map explains where the links are going logically.

  * It consists of collection of nodes that represents each links.

Figure: Site Map of a University Website

Phase III: Development and Testing

  * The design was implemented and the code was developed for both client side as well as server side in this phase.

  * It's the huge part where the original code was developed and then it will be tested for the optimality.

  * Once the code was developed it will be tested to check whether the required solution is obtained or not.

Phase IV: Search Engine Optimization

  * Whenever the development of web page was over, it should be implemented this process is said to be hosting.

  * The hosting of webpage refers to embedding the developed code into the server so that your website is available as World Wide.

  * If the number of users for the webpage is to be increased, then we have to implement a search engine optimization.

  * If we adopt the SEO, your website is globally available effectively.

Phase V: Maintenance and Updation

  * Once the all process was over, the website has to be maintained and if the customer needs any Updation it should be updated periodically.

  * For larger website, there will be a team called as website maintenance team who will take care of website and manages it.

Some Simple Techniques to maintain website:

  * Add scripts to enable right and left clicks so that copyright of your website will be preserved.

  * Implement Ad blocking mechanisms which will makes your website faster.

  * Update contents periodically.

  * Check for bugs and fix them if any.

  * Always have a practice to check whether all the links are properly working after each Updation process.

  * If possible, include a code on your website that tellswhat browser will effectively show your web page.

  * Identify the overall views of your webpage and take necessary actions to improve your SEO properties.

If the above stated steps are followed, the website produced will be worth-vile else it leads to collisionswhile working with it.

Types of Website:

  * There are different categories of website available. They are..

    * Simple Website.

    * Dynamic Website.

    * Transactional Website.

Static Website:

  * Static Websites are one which is implemented by simple HTML documentations.

  * They are simple and suitable for static content displaying sites.

Dynamic Website:

  * The main advantage of dynamic website is that it uses the database.

  * They use languages like PHP to connect and work with the database.

  * Example: Any university result publishing website is dynamic because they stored the marks of students in the database using PHP or something else then using front end design by CSS / HTML the client can access the database.

Transactional Website:

  * Transactional Website is one which performs transaction.

  * This kind of websites should have high security and authentication.

  * Websites which involves online ordering of clothing's, food etc..will comes under this category.

Introduction to HTML:

  * HTML is used for the creation of simple web-pages.

  * HTML is a collection of tags which are used to represent your web-page on the screen effectively.

  * As simply, it is set of markup's and tags which are used for creating the web-pages.

  * HTML 2.0 is the first version of HTML which was proposed in the year of 1995.

  * HTML doesn't need any software installations to work on with it. The essential thing is a web browser and a notepad.

Steps to create a HTML document:

  * Follow the following steps to open a notepad: Start → Run → Notepad.

  * Type the HTML code on the Notepad.

  * Click Save in the File Menu. Save the code with the extension of .html

  * After that, go the location where you saved the HTML file. Perform right click and select open with "Google Chrome (or) Mozila Firefox (or) IE (Internet Explorer) which will display the result of your code.

Is HTML tells any error?

  * In C program, if we write a code and after that it was handovered to the compiler for compilation.

  * During compilation if any error occurs, then the C compiler will throws the error to the user like "Undefined Symbol, Lvalue required and so on".

  * But if your HTML code is wrong anywhere, it never tells and pinpoint the errors. Just it stops the process by providing you a blank screen or it provides abnormal result.

  * If we want to throw errors in HTML then we have to use the Javascript that alerts you.

A simple structure of HTML:

  * The tags are started with <TAG_NAME> and ends with </TAG_NAME>

  * For a simple HTML code we need three major tags. They are

    * HTML tag

    * HEAD tag

    * BODY tag

  * HTML tag (Container Tag): The HTML tag will tells that the following coding was written in the HTML language.

Representation:

<HTML>

....

</HTML>

  * HEAD tag:It holds the details about the documents. The Head tag is the container for the title tag, style tag and script tag.

    * Title tag: This tag is used to display the title of your website on the title bar of your browser.

    * Style tag:This tag is used for formatting the website in such a way that the look and feel is effective.

    * Script tag: It is used for placing scripts like Javascript.

  * It is not the compulsory situation that all of the above tags should be implemented. We can also make <HEAD> tag as an empty tag. The conclusion is that it is developer's wish to use these tags.

  * Representation:

<HTML>

<HEAD>

......

</HEAD>

</HTML>

  * BODY TAG: The body is the main tag of HTML program in which it holds all the items of HTML document. It is similar to the main method in C.

  * Representation:

<HTML>

<HEAD>

<title>My First Web App!</title>

</HEAD>

<BODY>

Welcome to the Page!

</BODY>

</HTML>

Comment Line Tag:

  * In the C language, the comment lines are defined by // for single line comments or /*... */ incase of multiple line comments. The JAVA program will support the Documentation comments.

  * In the Hypertext markup language there is only one comment line tag used to represent both the single line comment as well as the multi-line comments.

  * <!-- Comments --> is the notation that represent the comment line tag in HTML.The comments are not visible to the browser.

Example:

<!-- My First HTML Documents \-->

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODY>

Welcome to the Page!

</BODY>

</HTML>

Heading Tags:

  * The Heading tags are used for defining the headings of the web-page in different font-sizes.

  * There are six different types of heading tags available. They ranges from <h1><h2><h3><h4><h5> and <h6>.

  * The font size of <h1> is larger than <h2> is larger than <h3> and so on.

  * The following program will illustrates the implementation of heading tag.

Example:

<!--STUDY OF HEADING TAGS \-->

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODY>

<H1> H1 </H1><!-- Larger in size -->

<H2> H2 </H2>

<H3> H3 </H3><!-- Smaller in size -->

</BODY>

</HTML>

Output:

Paragraph tag:

  * To display the above paragraph on the web page, we should not use the heading tag because it was implemented to display only the headings. So in order to display a paragraph we should use a tag called paragraph tag.

  * Syntax: <p> Contents of the Paragraph </p>

Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODY>

<p>Introduction – Features of Python – Printing Strings – Types of Strings – Printing Numbers – Raw Strings – Working with variables – Printing variables </p>

</BODY>

</HTML>

ALIGNMENT TAGS IN HTML:

  * The alignments tags are one which is used to align your webpage effectively. If a text is to be placed centred or else it should be bolded or italicized then to implement these things we have to use the alignment tags.

  * The following are the alignment tags that performs formatting your HTML web page..

    * <B>-This tag is used for displaying the bold text in the window.

    * <U>-This tag is used for underlining the text.

    * <I>-To display the text in the italicized manner this tag will be used.

    * <CENTER> \- Makes your text to be centred on the screen.

    * <LEFT> \- Makes your text at the left side of screen.

    * <RIGHT> \- Right alignment of the text.

    * <br> \- It is the important tag which is called as "break tag" . It used for implementing the line breaks. If we want to move the fore coming text to next line then this tag should be used.

    * &nbsp–nbspstands for nonbreaking spacing which is similar to "\t" in C language. It is used for indentation purpose which provides the tab spaces.

Implementation Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODY>

<center> CHATTING! </center>

<p> Hi <b>Hari! </b><i> How are you!</i><br>

<p>I am fine! &nbsp What about you!</p>

</BODY>

</HTML>

Result:

Attributes of HTML:

  * The tags are used for designing the web-pages. The tags have some different properties. They are called as "attributes".

  * Attribute is composition of name and value.

Note: We can also implement the above code using align attribute.

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODY>

<p align="center"> CHATTING! </p>

<p> Hi <b>Hari! </b><i> How are you!</i><br>

</BODY>

</HTML>

Tabulation of Attributes of HTML:

ATTRIBUTE NAME | DESCRIPTION

---|---

id | Used for the identification purpose. It should be unique one so that any item can be accessed in web-page with the help of id

style | Used for embedding the styles like CSS

FORMATTING TEXTS:

As we discussed in the alignment topic, the bold, italics of texts are coming under the formatting operation. Some miscellaneous formatting techniques that the HTML will support are

Super Script:

  * Have you noticed some mathematical equations like   . The 8 in the above equation is the power of x.It is called as super-script. The superscripts can be placed into a HTML document using the syntax: <sup>...</sup>

Subscript:

  * Some chemical formulae like  can also be represented in HTML by using the subscript tag. <sub>...</sub>is the syntax to implement subscript in HTML.

Small Tag:

  * It will display the text smaller than the actual <p> size.

  * Some unwanted information will be displayed under small tag.

  * Syntax: <small>..... </small>

Big Tag:

  * Big Tag is the converse of small tag.

  * Whenever a particular text is to be displayed as larger then big tag will perform the operation that shows the text bigger.

  * Syntax: <big>... </big>

Strike Tag:

  * When I want to display the replacement (or) to display the content is wrong (or) to display the overwritten text we have to use the strike tag.

  * Strike tag will strikes the text.

  * Syntax: <strike>...</strike>

Insert and Delete Tag:

  * The Insert tag is used to insert the new text.

  * Delete tag is similar to strike tag that will perform strike outing of text and insert tag will insert the alternative text with underline.

Implementation Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODY>

<p> Good Evening Friends</p><br>

<p>Can you solve: a<sub>1</sub> x<sup>2</sup>+3x+2<0 grapically? </p>

<p> I got the answer as <big>5</big>but actually its not <del>5</del><ins>It is 6</ins></p>

<p>Someone Please Help Me!</p>

</BODY>

</HTML>

Result:

Meta – Tags:

Meta data is the data about the data. In HTML the meta-data includes data about the document type, description about the code (content) and other information's about the code. It is similar to Java Documentation Comments in which the author name,constructors used and other info are specified.

In meta-tags, it has details about encoding mechanism used, type of document, author and other description. Meta-tags are mainly used for the purpose of search engine optimization.

The major attributes of meta-tags are keywords (for search engine optimization), author (that defines author information), content (explanation about the web-page)

Example for Meta-tags:

<html>

<head>

<meta name="keywords" content="Web, Webpage, PHP, DWP, SWP, Meta">  
<meta name="description" content="The Meta Tag Illustration">  
<meta name="author" content="Me!">

</head>

Font and Colors:

'Font' is used for displaying the text in various different styles. HTML will supportvarious types of fonts that are defined over <font> tag. There are different attributes available for the <font> tag. They are.

  1. Font face Attribute:

  * The font face attribute is used for displaying the text in various different fonts.

  * Some of the commonly used font face values are "Times New Roman", "Arial", "Comic Sans".

  * If there is any mis-spelling in the value of font face then it will take "Times New Roman" as default font for displaying the contents.

  * Syntax: <font face = "font name">Your Text! </font>

  2. Font Size Attribute:

  * The font size attribute is used for varying the font size. To display text larger or smaller or in intermediate sizes the font size attribute is used.

  * The values for font-size ranges from 1 –n where the n depends on each and browsers.

  * Syntax: <font size = "value"> Your Text </font>

Colors:

  * Colors are categorized into two parts in HTML. They are...

    * Colors for the font.

    * Colors for the background.

a) Colors for the font:

  * It used for displaying text in various colors. To provide good front-end it is essential to use such font colors.

  * HTML color specification for both font and background falls into 3categories.

Color specification:

  * We can specify the background color or the font color by three methods,

    * By Red Green Blue (RGB) Value.

    * By Explicit Specification of the color.

    * By Hexa-code of six digit.

Setting the font color:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODY>

<font color="red">This is RED color </font>

<font color="#2BCD11">Hexa Code Color</font>

</BODY>

</HTML>

Output:

Setting the Background Colors of a Website:

  * The attribute of the body tag is used for setting the background color of the website.

  * It sets the background color throughout the page.

  * As similar to setting font color, we can set the background color by any of the three methods.

Implementation:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODYbgcolor="rgb(255,1,255)">

<h1> Hello! </h1>

</BODY>

</HTML>

Lists:

List is used for the processof listing the elements one by one in the web browser. There are three different types of lists supported by the HTML. They are,

  1. Unordered List

  2. Ordered List

  3. Definition List

Unordered List:

  * Lists which are started with bullets rather than the numbers.

  * Unordered list contains list of elements that are started with special symbols to notate each elements in the list.

  * The symbol used to represent each item in the list was specified by using the "list-style-type" attribute.

  * The valid values for the "list-style-type" are disc, square, circle and none.

Syntax of Unordered List:

<ul>

<li>Item 1</li>

<li> Item 2</li>

</ul>

  * The above syntax illustrates that creation of un-ordered list in which <ul> tag defines the start of unordered list. Each <li>holds individual items of the list.

  * As by default, the list-style-type value is "Disc". If we want to change as square or circle we can re-write the code as follows,

<ulstyle= "list-style-type: square">

<li> Item 1</li>

<li> Item 2</li>

</ul>

  * The above code will change the bulleting as square.

Example:

<ul>

<li>Artificial Intelligence</li>

<li>Theory of Computation</li>

</ul>

Ordered List:

  * Ordered lists are one that either starts with a number, alphabet, roman number.

  * <ol> represents the start tag for ordered list hence </ol> is used to denote the end of ordered list.

Syntax:

<ol>

<li> Item 1</li>

<li> Item 2</li>

</ol>

  * If we doesn't mention the type (ie, either we need numbered order list or alphabet order list or roman) then thedefault "Numbered List" will be taken into consideration.

  * We can easily change the type of the ordered list by using type attribute.

TYPE ATTRIBUTE | DESCRIPTION

---|---

type = "a" | List starts from a...

type = "A" | List starts from A...

type = "I" | List starts from the Roman Number I, II...

type= "1" | List starts from 1,2...

Implementation Example:

<ol type= "I">

<li>Java</li>

<li>Computer Networks</li>

<li> Database Management Systems</li>

</ol>

Result:

Definition List:

  * It is a special kind of list in which <dl>defines the start of definition list,<dt> indicates the term that is going to be stated in the definition list and <dd>implements the description of the term.

  * This is a list in which the additional definition about each item on it

Syntax:

<dl>

<dt>Term 1 Heading </dt>

<dd> Description of the Term1 </dd>

<dt> Term 2 Heading </dt>

<dd> Description of the Term 2</dd>

</dl>

Example:

<dl>

<dt>TPDE</dt>

<dd>Transforms and Partial Differential Equations</dd>

<dt>PQT</dt>

<dd>Probability and Queuing Theory</dd>

</dl>

Result:

Text Decorating Tags:

The text decorating tags are similar to the alignment tags in the HTML. Text decorating tags isproviding advanced alignments to decorate the text. The following are the text-decorating tags supported by HTML.

  1. Mark Tag

  2. Abbr Tag

  3. Quote Tag

  4. Code Tag

Mark Tag:

  * Mark tag is used for highlighting a particular text in the paragraph or line.

  * It highlights the text by the yellow color as default.

  * Syntax: <mark>Text to be marked </mark>

Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<h1> Hello! </h1>

<BODY>

<p>It is very important notice for <mark> CSE </mark> students.</BODY>

</HTML>

Result:

Abbr Tag:

  * The Abbr tag is used for notating the abbreviations.

  * Syntax: <abbr title= "expanded text ">Simplified Notation</abbr>

  * They are used to embed the dictionaries with your website.

Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<h1>Abbreviated Tags</h1>

<BODY>

<p>The Central Part of Computer is<abbr title= "Central Processing unit">CPU </abbr></p>

</BODY>

</HTML>

Quote Tag:

The quote tags are used for notating the quotes in the website. There are two types of quote tags. They are.

  1. Short Quote Tag

  2. Block Quote Tag

Short Quote Tag:

  * The Short Quote Tag is used for representing the text inside " " (double quotes)

  * Syntax: <q>Text to be displayed </q>

Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<h1>Short Quote Tag</h1>

<BODY>

<p><q>Welcome!</q></p>

</BODY>

</HTML>

Block Quote Tag:

  * The block quote tag is used for the purpose of displaying multi-line quotes or block of codes in HTML.

  * If you mention a text in the block quote then it will be partially centred.

  * Syntax: <blockquote>.... </blockquote>

Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<h1>Block Quote Tag </h1>

<BODY>

<blockquote>Welcome to the Department of Computer and Science and Engineering</blockquote>

<p>Login to Continue...</p>

</HTML>

Code Tag:

  * Consider that the website going to be developed is for programming tutorial then we have to embed some codes on that website.

  * Code tag is used for displaying the codes in your website.

  * If we use the code tag, then the text will be displayed in the Consolas (Mono spaced font) so that the end-user can differentiate the code from the non-code content of the website.

  * Syntax : <code>Your code goes here...</code>

Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<h1>Code Tag Description</h1>

<BODY>

<p>Code for Palindrome in Python</p>

</BODY>

</HTML>

Links in HTML:

Links are used for the purpose of switching over from one page to another page or for downloading purpose. There are two different types of links in HTML. They are..

  1. Internal Links

  2. External Links

Internal Links:

Internal links are used for the purpose of linking from one web-page to another web-page that is locally available (or) locally created. If we have n web page documents, then the linking within the n pages alone are said to be internal links.

The internal links are represented by the anchor tag <a>. The syntax for the internal link is <a href = "Full Path">Text to be displayed</a>. We have to mention the full path where the document is available.

External Links:

The external links are used to link among different website. The same anchor tag is used for defining the external links. The syntax is of <a href= "External link / URL"> Text to be displayed</a>

Download links are special type of external link which links to the file directly rather than the web-page.

Implementation Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<h1> Links </h1>

<BODY>

<p>Internal Links<a href= "C://Program Files/abc.html"> Link to the Internal Fileabc</a></p>

<p> External Links<a href= "www.educdetails.com"> Link to the website EDUCDETAILS </a></p>

<p> Download Links <a href= "www.educdetails.com/abc.pdf"> which links to the PDF file in the EDUC details website.</a></p>

</BODY>

</HTML>

Result:

Table:

  * HTML tag <table> supports to display the table on your web-page. The table is a collection of rows and columns. There are different sub-tags available under the <table> tag to display the table effectively on the website.

  * <tr> tag is used for specifying the table row.

  * <td>tag is used for displaying data.

  * We can also change the border width of the table by using the special kind of tag called as border tag.

  * <th> is used to display the table heading in the first column of the table.

  * It is also possible to change the table background color as well as the border color, height, width etc.

Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<BODY>

<TABLE border="4">

<TR>

<TH>

This is heading for table's first column

</TH>

</TR>

<TR>

<TD>

The Definition goes here...

</TD>

</TR>

</TABLE>

</HTML>

Result:

Other Example Snippets:

  1. <TABLE border="2">

  2. <TABLE border= "2" bordercolor= "grey">

  3. <TABLE border ="3" bgcolor = "red">

  4. <TABLE border= "4" width= "500" height = "230">

Marquee:

HTML will supports the different types of simple animations. One among them is said to be marquee. The moving or scrolling text is said to be marquee.

Attributes of Marquee Tag:

ATTRIBUTE | EXAMPLE

---|---

<marquee> | The main attribute for displaying the scrolling text

width | Width of Marquee will be specified

height | The height of marquee, in case of up-down (or) down-up marquee will be specified.

scrollamount | Determines how fast the marquee should be scrolled

bgcolor | The background color of the marquee.

direction | To notate the direction of scroll either left, right, up or down

Example:

<HTML>

<HEAD>

<title> My First Web App!</title>

</HEAD>

<h1>Marquee</h1>

<BODY>

<marquee scrollamount= "3" bgcolor= "red" direction= "up" width= "140" height= "140">Welcome to this page!</marquee>

</BODY>

</HTML>

Result:

SELF-EVALUATION

Create your own web-page for the following constraints:

  1. Write a HTML code to develop a web-page to display the menu contents of various sessions of a hotel. [Hint: Use List].

  2. Implement a HTML code for developing a C programming tutorial. Add the necessary links to download tutorial book from an external website.

  3. Implement various text-decorations in a simple web-page.

  4. Code a HTML page that implements various attributes of marquee.

  5. Identify which type of website is suitable for

    1. Online Banking System.

    2. Hotel Management System.

    3. University.

    4. Tutorial System. – Justify your answer.

  6. Code a HTML to show the following question paper in the web-browser:

  7. With necessary links, develop a static web-page for displaying services of the hospital.

  8. C reate a web page that looks like the one below.

  9. Create a page that supports the following hyperlinks depicted

  * Link to the document list_graphic_bullets.htm

  * Create link to Amazon.com

  * Link to a place in your document (use the book1.gif)*

  10. Create a table like the one below.

  11. Create a table like the one below.

  12. Create a frameset like the one below. You can use the following files to accomplish this task.

1. Idx.bmp

2. Alignment.htm

3. Font.htm

You may feel free to substitute any content with your own, as long as the "look andfeel" of the frames remains the same.

  13. Create a form like the one below

  14. Using frames as an interface, create a series of web pages where the theme is to provide resources (internet, intranet, static HTML pages) pertaining to the subject of HTML. Ideally, your goal is to create a resource that you can use long after this module when needing information on HTML. As a minimum requirement to this assignment your webpage should...

  * Consist of at least 3 frames.

  * Contain at least 5 url's to internet and/or intranet sites that you can reference aspart of your job.

  * Contain at least 5 references to documents that you have created that you useon a regular basis.

  * Contain at least 5 references to documents others have created that you use ona regular basis.

  * Be organized in a fashion that is logical and intuitive to you.

  * Is done with enough quality that you would not be opposed to it being a link atanother site.

  15. Create a page that contains a table that corresponds to your class Time Table.

  16. a) Create a page that contains an unordered grocery list.  
b) Underline the most important items that you need to get.

  17. a) Create a page that will display 3 frames. Following the example above.  
b) The title of the page should include your name.  
c) Place your Name as the logo in the first frame.  
d) On the left most frame, Include the links Contact Info, History, Time Table, Grocery List.  
e) When this page opens it should show the Contact Info page.

  18. Create a hyperlink to show the information and syllabus of management and engineering MCA. When click on the links each page should display the objective of respective course, fees, duration and year wise and semester wise.

  * Purpose: - Introduce anchor tag to create links between pages. One can able to transfer the control to next page, previous page or to a specific page like Home page.

  19. Design web pages to display the information about JNEC and MCA stream. Divide the page into three frames. The top frame should display the title of the college, left frame shout display the streams of MCA i.e. Engineering and Management and the right frame display the details of selected MCA stream like fees, syllabus etc

  20. Design web pages to accept the student information. Student should enter the details like first name, last name, middle name, city up to 25 characters, and address up to 50 characters. Show the combo box to select the qualification, option button for gender selection. Display the information accepted in a formatted form.

  21. Create a webpage that prints the message "When was this webpage created? Check page's title for the answer." to the screen, and set the title of the page to the current date.

  22. Print two addresses in the same format used on the front of envelopes (senders address in top left corner, receivers address in the center)

  23. Create a page with a link at the top of it that when clicked will jump all the way to the bottom of the page. At the bottom of the page there should be a link to jump back to the top of the page.

  24. Display an image that has a border of size 2, a width of 200, and a height of 200.

  25. Print the squares of the numbers 1 - 20. Each number should be on a separate line, next to it the number 2 superscripted, an equal sign and the result. (Example: 102 = 100).

  26. Display five different images. Skip two lines between each image. Each image should have a title.

____

CHAPTER 02  
WORKING WITH FORMS IN HTML

In the last chapter, we discussed lot of tags that helps to design a simple web-page. This chapter is the extension of chapter 1. Forms plays important role in PHP so I discovered new chapter to study about forms in detail.

Form Tag:

The main process of the dynamic web paging is user interaction. The user can request the server for queries. The queries are handled and validated by the server side's scripts then the relevant actions will be performed.

To provide the user interaction in an effective way the HTML form tags are used. With the help of forms, the user can query the server. There are different core-attributes available under the form tag.

Syntax: The basic general notation to represent the form tag is <form>...</forms>

Form: A form will consist of many fields. Consider a real time situation about course registration (online). To register for a course online the system should require the followings,

  * Name of the candidate

  * Data of Birth

  * Gender

  * Educational Details

  * Address

  * Contact Number

  * E-Mail ID etc..

The above information should be submitted by online so that the candidate can get registered for the course if his/her request was successful according to the server. To get input for the above fields we require forms.

Major Form Attributes:

There are three major form attributes available in HTML. They are

  1. Action

  2. Method

  3. Target

Action:

  * The action attribute of the form specifies how the user given input is to be processed. The form should be submitted to a script so that it validates the fields and then submitted to the server if the script is valid.

  * Whenever a form is created, we should embed the submit button to submit the form then the submission request will seek the action attribute in which the validation will be performed.

Method:

  * There are two methods in HTML forms, they are GET and POST.

  * GET method is used for requesting a data and POST method is to submit the data.

  * Consider a real time scenario of e-billing to a purchase. Initially you have to get the information about the items that you would like to purchase in this case GET method is used to retrieve the data's that are stored.

  * After getting the items, we have to buy to the product by paying money. The online e-transaction should be initiated. For this case, we have to submit the Credit Card Number and other details. At this case, we have to use the POST method.

Text Box:

  * To get the text input from the user, we have to use the text box sub-tag which comes under the form tag.

  * There are three different types of text boxes are possible.

    * Plain Text Box (or) Default Text Box

    * Password Text Box (or) Encrypted Text Box

    * Multi-line Text Box

Plain Text Box (or) Default Text Box:

  * Plain text box is used to get the inputs like user name from the user.

  * They are used for getting a single line text.

  * Syntax: <input type = "text" name = "any name">

Example:

<HTML>

<BODY>

<form>

Name: <input type= "text" name= "name1">

</form>

</BODY>

</HTML>

The result for the above code is,

If we type into the field then it would looks like as follows,

Password Text Box (or) Encrypted Text Box:

  * The Password Text Box is used for getting the secret fields like password, authentication number from the user.

  * The difference between the Plain text box and the Encrypted text box will be defined by the following example.

Example:

<HTML>

<BODY>

<form>

Name: <input type= "text" name= "name1">

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

</form>

</BODY>

</HTML>

Result:

The first text box input type is "text" so that it displays whatever the user types as it is on the screen but the password text box is of input type "password" hence the user typing contents are encrypted. We can also set the size and maximum length for this field.

Multi-line Text Box:

  * Multi-line Text Box is used for getting texts of more than 1 line.

  * Syntax: <textarea rows="value" cols= "value" name= "valid name">

  * Rows define number of rows similarly cols define number of columns.

  * In maximum cases, the multi-line text boxes are used for getting the addresses from the user.

Example:

<HTML>

<BODY>

<form>

Name:<br><input type= "text" name= "name1"><br>

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

Address: <textarea rows= "4" cols= "20" name= "add"></textarea>

</form>

</BODY>

</HTML>

Result:

Checkbox Control:

The check box control is used for the purpose of selecting the multiple fields. For selecting the area of interest under given some list of areas we should you the check box control.

Syntax:

<input type= "checkbox" name= "c1"> Name

Value Attribute Box:

  * Defines value that has to be entered while selecting the box.

Example:

<HTML>

<BODY>

<form>

Name:<br><input type= "text" name= "name1"><br>

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

Address: <textarea rows= "4" cols= "20" name= "add"></textarea><br>

Select:

<input type= "checkbox" name= "n1" value= "SS">System Software

<input type = "checkbox" name= "n2" value= "OS"> Operating Systems

</form>

</BODY>

</HTML>

Result:

Select Box:

To select from a set of pre-defined values, the select box tag is used. Select box is used to any only one item from already defined / existing list of items.

It's similar to the drop-down menu which derives set of items when it has been clicked.

Syntax:

<select name= "NAME">

<option value= "val1" selected>Text to be selected</option>

<option value= "val2">Text to be selected</option>

</select>

Example:

<HTML>

<BODY>

<form>

Name:<br>

<input type= "text" name= "name1"><br>

Password:

<input type= "password" name= "pass">

<br>

Address:

<textarea rows= "4" cols= "20" name= "add"></textarea><br>

Select:

<input type= "checkbox" name= "n1" value= "SS">System Software

<input type = "checkbox" name= "n2" value= "OS"> Operating Systems

<select>

<br>

Please Choose the Core Subject:

<option value= "val1" selected>Maths</option>

<option value= "val2">Science</option>

</select>

</form>

</BODY>

</HTML>

Result:

Radio Button:

To select only option the radio button is used. It doesn't allow the user to select multiple values. If one value is selected, the other values are automatically disabled in the radio-button.

Real Time Example: Selecting gender should take only one value either male or female. Hence at this case, radio button should be used.

Syntax:

<input type = "radio" name= "name 1" value= "val1"> Text 1

<input type = "radio" name= "name 2" value= "val2"> Text 2

Example:

<HTML>

<BODY>

<form>

Name:<br>

<input type= "text" name= "name1"><br>

Password:

<input type= "password" name= "pass"><br>

Address:

<textarea rows= "4" cols= "20" name= "add"></textarea><br>

Select:

<input type= "checkbox" name= "n1" value= "SS">System Software

<input type = "checkbox" name= "n2" value= "OS"> Operating Systems

<select><br><br>

Please Choose the Core Subject:

<option value= "val1" selected>Maths</option> <option value= "val2">Science</option></select>

Select your Gender:

<input type= "radio" name= "t1" value= "M">Male

<input type= "radio" name= "t1" value= "F">Female

</form>

</BODY>

</HTML>

Result:

Exceptions on Radio Button:

Consider the following code for the radio-button,

Select your Gender:

<input type= "radio" name= "t1" value= "M">Male

<input type= "radio" name= "t1" value= "F">Female

In this code, the name of the radio button should be same or else it will allow the user to select the multiple options.

Select your Gender:

<input type= "radio" name= "t1" value= "M">Male

<input type= "radio" name= "t2" value= "F">Female

The output for the above modified code is,

The above figure represents that the radio button will allow multiple selection due to the change in variable names.

Buttons:

  * Once the values required for all the fields are typed or clicked by the user, then it has to send for validation.

  * The validation was performed by the scripting languages like Javascript.

  * At the result of successful validation, the form should be submitted to the database for saving the information.

  * To achieve the overall process, we have to implement a submit button which is used for submitting the form.

  * If the fields of the form is has to be reset, then at this case we have to use button called as "reset" button.

Syntax:

<form action= "where to go" method= "method_name">

Where method_name takes any one value either GET or POST.

Action should have the file name where validating code was written.

Example:

<HTML>

<BODY>

<form>

<form action= "abc.html" method= "post">

Name:<br><input type= "text" name= "name1"><br>

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

Address: <textarea rows= "4" cols= "20" name= "add"></textarea><br>

Select:

<input type= "checkbox" name= "n1" value= "SS">System Software

<input type = "checkbox" name= "n2" value= "OS"> Operating Systems

<select><br><br>

Please Choose the Core Subject:

<option value= "val1" selected>Maths</option> <option value= "val2">Science</option></select>

Select your Gender:

<input type= "radio" name= "t1" value= "M">Male

<input type= "radio" name= "t1" value= "F">Female<br>

<input type= "submit"/>

<input type= "reset" name= "reset"/>

</form>

</BODY>

</HTML>

Result:

Thus the overall all form has been created using HTML.

Validating the Forms:

It is not enough to create a form in HTML and also we have to provide a code for validating the form so that it will be worth vile. Checking the validations of the form fields are handled by Javascript.

Needs of Javascript:

  * Form created only by HTML tags doesn't perform any useful operations. They are static in nature that means, we can't make any submissions to the form.

  * In order to make HTML as dynamic one, we have to start with Javascript. The Javascript will perform a simple thing called "validation" which means checking whether the user gives valid information for the form fields or not.

  * We will discuss more on Javascript in next topic.

Self – Evaluation

1. Create a Form to register students for various courses.

2. Write a Code in HTML to control various actions of Marquee using the button.

3. Create a standard form for the following environment's,

1. Admission of Patient in a Hospital.

2. Voting System.

3. Staff Login System for College.

4. Sign Up form for creating Mail ID.

4. Differentiate between submit and reset.

5. List out the needs of Javascript.

6. Is it possible to validate the form fields using HTML? Reason out in detail.

7. Write HTML programs to implement the form with submit and reset buttons for the Online Shopping Cart System.

8. Using the HTML program to perform actions on exceptions in radio button.

9. Implement a FORM with both GET and POST methods.

CHAPTER 03  
JAVASCRIPT PROGRAMMING

The Javascript is the first approach that converts the static HTML to dynamic HTML by using some special kind of scripts. It is widely used for the purpose of form validation. It has various functions to perform different sort of operations. Javascript is developed by Brendan Eich at Netscape.

It has various pre-defined functions as well as user can write their own functions to make the HTML web-pages more interactive. Without the help of Javascript, there is no interaction to the web-page. It is a case sensitive language and OOP language

We can implement the Javascript in two different ways,

  1. Embedding in HTML.

  2. Creating separate Javascript file using .js extension.

The embedding process of Javascript tags in the HTML document follows the following syntax,

<script language= "javascript" type= "text/javascript">

Javascript code goes here!!

</script>

In the above syntax, the script language is selected as Javascript and the type will tells that scripting language "Javascript" was used for coding.

Embedding Javascript in HTML:

  * The following simple program defines how to embed the Javascript into a HTML document.

<HTML>

<HEAD>

<title> Good Evening!</title>

</HEAD>

<script language= "javascript" type= "text/javascript">

document.write("Welcome to Javascript!");

</script>

</HTML>

Result:

Storing values into variable using Javascript:

  * Variables are similar to the box which holds something. As similar variable holds some values. The following example illustrates a Javascript program to perform operations with variables.

Syntax for variable Initialization:

Variable_name= value; (or)

varvariable_name = value;

Rules for variables:

  1. Keywords not allowed.

  2. Letters, numbers and underscore only allowed.

  3. Numbers should not occupy first position in the variable.

Types:

  1. Global Variable – Accessed all over the script.

  2. Local Variable – can be accessed only over the specific function.

Example:

<HTML>

<HEAD>

<title>

Storing Contents into Variable!

</title>

</HEAD>

<script language= "javascript" type= "text/javascript">

v=1;

// Initialize v=1;

t=2;

// Initialize t=2;

u=v+t;

// Perform Addition and store result to variable.

document.write("Addition of two numbers is ",u);

</script>

</HTML>

Result:

Operators in Javascript:

The following list shows various operators that are supported by the Javascript object based language. They are

  * Arithmetic Operators : +, -, *, /, %, ++,--

  * Relational Operators : ==, !=, <, >, <=, >=

  * Logical Operators : &&, ||, !,===,!==

ARITHMETIC OPERATORS:

The arithmetic operators in Javascript are used for performing various arithmetic operations. It includes addition, subtraction, multiplication, division, modulus, increment and decrement operators.

Consider that, A=5 and B=3 then the result of the applying arithmetic operators on A and B are,

OPERATOR USED | OPERATION | RESULT

---|---|---

+ | Adds two number | 5+3=7

- | Subtracts two number | 5-3=2

* | Multiplies two number | 5*3=15

/ | Divides two number | 5/3=1.66667

% | Takes modulus of two number | 5%2=2

++ | Increment by 1 | A++ = 6

B++ = 4

\-- | Decrement by 1 | A-- = 4

B-- = 3

Example 1: Implementation of Arithmetic Operators in Javascript.

<HTML>

<HEAD>

<title>Arithmetic Operators</title>

</HEAD>

<script language= "javascript" type= "text/javascript">

v=1;

t=2;

a1=v+t;

a2=v-t;

a3=v/t;

a4=v*t;

document.write("Addition of two numbers is ",a1);

document.write("Subtraction of two numbers is ",a2);

document.write("Division of two numbers is ",a3);

document.write("Multiplication of two numbers is ",a4);

</script>

</HTML>

RELATIONAL OPERATORS:

The relational operators are used to compare the values between two variables. The result of the comparison will takes two values that it either may be true or false.

Consider that, A=5 and B=3 then the result of the applying relational operators on A and B are,

OPERATOR USED | OPERATION | RESULT

---|---|---

== | Checks whether both values are same | FALSE

!= | Checks whether both values are not the same | TRUE

< | Checks whether a<b | FALSE

> | Checks for A greater than B | TRUE

<= | Checks whether A less than or equal to B | FALSE

>= | Checks whether A is greater than or equal to B | TRUE

Example 2: Implementation of Relational Operators in Javascript.

<HTML>

<HEAD>

<title>Relational Operators</title>

</HEAD>

<script language= "javascript" type= "text/javascript">

a=1; b=2; c=1;

document.write(a==b);

document.write(a!=b);

document.write(a<b);

</script>

</HTML>

The above program will print the result as FALSE TRUE TRUE.

LOGICAL OPERATORS:

The logical operators in Javascript includes &&, || and !. The && (AND) operator returns true value if both variables holds the non-zero values and || (OR) operator will return true value if any one of the operator holds non-zero values ! (NOT operator) is used for reversing the resultant value. If result is TRUE it's NOT operation is FALSE and if the result is FALSE then it returns TRUE.

Ternary Operator:

  * The Ternary Operator (Or) Conditional Operator evaluates the first expression if it is true, then it executes (or) takes the value of statement 1 which is nearer to the expression else it executes the statement 2.

  * Syntax: (Expression) ? Statement 1 : Statement 2.

Example 3: Implementation of Ternary Operator in Javascript.

<HTML>

<HEAD>

<title>Ternary Operators</title>

</HEAD>

<script language= "javascript" type= "text/javascript">

a=1; b=2; c=1;

y=(a>b)?3:7;

document.write(y);

</script>

</HTML>

The above program will print "7" as the result.

Assignment Operator:

The assignment operator is used to assign the result to the variable after performing the desired operation. Javascript allows the following assignment operators.

It perform arithmetic operations on right operand and left operands and stores the results into the left operand.

OPERATOR USED | OPERATION | EXAMPLE

(Consider a=3,b=1)

---|---|---

= | It assigns the variable 1 value to variable 2.

var2=var1 | b=a;

Now the value b is 3

+= | Performs addition then stores the result. | a+=2;

Expanded as: a=a+2;

The value of a is 5

-= | Performs subtraction then stores the result. | a-=2;

Expanded as: a=a-2;

The value of a is 1

*= | Performs multiplication then stores the result. | a*=2;

Expanded as: a=a*2;

The value of a is 6

/= | Performs division then stores the result. | a/=2;

Expanded as: a=a/2;

The value of a is 1.667

Keywords in Javascript:

  * The keywords are reserved words that can't be used or declared as a variable name and has some specific characteristics.

List of Keywords in Javascript:

abstract  
boolean  
break  
byte  
case  
catch  
char  
class  
const  
continue  
debugger  
default  
delete  
do  
double

else  
enum  
export  
extends  
false  
final  
finally  
float  
for

function  
goto  
if  
implements  
import  
in

 | instanceof  
int  
interface  
long  
native  
new  
null  
package  
private  
protected  
public  
return  
short  
static  
super

switch  
synchronized  
this  
throw  
throws  
transient  
true  
try  
typeof

var  
void  
volatile  
while  
with

---|---

  * The above stated keywords are pre-defined for performing the specific operations. Hence we shouldn't use these reserved words as a variable name.

Decision Making:

The logical path selection of the program will be decided with the help of decision making statements. The decision making statements are used for finding path of execution for further execution.

In the Javascript language, the decision making statements are,

  1. If statement

  2. If...else statement

  3. If...else if...else statement.

If statement:

The decision making statements are also said to be conditional statement. The if statement checks for a constraint. If the result of the constraint is true, then it will executes the statements that are placed under the if block else it will just skips the if block.

Syntax:

if(condition)

{

Statements;

}

If condition is true, then the statements will be executed.

Example:

<HTML>

<HEAD>

<title>Rank Holder

</title>

</HEAD>

<h2>Rank Holder</h2>

<script language= "javascript" type= "text/javascript">

var x=1;

if(x==1)

{

document.write("You're the first rank holder");

}

</script>

</HTML>

Result:

The above condition if(x==1) returns true value since we initialized x=1, hence the output of the above code leads to printing the text like "You're the first rank holder".

If you change, var x=3, then the result will prints a blank window by just showing the header as "Rank Holder". This is due to failure of condition and also unavailability of else part in the code.

If...else statement:

The if condition fails, then it provides a blank screen as an output. To show statements to the user whenever a condition gets failed, if...else statements are used.

Syntax:

if(condition)

{

Statement 1;

}

else

{

Statement 2;

}

If condition is true, then the statement 1 will be executed or else the flow goes to statement 2 and the contents inside the else part will be executed.

Example:

<HTML>

<HEAD>

<title>Eligibility for Voting</title>

</HEAD>

<h2>Rank Holder</h2>

<script language= "javascript" type= "text/javascript">

var x=18;

if(x>=18)

{

document.write("You're eligible to vote");

}

else

{

document.write("You're Not eligible to vote!");

}

</script>

</HTML>

Result:

The above condition if(x>=18) returns true value since we initialized x=18, hence the output of the above code leads to printing the text like "You're eligible to vote".

If you change, var x=3, then the result will be "You're Not eligible to vote!" .This is due to failure of condition and also availability of else part in the code.

If...else if...else statement:

To check multiple constraints for a single decision the if...else if...else statements are used. It checks several conditions, if any of them satisfied then it executes their respective coding, if all the conditional checks returns false value, then it finally executes the else part of the control statement.

Syntax:

if(condition 1)

{

Statement 1;

}

else if(condition 2)

{

Statement 2;

}

else

{

Statement n;

}

Example:

<HTML>

<HEAD>

<title>Grades</title>

</HEAD>

<script language= "javascript" type= "text/javascript">

var x=74;

if(x>=91)

{

document.write("S Grade");

}

else if(x>=81)

{

document.write("A Grade");

}

else if(x>=71)

{

document.write("B Grade");

}

else

document.write("Fail");

</script>

</HTML>

Result:

The above condition if(x>=91) returns false value since we initialized x=74, hence it executes the next else if part of the code and checks whether (x>=81) it too returns the value false, hence it goes for the next else if section and checks for (x>=71) and the condition becomes true. At this instant, it will prints "B Grade" as the result.

Looping Statements in Javascript:

Javascript has the following looping statements,

  * For loop

  * For in loop

  * While loop

  * Do-while loop

For loop:

The syntax of for-loop is as follows.

for (initial value; condition; operation)

{

Looping statements goes here..

}

The for loop has three major sectors. They are,

  * Initial value:

    * It represents the start value of the count.

    * At the starting of the loop, the loop iterating variable holds this initial value.

  * Condition to be tested:

    * It represents what is the condition to be tested at this iteration.

Example: Calculation of Sum of 'N' Natural Numbers:

<html>

<head>

<script type = "text/javascript">

varnum = window.prompt("Enter the number:","");

var n = parseInt(num);

var i;

var s = 0;

for(i = 1; i < =n; i++)

{

s = s + i;

}

document.write("<h1>The sum of " + n + "natural number is" + s);

</script>

</head>

</html>

Result:

Note:

window.prompt() – is a method used for getting input from the user.

document.write() – is a method used for writing the output or result or desired data to the web-page.

How the program works?

  1. Specifying Script type:

<script type = "text/javascript">

  2. Initialization of variables required and getting input from user:

varnum = window.prompt("Enter the number:","");

var n = parseInt(num); Getting Input from the user and store to n.

var i; i is a looping variable used for iteration operation.

var s = 0; Initially sum is initialized as zero.

  3. Looping / Performing Calculation:

for(i = 1; i < =n; i++)

{

s = s + i;

}

Iterations: (Consider input as 5)

i value | Condition | Result

---|---|---

1 | 1 <= 5 ; True | s = 0 + 1 = 1

2 | 2 <=5 ; True | s = 1 + 2 = 3

3 | 3 <= 5 ; True | s = 3 + 3 = 6

4 | 4 <= 5; True | s = 6 + 4 = 10

5 | 5 <= 5 ; True | s = 10 + 5 = 15

6 | 6 <= 5; False | Terminated

  4. Printing Result:

document.write("<h1>The sum of " + n + "natural number is" + s);

which prints result in heading tag.

While loop:

  * While loop is used to perform same operation again and again until condition gets failed.

Syntax:

while (Condition c)

{

Looping statements...

}

Whenever condition c returns true value the loop codes are executed else they will not be executed (i.e, loop gets failed)

Example 1: Javascript for Armstrong Number or Not:

<html>

<head>

<script language="JavaScript">

varre,temp,count=0;

varinp=prompt("Provide Number!");

temp=inp;

while(temp>0)

{

re=temp%10;

count=count+(re*re*re);

temp=parseInt(temp/10);

}

if(inp==count)

document.write("<h3>The number "+inp+" is Armstrong number");

else

document.write("<h3>The number "+inp+" is not an Armstrong number");

</script>

</head>

<body>

</body>

</html>

Output:

The number 371 is Armstrong Number.

Example 2: Javascript or reversing the number.

<html>

<head>

<script language="JavaScript">

var input=prompt("Enter the number");

varrem,sum=0;

var temp=input;

while(input>0)

{

rem=input%10;

sum=sum*10+rem;

input=parseInt(input/10);

}

document.write("Reversed Number is:"+sum);

</script>

</head>

</html>

Result:

Enter the Number: 34

Reversed Number is: 43

Arrays in Javascript:

Arrays are used to store the elements in the consecutive memory locations which are accessed by using the single variable.

Syntax for Array:

varar_name ["element1" , "element2"... "element n"]

Example: Printing the elements of an array:

<html>

<head>

<script language="JavaScript">

var a=["Teena","Veena","Prasath","Sugumar","Parandaman",

"Latha","Deepika"];

document.write("<h3>Array Elements are:"+a);

</script>

</head>

</html>

Result:

Array Elements are:

Teena,Veena,Prasath,Sugumar,Parandaman,Latha,Deepika

Note:

  * It is possible to initialize the empty array by using the syntax var a=[] which size will be determined at the run time.

  * We can also access individual elements of an array by using its index value. Example: a[0] returns first location value. (i.e, Teena in our example)

Miscellaneous on Arrays:

Getting length of an array:

We can able to get the length of the array using the syntax arrayname.length. In our example, if we add the line,

document.write ("Length of the array:"+a.length);

will write the result "Length of the array: 7" on the web browser.

Operations on Arrays:

There are different methods used for performing various operations with arrays we can insert, delete, shift, reverse, join and compare the elements of an array using some built-in functions.

Inserting elements:

The inserting new element into an array is performed by using push() method. It will add the new element into the end location of an array which already exists.

Syntax: array_name.push("Item to be inserted");

Example:

<html>

<head>

<script language="JavaScript">

var a=["Parandaman","Latha","Deepika","Hariprasath"];

document.write("<h2>Family Members in 1990:"+a);

a.push("Guru");

document.write("<h2> Family Members in 2014:"+a);

</script>

</head>

</html>

Deleting Element from an array:

The deleting of element from an array is performed by using pop() method. It will delete the element which is available in the end of the array.

Example:

<html>

<head>

<script language="JavaScript">

var a=["Parandaman","Latha","Deepika","Hariprasath"];

document.write("<h2>Family Members in 1990:"+a);

a.push("Guru");

document.write("<h2> Family Members in 2014:"+a);

a.pop();

document.write("<h2>After Pop:"+a);

</script>

</head>

</html>

Shifting elements in an array:

  * The shift method will delete first element in the array.

  * It is equivalent to pop but deletion is from the beginning.

Syntax: a.shift()

Deleting Elements:

We can also delete the elements of an array by mentioning the index of the array. The delete will perform permanent removal of particular element from the array.

Syntax:

deletearray_name[index];

Functions in Javascript:

Function is a block of code which is used for performing some sub task or sub module. Generally, in any programming language, there are two types of functions. They are,

  1. Pre-defined (or) Built In Functions.

  2. User defined functions.

Javascript is well known for it's built in functions. It has various built in functions to perform various operations.

Pre-defined Functions:

Predefined functions are set of functions which are already included in the programming language. It performs some sort of already existing operation. This section will describes some set of pre-defined functions that are used in Javascript.

isFinite(Value) \- Checks whether the passed value is finite or not.Returns the true value if it is a finite number or else if it is aninfinite number then it returns the false value.

isNaN(Value) \- Checks whether the value is Not a Number or not. Returns the true value if it is not a number or else if it is a number then it returns the false value.

eval(string) \- It will evaluates the string value which is passed as a parameter.

Implementation Example:

<html>

<head>

<script language="JavaScript">

var a=1;

var b=3;

t=isFinite(a);

t1=eval(a+b-2);

t2=isNaN("Infinity");

t3=isFinite("Infinity");

document.write(t,t1,t2,t3);

</script>

</head>

</html>

Result:

True 2 False False

User-defined Functions:

User-defined functions are one which is created by the programmer. It will take 0/more arguments. It will perform some specific sort of operation and return the result of that operation to the called function. Simply, functions are logical codes which are performing some logical module.

Syntax:

<script type="text/javascript">

functionfunction_name (argument_1, ... , argument_n)

{

statement_1;

statement_2;

...

statement_m;

returnreturn_value;

}

</script>

Example:

  * A function definition consists of the function keyword and the name of the function. A list of arguments to the function is enclosed in parentheses and separated by commas.

  * The keyword return is used for returning the resultant value.

Example 1: Simple Calculator using Javascript.

<html>

<head>

<script language="JavaScript">

function add(a,b)

{

c=a+b;

return c;

}

function sub(a,b)

{

var c=a-b;

return c;

}

functionmul(a,b)

{

var c=a*b;

return c;

}

function div(a,b)

{

var c=a/b;

return c;

}

functionmodul(a,b)

{

var c=a%b;

return c;

}

t=add(34,5);

t1=sub(14,5);

t2=mul(44,5);

t3=div(4,40);

t4=modul(4,5);

document.write("Addition function return value:"+t);

document.write("Subtraction function return value:"+t1);

document.write("Multiplication function return value:"+t2);

document.write("Division function return value:"+t3);

document.write("Modulus function return value:"+t4);

</script>

</head>

</html>

Result:

Addition function return value:39

Subtraction function return value:9

Multiplication function return value:220

Division function return value:0.1

Modulus function return value:4

Switch Case:

It is a control altering methodology which uses to switch over various options depends upon the value that was holded by the variable.

Syntax:

switch(expression){

case expression 1 :

statements;

break;

case expression 2 :

statements;

break;

default :

statement n;

}

Example:

<html>

<head>

<title>Simple Calculator with switch case</title>

<script language="javascript">

var i,j,op1,op2,op,f;

function digit(i)

{

switch(i)

{

case 1:

document.calc.display.value=(document.calc.display.value)+"1";

break;

case 2:

document.calc.display.value=(document.calc.display.value)+"2";

break;

case 3:

document.calc.display.value=(document.calc.display.value)+"3";

break;

case 4:

document.calc.display.value=(document.calc.display.value)+"4";

break;

case 5:

document.calc.display.value=(document.calc.display.value)+"5";

break;

case 6:

document.calc.display.value=(document.calc.display.value)+"6";

break;

case 7:

document.calc.display.value=(document.calc.display.value)+"7";

break;

case 8:

document.calc.display.value=(document.calc.display.value)+"8";

break;

case 9:

document.calc.display.value=(document.calc.display.value)+"9";

break;

case 0:

document.calc.display.value=(document.calc.display.value)+"0";

break;

case 10:

document.calc.display.value=(document.calc.display.value)+".";

break;

}

}

function operation(j)

{

if(j==1)

{

op1=parseFloat(document.calc.display.value);

document.calc.display.value="";

op=1;

}

if(j==2)

{

op1=parseFloat(document.calc.display.value);

document.calc.display.value="";

op=2;

}

if(j==3)

{

op1=parseFloat(document.calc.display.value);

document.calc.display.value="";

op=3;

}

if(j==4)

{

op1=parseFloat(document.calc.display.value);

document.calc.display.value="";

op=4;

}

if(j==5)

{

op2=parseFloat(document.calc.display.value);

if(op==1)

{

f=op1+op2;

document.calc.display.value=f;

}

else if(op==2)

{

f=op1-op2;

document.calc.display.value=f;

}

else if(op==3)

{

f=op1*op2;

document.calc.display.value=f;

}

else if(op==4)

{

f=op1/op2;

document.calc.display.value=f;

}

}

}

</script>

</head>

<body>

<form name="calc">

<table align="center" bgcolor="black" cellspadding=5 cellspacing=5 height=200 width=200>

<tr>

<td colspan=4 align="center">

<input type="text" name="display">

</td>

</tr>

<tr>

<td>

<input type="button" name="B" value=" 7 "onClick="digit(7)">

</td>

<td>

<input type="button" name="B" value=" 8 "onClick="digit(8)">

</td>

<td>

<input type="button" name="B" value=" 9 "onClick="digit(9)">

</td>

<td>

<input type="button" name="B" value=" + "onClick="operation(1)">

</td>

</tr>

<tr>

<td>

<input type="button" name="B" value=" 4 "onClick="digit(4)">

</td>

<td>

<input type="button" name="B" value=" 5 "onClick="digit(5)">

</td>

<td>

<input type="button" name="B" value=" 6 "onClick="digit(6)">

</td>

<td>

<input type="button" name="B" value=" - " onClick="operation(2)">

</td>

</tr>

<tr>

<td>

<input type="button" name="B" value=" 1 "onClick="digit(1)">

</td>

<td>

<input type="button" name="B" value=" 2 "onClick="digit(2)">

</td>

<td>

<input type="button" name="B" value=" 3 "onClick="digit(3)">

</td>

<td>

<input type="button" name="B" value=" * " onClick="operation(3)">

</td>

</tr>

<tr>

<td>

<input type="button" name="B" value=" 0 "onClick="digit(0)">

</td>

<td>

<input type="button" name="B" value=" ." onClick="digit(10)">

</td>

<td>

<input type="button" name="B" value=" = " onClick="operation(5)">

</td>

<td>

<input type="button" name="B" value=" / "onClick="operation(4)">

</td>

</tr>

</table>

</center>

</form>

</body>

</html>

Result:

Implementation of Javascript for Form Validation:

We studied about the Javascript in this entire unit. This is because while creating the dynamic web-page there should be a user interaction. The user interaction will be in terms of forms at most cases. The form fields should be validated to precede further steps. Hence, for the validation operation we have to use the Javascripts.

The following Javascript coding will validate the form fields before submission. If any errors, it will throw errors / alert messages to the user terminal.

validate.js

functionvalidatesForm()

{

var names= document.getElementById("Pname");

var age= document.getElementById("Page");

var city= document.getElementById("Pcity");

var state= document.getElementById("Pstate");

var email= document.getElementById("Pmail");

varpwd= document.getElementById("Ppwd");

if(isAlphabet(names))

{

if(isNumber(age))

{

if(isAlphabet(city))

{

if(isSelected(state))

{

if(isMail(email))

{

if(isAlphanumeric(pwd))

{

alert("Form fill successful");

return true;

}

}

}

}

}

}

return false;

}

functionisAlphabet(elem)

{

varaexpr= /^[a-zA-Z]+$/;

if(aexpr.test(elem.value))

{

return true;

}

else

{

alert("Characters only in Name text box");

elem.focus();

return false;

}

}

functionisNumber(elem)

{

varstr=elem.value;

varnexpr= /^[0-9]{2}$/;

if(!str.match(nexpr))

{

alert("Age must be less than 100");

setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);

return false;

}

else

{

return true;

}

}

functionisSelected(elem)

{

if(elem.value=="Please Choose")

{

alert("Choose valid state");

elem.focus();

return false;

}

else

{

return true;

}

}

functionisMail(elem)

{

varmexpr= /^[\w\\-\\.\\+]+\@[a-zA-Z0-9\\.\\-]+\\.[a-zA-z0-9]{2,4}$/;

if(mexpr.test(elem.value))

{

return true;

}

else

{

alert("Enter a valid email id");

elem.focus();

return false;

}

}

functionisAlphanumeric(elem)

{

varalexpr= /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;

if(alexpr.test(elem.value))

{

return true;

}

else

{

alert("Password must be at least 6 characters long");

elem.focus();

return false;

}

}

Login.html

<HTML>

<HEAD>

<TITLE>Passenger Login </TITLE>

</HEAD>

<BODY>

<CENTER><H1>LOGIN</H1></CENTER>

<HR>

<PRE>

<BR><BR>

<FORM method="POST" onsubmit="return Logs()">

USER NAME: <INPUT type="text" id="Uname"/>

<BR>

PASSWORD: <INPUT type="password" id="pwd"/>

<BR>

<INPUT type="submit" value="Log In"/>

</FORM>

<HR><HR>

</PRE>

<SCRIPT>

function Logs()

{

var name=document.getElementById("Uname");

varpwd=document.getElementById("pwd");

var alpha= /^[a-zA-Z]+$/;

if(alpha.test(name.value))

{

if(pwd.value=="CSE")

{

open("Passenger Form.html");

return true;

}

else

{

alert("Wrong Password");

return false;

}

}

else

{

alert("Invalid Username");

return false;

}

}

</SCRIPT>

</BODY>

</HTML>

Passenger Form.html

<HTML>

<HEAD>

<TITLE> Passenger Details </TITLE>

<SCRIPT type="text/javascript" src="validate.js">

</SCRIPT>

</HEAD>

<BODY>

<H1><CENTER><U>PASSENGER DETAILS</U></CENTER></H1>

<PRE>

<FORM onsubmit="return validatesForm()">

NAME:

<INPUT type="text" id="Pname" />

<BR>

AGE:

<INPUT type="text" id="Page" />

<BR>

GENDER:

<INPUT type="radio" id="Pgender" value="male" checked />

Male

<INPUT type="radio" id="Pgender" value="female" />

Female

<BR>

CITY:

<INPUT type="text" id="Pcity" />

<BR>

STATE:

<SELECT id="Pstate">

<OPTION>Please Choose</OPTION>

<OPTION>Tamil Nadu</OPTION>

<OPTION>Kerala</OPTION>

<OPTION>Andhra Pradesh</OPTION>

<OPTION>Karnataka</OPTION>

</SELECT>

<BR>

E-MAIL ID:

<INPUT type="text" id="Pmail" />

<BR>

PASSWORD:

<INPUT type="text" id="Ppwd" />

<BR>

<HR>

<BR>

<INPUT type="submit" value="Submit" />

<INPUT type="reset" value="Reset" />

</FORM>

</PRE>

</BODY>

</HTML>

Result:

Login.html

Passenger Form.html

Result:

CHAPTER 04

INTRODUCTION TO SQL

SQL stands for Structured Query Language. It is a language used for manipulating, storing and retrieving data from the Relational Database.

SQL is used in RDBMS (Relational Data Base Management System). All RDBMS are implemented via the usage of Relations. Relation is also called as tables which contain collection of rows (records) and columns (fields).

Some of the RDBMS used are Postgres, Informix, MS access, Oracle, MySQL, Sybase...etc.

Why SQL?

  * It's used for accessing RDBMS

  * To store, manipulate and retrieve data

  * Can be embedded easily in other languages using predefined modules

SQL Commands

SQL commands are instruction which are used to access or communicate with the database to perform some specific task. SQL commands can be grouped into five major classifications, they are,

  * Data Definition Language

  * Data Manipulation Language

  * Data Query Language

  * Transaction Control Language

  * Data Control Language

Data Query Language is normally not specified explicitly and is grouped under Data Manipulation Language in general.

History of Oracle

In further chapters we proceed by using Oracle as our Database. In 1977, Relational Software Incorporated (RSI) a company formed by Larry Ellison, Bob Miner and Ed Oates. This company designed a RDMS called Oracle. The key idea of this company is to develop their RDMS using C and SQL interface.

The version-1 was a prototype, later it released its version-2 to customers which worked on PDP-11 machines using RSX-11 OS and later extended to DEC VAX systems.

In 1983, version-3, was released with slight changes in SQL which increased the performance of the database, unlike previous version which was purely written in C. After this milestone they changed their company to Oracle Corporation.

The version-4 was released in 1984 which is supported in VAX and IBM VM OS. This is the first version to add read consistency as one of its enhancement.

Later in 1985, version-5 was introduced and it was one of its greatest milestone because it gave the world about the client/server mechanism which uses SQL.Net and added that it is the first MS-DOS product to break the 640KB barrier.

In course of time Oracle released version-6 which had enhancements of deferred writes. In 1991 Oracle introduced version-6.1 for DEC VAX platform which had parallel server option.

In1992, version-7 came into market with many architectural changes in the fields of memory, CPU and I/O utilization. This version is the fully fledged RDBMS that is used by many of us.

Soon Oracle developed its versions year after year, now version-12 has been released and will continue its extensions.

Introduction to Terms

There various term use throughout this book which would hard for a novice learner to pick up. Hence some of the used terms are listed out here, for easy understanding purpose.

  1. Block:  
It's the smallest unit of storage in the database. It can be data or a PL/SQL code. The size of block varies from 2KB (min) and 16KB (max).

  2. Buffer:  
The amount of memory that is used to store data which is about or just have been used. It offers quick access to data. There are two buffers namely, database buffer cache (a set of block buffers) and redo log buffers (used for temporary store of entries that are to be written onto to the disk).

  3. Cache:  
It's a storage area which helps us to access the data in faster and efficient manner. It reduces the number of disk access. Caching reduces the time taken to retrieve frequently accessed data in efficient manner.

  4. Checkpoint:  
A point in course of time, which forces all the operation to be written out to disk.

  5. Concurrency:  
The process of performing many function or operation at same time. Oracle provides this facility for the user.

  6. Database:  
A database is a set of organized data which contains actual data which is accessed when it is needed.

  7. Data Dictionary:  
It is a set of tables that maintains the information about the database. The information may be about tables, views, indexes, clusters... etc.

  8. DBA (Database Administrator):  
It is person who is responsible for the operation, configuration and performance of the database. DBA is also responsible for backup of database.

  9. DBMS and RDBMS:

DBMS (Database Management System) is a software or collection of tools that is used to manage database whereas RDBMS (Relational Database Management System) uses relational access of data.

  10. Procedure:  
A procedure is a set of SQL or PL/SQL statements used together to execute a particular function. Both procedure and function are similar except that function returns a value while procedures don't.

  11. Query:  
A query is a read-only operation done with database. It is achieved using SELECT statement.

  12. Relation:

Relation or simply table is collection of records and fields. Records or rows contain different types of data whereas Fields or columns contain same type of data. Intersection of row and column forms a cell or a data value in the relation.

  13. Schema:  
A collection of object related to database.

  14. Transaction:  
A collection of one or more SQL statements which comprises a unit of work, and ends with either a commit or rollback operation.

  15. Trigger:  
It a set of procedure which is executed automatically whenever INSERT, UPDATE or DELETE statements are executed on a table or a view.

Merits of Database

  * Allows to store and retrieve data when and where ever required

  * Easy representation of data

  * No integrity issues

Points to be noted:

  * Oracle commands are not case sensitive

  * But the values inside ' ' are case sensitive

DATA DEFINITION LANGUAGE (DDL)

The DDL commands are used to interact with database. It is used to create, modify and delete relations in the database.

The commands used are CREATE, ALTER, DROP and TRUNCATE

CREATING TABLE

Tables are basic object in the database. To create a new relation on database the following syntax is implied.

Syntax:

CREATE TABLE <tablename> (<colname1> datatype1...);

Example:

SQL> create table EMP1(

2 EMPNO number(4)not null,

3 EMPNAME varchar2(30)not null,

4 JOB varchar2(10),

5 MGR number(4),

6 HIREDATE date,

7 SAL number (7,2),

8 DEPTNO number(2) );

Table created.

The 'not null' keyword will be discussed in later Chapter.

TABLE DESCRIPTION

To view the table description. In other words, it helps us to know about the detailed information about the table.

Syntax:

DESC <tablename>;

Example:

SQL>desc emp1;

Name Null? Type

\----------------------------------------- -------- \----------------------------

EMPNO NOT NULL NUMBER(4)

EMPNAME NOT NULL VARCHAR2(30)

JOB VARCHAR2(10)

MGR NUMBER(4)

HIREDATE DATE

SAL NUMBER(7,2)

DEPTNO NUMBER(2)

MODIFYING TABLE AND COLUMN DEFINITION

To modify the table fields by adding or removing and altering its datatypes.

Syntax:

  1. To add a column

ALTER TABLE <tablename> ADD (<newcolumn> datatype);

  2. To modify column

ALTER TABLE <tablename> MODIFY (<existingcolumn> datatype);

  3. To delete a column

ALTER TABLE <tablename> DROP COLUMN <existingcolumn>;

Example:

SQL> alter table emp1 add (EDGE number(3));

Table altered.

SQL>desc emp1;

Name Null? Type

\----------------------------------------- -------- \----------------------------

EMPNO NOT NULL NUMBER(4)

EMPNAME NOT NULL VARCHAR2(30)

JOB VARCHAR2(10)

MGR NUMBER(4)

HIREDATE DATE

SAL NUMBER(7,2)

DEPTNO NUMBER(2)

EDGE NUMBER(3)

SQL> alter table emp1

2 modify (job number(15));

Table altered.

SQL>desc emp1;

Name Null? Type

\----------------------------------------- -------- \----------------------------

EMPNO NOT NULL NUMBER(4)

EMPNAME NOT NULL VARCHAR2(30)

JOB NUMBER(15)

MGR NUMBER(4)

HIREDATE DATE

SAL NUMBER(7,2)

DEPTNO NUMBER(2)

EDGE NUMBER(3)

RENAMING A TABLE

The name of the table can be changed from one name to another by using the following syntax

Syntax:

RENAME <oldtable> TO <newtable>;

Example:

SQL>rename emp1 to employee;

Table renamed.

SQL>desc emp1;

ERROR:

ORA-04043: object emp1 does not exist

SQL>desc employee;

Name Null? Type

\----------------------------------------- -------- \----------------------------

EMPNO NOT NULL NUMBER(4)

EMPNAME NOT NULL VARCHAR2(30)

JOB NUMBER(15)

MGR NUMBER(4)

HIREDATE DATE

SAL NUMBER(7,2)

DEPTNO NUMBER(2)

EDGE NUMBER(3)

READ ONLY TABLES

This is an enhanced feature in 11g. It allows tables to be used for read only purpose. By setting a table to Read-Only we can restrict a user to modify the content of the table thereby protecting the values in the relation.

Syntax:

ALTER TABLE <tablename> READ ONLY;

ALTER TABLE <tablename> READ WRITE;

Example:

SQL> alter table employee read only;

Table altered.

SQL> insert into employee VALUES(2);

insert into employee VALUES(2)

*

ERROR at line 1:

ORA-12081: update operation not allowed on table "USER328"."EMPLOYEE"

SQL> UPDATE employee set id = 2;

UPDATE employee set id = 2

*

ERROR at line 1:

ORA-12081: update operation not allowed on table "USER328"."EMPLOYEE"

DELETING A TABLE

To delete the table permanently from the database. But in real fact the dropped table is kept in an in-built recycle bin, which can recover later. To delete table permanently additional keyword PURGE is used.

Syntax:

  1. Temporary delete

DROP TABLE <tablename>;

  2. Permanent delete

DROP TABLE <tablename> PURGE;

Example:

SQL>DROP TABLE employee;

Table dropped.

DATA MANIPULATION LANGUAGE (DML)

The DDL commands are used to interact with database. It is used to modify the content of relations in the database.

The commands used are SELECT, INSERT, UPDATE and DELETE. Note that SELECT command is Data Query Language (DQL) but it can be categorized under DML also.

INSERTING INTO TABLE

When adding a new row, we must ensure that the datatype of the value and the column matches the insert of data in relation. Insert can be performed in three ways.

Syntax:

  1. INSERT INTO <table> (col1, col2...) VALUES (val1, val2...);

  2. INSERT INTO <table> VALUES (val1, val2...);

  3. INSERT INTO <table> VALUES ('&col1', '&col2'...);

Example:

Type 1

SQL> insert into emp (empno,ename,job,mgr,hiredate,sal,deptno)

2 values (3737,'priya','officer','7777','07-mar-09',34000,07);

1 row created

Type 2

SQL> insert into empvalues(2323,'anitha','officer',5454,'09-jan-08',42000,09);

1 row created.

SQL> insert into empvalues(5352,'retish','secretary',5555,'09-jun-09',20000,08);

1 row created.

SQL> insert into empvalues(5332,'rocky','assit',5555,'08-jan-09',13000,07);

1 row created.

SQL> select * from emp;

EMPNO ENAME JOB MGR HIREDATE SAL DEPTNO

\---------- -------------- \--------- --------- ---------------- --------- \----------------

2323 anitha officer 5454 09-JAN-08 42000 9

5352 retish secretary 5555 09-JUN-09 20000 8

5332 rocky assit 5555 08-JAN-09 13000 7

Type 3

SQL> insert into emp values

2 ('&empno','&ename','&job','&mgr','&hiredate','&sal','&deotno');

Enter value for empno: 7575

Enter value for ename: karthi

Enter value for job: officier

Enter value for mgr: 3337

Enter value for hiredate: 07-jul-2007

Enter value for sal: 72000

Enter value for deotno: 07

old 2: ('&empno','&ename','&job','&mgr','&hiredate','&sal','&deotno')

new 2: ('7575','karthi','officier','3337','07-jul-2007','72000','07')

1 row created.

UPDATE THE TABLE

The update statement is used to modify the content of the relation contained in the database. The update can either be of Tuple (row) or Column update.

Syntax:

  1. UPDATE <table> SET <col1>=<val1>, <col2>=<val2>... [WHERE clause]

  2. UPDATE <table> SET <col>=<val> [WHERE clause]

Example:

  1. TUPLE UPDATE

SQL> update emp set

2 job='assit',deptno=20,sal=sal+3000

3 whereename='rocky';

1 row updated.

  2. COLUMN UPDATE

SQL> update emp set

2 sal=sal*1.5

3 wheredeptno=7;

1 row updated.

SELECT CONTENT OF TABLE

As such entering data into the database is of no use. Hence to see what the content of the relation are, SELECT query is used. This is the most often used query in the database. Select can be of various forms and clauses

Syntax:

  1. SELECT * FROM <table>;  
To select entire record from the table

  2. SELECT <col> FROM <table>;  
To select a particular column from the relation

  3. SELECT <col1>, <col2>... FROM <table>;  
To select multiple column from the relation

  4. SELECT <col><expr><val> FROM <table>;  
To apply a particular expression to a column without affecting the content of the relation

  5. SELECT DISTINCT <col1> FROM <table>;  
To select only the unique values from the relation

  6. SELECT * FROM <table> ORDER BY <column>;  
To select particular columns which is ordered by the column specified in the query

  7. SELECT * FROM <table> ORDER BY <column> ASC;  
To select the contents of table with respect ot the content of column in query in ascending order

  8. SELECT * FROM <table> ORDER BY <column> DESC;  
To select the contents of table with respect ot the content of column in query in descending order

  9. SELECT <column> FROM <table> WHERE (<condition1> OR <condition2>);

  10. SELECT <column> FROM <table> WHERE (<condition1> AND <condition2>);

  11. SELECT <column> FROM <table> WHERE <col> IN (<val1>, <val2>...);

  12. SELECT <column> FROM <table> WHERE <col> BETWEEN <val1> AND <val2>;

Example:

SQL> select * from emp;

EMPNO ENAME JOB MGR HIREDATE SAL DEPTNO

\---------- -------------- \--------- --------- ---------------- --------- \----------------

2323 anitha officer 5454 09-JAN-08 42000 9

5352 retish secretary 5555 09-JUN-09 20000 8

5332 rocky assit 5555 08-JAN-09 19500 7

SQL> select ename from emp;

ENAME

\------------------------------

anitha

retish

rocky

DISTINCT

SQL> select distinct mgr from emp;

MGR

\----------------

5454

5555

OR

SQL> select ename from emp where (mgr=5555 or deptno=07);

ENAME

\------------------------------

retish

rocky

AND

SQL> select ename from emp where (mgr=5555 and deptno=07);

ENAME

\------------------------------

rocky

IN

SQL> select ename ,sal

2 fromemp

3 whereempno in

4 (2323,5555);

ENAME SAL

\------------------------------ \----------

anitha 42000

SQL> select ename ,sal

2 from emp

3 where empno in

4 (2323,7575);

ENAME SAL

\------------------------------ \----------

anitha 42000

BETWEEN

SQL> select ename ,sal

2 fromemp

3 wheresl between 25000 and 50000;

ENAME SAL

\------------------------------ \----------

anitha 42000

TUPLE DELETION

To delete existing records from the table DELETE along with WHERE clause is used to delete particular tuple or record.

Syntax:

DELETE FROM <table> [WHERE clause]

Example:

SQL> delete from emp

2 wheredeptno=8;

1 row deleted.

DATA CONTOL LANGUAGE (DCL)

The DDL commands are used to control the activities performed in database. It is used to create, modify and revoke privileges from user. The commands used are CONNECT, GRANT and REVOKE

CREATING USER

This command is used to create a new user for the database.

Syntax:

CREATE USER <uname> IDENTIFIED BY <pwd>;

Example:

SQL> create user gokul identified by mine;

User created.

CONNECTING TO DATABASE

This command is used to connect a new user for the database.

Syntax:

CONNECT <uname>/<pwd>;

Example:

SQL>connect user328/user328@oracle11g

GRANT COMMAND

This command is used to issue appropriate privileges to a particular user.

Syntax:

  1. GRANT <privileges> ON<objectname> TO <user>;

  2. GRANT CREATE TABLE TO <uname>;

  3. GRANT SELECT ON <objectname> TO <uname>;

  4. GRANT ALL PRIVILEGES ON <objectname> TO <uname>;

Example:

SQL> grant create table to gokul;

Grant succeeded.

SQL> create table tab(name char(5),ph_no number(6));

Table created.

SQL> create table tab2(id number(4),place char(10));

Table created.

SQL> select * from tab2;

no rows selected

SQL> insert into tab2 values(1111,'chennai');

1 row created.

SQL> insert into tab2 values(2222,'mumbai');

1 row created.

SQL> insert into tab2 values(3333,'delhi');

1 row created.

SQL> select * from tab2;

ID PLACE

\----------- -------------

1111 chennai

2222 mumbai

3333 delhi

SQL> select * from tab2;

no rows selected

SQL> grant select on tab2 to gokul;

Grant succeeded.

SQL> select * from tab2;

ID PLACE

\----------- -------------

1111 chennai

2222 mumbai

3333 delhi

SQL> grant update

2 on tab2

3 to gokul;

Grant succeeded.

SQL> grant insert

2 on tab2

3 to gokul;

Grant succeeded.

Or

SQL> grant all privileges on tab2 to gokul;

Grant succeeded.

SQL> insert into tab2 values(4444,'calcutta');

1 row created.

SQL> update tab2 set place='bombay' where id=2222;

1 row updated.

SQL> select * from tab2;

ID PLACE

\----------- -------------

1111 chennai

2222 bombay

3333 delhi

4444 calcutta

REVOKE COMMAND

This command is used to remove appropriate privileges to a particular user.

Syntax:

  1. REVOKE <privileges> ON<objectname> FROM <user>;

  2. REVOKE CREATE TABLE FROM <uname>;

  3. REVOKE UPDATE ON <objectname> FROM <uname>;

  4. REVOKE ALL PRIVILEGES ON <objectname> FROM <uname>;

Example:

SQL> revoke select on tab2 from gokul;

Revoke succeeded.

SQL> select * from tab2;

no rows selected

SQL> revoke create table from gokul;

Revoke succeeded.

SQL> create table tab (id number(5));

create table tab (id number(5))

*

ERROR at line 1:

ORA-01031: insufficient privileges

SQL> revoke update on tab2 from gokul;

Revoke succeeded.

SQL> revoke insert on tab2 from gokul;

Revoke succeeded.

Or

SQL> revoke all privileges from gokul;

Revoke succeeded.

WORKING WITH CONSTRAINTS

Constraints are condition or rules that are used to limit the type of data that can go into a table. Such constraints are also called as integrity constraints and are specified in create and alter statements. The constraints can be classified broadly into three categories, they are

  1. Domain integrity constraints

    * NOT NULL

    * DEFAULT

    * CHECK

  2. Entity integrity constraints

    * UNIQUE

    * PRIMARY KEY

  3. Referential integrity constraints

    * FOREIGN KEY

DOMAIN INTEGRITY CONSTRAINTS

These constraints are imposed on the column or the fields of the relation.

NOT NULL

This constraint is used to specify that a column may never hold a NULL value.

Syntax:

  1. CREATE TABLE <table> (<col1> datatype [CONSTRAINT cname] NOT NULL...);

  2. ALTER TABLE <table> MODIFY <col> datatype [CONSTRAINT cnme] NOT NULL;

Note that Modify or add clause can be used but while using modify see to that the table is empty.(This is applicable for all the constraints discussed in this chapter)

Example:

SQL> create table customers

2 (sid integer not null,

3 last_namevarchar(30)not null,

4 first_namevarchar(30));

Table created.

SQL>desc customers;

Name Null? Type

\----------------------------- -------------- \----------------------------

SID NOT NULL NUMBER(38)

LAST_NAME NOT NULL VARCHAR2(30)

FIRST_NAME VARCHAR2(30)

SQL> insert into customers values(23333,'ram','priya');

1 row created.

SQL> insert into customers values(12222,'','jai');

insert into customers values(12222,'','jai')

*

ERROR at line 1:

ORA-01400: cannot insert NULL into ("USER328"."CUSTOMERS"."LAST_NAME")

SQL> insert into customers values(12222,'raj','');

1 row created.

SQL> select * from customers;

SID LAST_NAME FIRST_NAME

\---------- \------------------------------ \------------------------------

23333 ram priya

12222 raj

DEFAULT

This constraint provide a default value to column when an INSERT INTO statement does not provide a specific value.

Syntax:

  1. CREATE TABLE <table> (<col1> datatype [CONSTRAINT cname] DEFAULT value...)

  2. ALTER TABLE <table> MODIFY <col> datatype [CONSTRAINT cnam] CHECK (column condition);

Example:

SQL> create table customers

2 (sid integer not null,

3 last_namevarchar(30)not null,

4 first_namevarchar(30) default 'jai');

SQL> insert into customers (sid,last_name) values (122,'raaju');

1 row created.

SQL> select * from customers;

SID LAST_NAME FIRST_NAME

\---------- \------------------------------ \------------------------------

23333 ram priya

12222 raj

122 raaju jai

CHECK

This constraints are imposed to validate incoming column or row at insertion time.

Syntax:

  1. CREATE TABLE <table> (col datatype CHECK <coditiom>...);

  2. ALTER TABLE <table> MODIFY <col> datatype [CONSTRAINT cname] CHECK (<col><condition>);

Example:

SQL> create table customer

2 (sid integer check(sid>100),

3 last_namevarchar(30),

4 first_namevarchar(30));

Table created.

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid: 244

Enter value for last_name: ram

Enter value for first_name: pri

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('244','ram','pri')

1 row created.

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid: 23

Enter value for last_name: uma

Enter value for first_name: ram

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('23','uma','ram')

insert into customer values('23','uma','ram')

*

ERROR at line 1:

ORA-02290: check constraint (USER328.SYS_C0013721) violated

ENTITY INTEGRITY CONSTRAINT

Constraints that are imposed on each row

UNIQUE

These constraints ensure that all value in column are distinct and NULL values is accepted.

Syntax:

  1. CREATE TABLE <table> (<col1> datatype [CONSTRAINT cname] UNIQUE...);

  2. ALTER TABLE <table> MODIFY <col> datatype [CONSTRAINT cnme] UNIQUE;

Example:

SQL> create table customer

2 (sid integer unique,

3 last_namevarchar(30),

4 first_namevarchar(30));

Table created.

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid: 23

Enter value for last_name: rad

Enter value for first_name: ree

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('23','rad','ree')

1 row created.

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid: 24

Enter value for last_name: ram

Enter value for first_name: pri

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('24','ram','pri')

1 row created.

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid: 23

Enter value for last_name: kek

Enter value for first_name: kak

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('23','kek','kak')

insert into customer values('23','kek','kak')

*

ERROR at line 1:

ORA-00001: unique constraint (USER328.SYS_C0013617) violated

PRIMARY KEY

A primary key is used to uniquely identify each row in a table and also will not allow a NULL value. More than one primary key is possible. Such situation of multiple key are called as composite key.

Primary Key=Unique + Not Null

Syntax:

  1. CREATE TABLE <table> (<col1> datatype [CONSTRAINT cname] PRIMARY KEY...);

  2. ALTER TABLE <table> MODIFY [COSTRAINT cname] PRIMARY KEY (<col>);

Example:

Sample 1:

SQL> create table customer

2 (sid integer ,

3 last_namevarchar(30),

4 first_namevarchar(30),

5 primary key(sid));

Table created.

SQL>desc customer

Name Null? Type

\--------------------------------- ---------------- \----------------------------

SID NOT NULL NUMBER(38)

LAST_NAME VARCHAR2(30)

FIRST_NAME VARCHAR2(30)

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid: 34

Enter value for last_name: ram

Enter value for first_name: pri

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('34','ram','pri')

1 row created.

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid: 54

Enter value for last_name: oop

Enter value for first_name: raj

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('54','oop','raj')

1 row created.

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid: 54

Enter value for last_name: tem

Enter value for first_name: temp

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('54','tem','temp')

insert into customer values('54','tem','temp')

*

ERROR at line 1:

ORA-00001: unique constraint (USER328.SYS_C0013728) violated

SQL> insert into customer values('&sid','&last_name','&first_name');

Enter value for sid:

Enter value for last_name: trim

Enter value for first_name: trimi

old 1: insert into customer values('&sid','&last_name','&first_name')

new 1: insert into customer values('','trim','trimi')

insert into customer values('','trim','trimi')

*

ERROR at line 1:

ORA-01400: cannot insert NULL into ("USER328"."CUSTOMER"."SID")

Sample 2:

SQL> create table customer

2 (sid integer ,

3 last_namevarchar(30),

4 first_namevarchar(30));

Table created.

SQL>desc customer;

Name Null? Type

\--------------------------------- ---------------- \----------------------------

SID NUMBER(38)

LAST_NAME VARCHAR2(30)

FIRST_NAME VARCHAR2(30)

SQL> alter table customer add primary key (sid);

Table altered.

SQL>desc customer;

Name Null? Type

\--------------------------------- ---------------- \----------------------------

SID NOT NULL NUMBER(38)

LAST_NAME VARCHAR2(30)

FIRST_NAME VARCHAR2(30)

REFERENTIAL INTEGRITY CONSTRAINT

Constraints imposed to ensure the integrity of data or only value that are supposed to appear in database are permitted.

FOREIGN KEY

A foreign key is a field that points to the primary key of another table. The purpose is to ensure referential integrity of data.

Syntax:

  1. CREATE TABLE <table> (<col1> datatype [CONSTRAINT cname] REFERENCES <parentTable><parentCol>...);

  2. CREATE TABLE <table> (<col1> datatype [CONSTRAINT cname] REFERENCES <parentTable><parentCol> ON DELETE CASCADE...);

Example:

SQL>desc customer;

Name Null? Type

\--------------------------------- ---------------- \----------------------------

SID NOT NULL NUMBER(38)

LAST_NAME VARCHAR2(30)

FIRST_NAME VARCHAR2(30)

SQL> create table orders

2 (order_id integer primary key,

3 order_date date,

4 customer_sid integer references customer(sid),

5 amount number(8,2));

Table created.

SQL> insert into orders values('&order_id','&order_data','&customer_sid','&amount');

Enter value for order_id: 545

Enter value for order_data: 30-sep-2009

Enter value for customer_sid: 34

Enter value for amount: 9000

old 1: insert into orders values('&order_id','&order_data','&customer_sid','&a

mount')

new 1: insert into orders values('545','30-sep-2009','34','9000')

1 row created.

SQL> insert into orders values('&order_id','&order_data','&customer_sid','&amoun

t');

Enter value for order_id: 506

Enter value for order_data: 11-aug-2009

Enter value for customer_sid: 54

Enter value for amount: 3000

old 1: insert into orders values('&order_id','&order_data','&customer_sid','&a

mount')

new 1: insert into orders values('506','11-aug-2009','54','3000')

1 row created.

SQL> insert into orders values('&order_id','&order_data','&customer_sid','&amoun

t');

Enter value for order_id: 545

Enter value for order_data: 30-sep-2009

Enter value for customer_sid: 567

Enter value for amount: 9000

old 1: insert into orders values('&order_id','&order_data','&customer_sid','&a

mount')

new 1: insert into orders values('545','30-sep-2009','567','9000')

insert into orders values('545','30-sep-2009','567','9000')

*

ERROR at line 1:

ORA-02291: integrity constraint (USER328.SYS_C0013767) violated - parent key

not found

SQL> select * from orders;

ORDER_ID ORDER_DAT CUSTOMER_SID AMOUNT

\--------------- \------------------ ----------------------- \----------------

545 30-SEP-09 34 9000

506 11-AUG-09 54 3000

SQL> select * from customer;

SID LAST_NAME FIRST_NAME

\---------- \------------------------------ \------------------------------

77 sidbalu

34 ram pri

54 oop raj

69 joe don

55 sam god

SQL> delete from customer where last_name='sid';

1 row deleted.

SQL> delete from customer where last_name='oop';

delete from customer where last_name='oop'

*

ERROR at line 1:

ORA-02292: integrity constraint (USER328.SYS_C0013767) violated - child record

found

SQL> delete from orders where customer_sam=55 ;

1 row deleted.

SQL> select * from orders;

ORDER_ID ORDER_DAT CUSTOMER_SID AMOUNT

\--------------- \------------------ ----------------------- \----------------

506 11-AUG-09 54 3000

SQL> select * from customer;

SID LAST_NAME FIRST_NAME

\---------- \------------------------------ \------------------------------

34 ram pri

54 oop raj

69 joe don

SQL> delete from customer where last_name='joe';

1 row deleted.

JOINS

The purpose of a join concept is to combine data spread across the tables. A join is can be achieved using 'where', 'on', 'using' clause which combines specified rows of table. The type of join are,

  1. Simple Join

    1. Equi-join

    2. Non Equi-join

  2. Self-Join

  3. Inner Join

  4. Natural Join

  5. Cross Join

  6. Outer Join

    1. Left Outer Join

    2. Right Outer Join

    3. Full Join

General Syntax:

SELECT <columns> FROM <table1>, <table2> WHERE <logicalexpr>;

SIMPLE JOIN

It is the most common type of join which receives two tables which has a common column. They can be further classified as,

  1. EQUI-JOIN

A join which contains an equal to '=' operator in join condition is said to be equi-join.

Syntax:

SELECT * FROM <table1>, <table2> WHERE <table1>.<col1>=<table2>.<col2>;

  2. NON EQUI-JOIN

A join which contains an operator other than '=' such as <, >, >=, <= in the join condition.

Syntax:

SELECT * FROM <table1>, <table2> WHERE <table1>.<col1> [condition] <table2>.<col2>;

Where [condition] can be <, >, >=, <=

SELF JOIN

The joining of a table o itself is known as self-join. It joins one row in a table with another. It can compare each row of table to itself and also with other rows of same table.

Syntax:

SELECT * FROM <table1><var1>, <table1><var2> WHERE <var1>.<column1> [condition] <var2>.<column2>;

<var1> and <var2> are temporary variables for the <table1>

INNER JOIN

A join which displays all the records that are matched on any two table is called Inner join.

Syntax:

SELECT * FROM <table1> INNER JOIN <table2> USING (<col>);

NATURAL JOIN

A join that compares all common columns on both tables is said to be natural join.

Syntax:

SELECT * FROM <table1> NATURAL JOIN <table2>;

CROSS JOIN

A join that gives cross product of both tables is said to be cross join.

Syntax:

SELECT * FROM <table1> CROSS JOIN <table2>;

OUTER JOIN

It extends the result of a simple join. An outer join returns all the rows returned by simple join as well as those rows from one table that do not match any row from the table. The symbol (+) represent the outer join.

  1. LEFT OUTER JOIN

A join which displays all the matching records and records which are in left hand side table and those that are not in right side of table.

Syntax:

SELECT * FROM <table1>, <table2> WHERE <table1>.<column> (+)=<table2>.<column>;

  2. RIGHT OUTER JOIN

A join which displays all the matching records and records which are in right hand side table and those that are not in left side of table.

Syntax:

SELECT * FROM <table1>, <table2> WHERE <table1>.<column> = <table2>.<column>(+);

  3. FULL JOIN

A join which displays all matching record and non-matching record from both the table.

Syntax:

SELECT * FROM <table1> FULL OUTER JOIN <table2> ON (<table1>.<column>=<table2>.<column>);

Example:

Table1 Description

SQL>desc tab1;

Name Null? Type

\-------------------- \--------------------- ---------------------------

ROLLNO NUMBER(4)

NAME VARCHAR2(10)

Table1 Insertion

SQL> insert into tab1 values('3444','raj');

1 row created.

SQL> insert into tab1 values('5666','das');

1 row created.

SQL> insert into tab1 values('6777','kak');

1 row created.

SQL> insert into tab1 values('6788','riya');

1 row created.

SQL> insert into tab1 values('2333','ram');

1 row created.

SQL> select * from tab1;

ROLLNO NAME

\--------------- \--------------

3444 raj

5666 das

6777 kak

6788 riya

2333 ram

Table2 Description

SQL>desc tab2;

Name Null? Type

\------------------------ \----------------- ----------------------------

ROLLNO NUMBER(4)

MARKS NUMBER(3)

Table2 Insertion

SQL> insert into tab2 values('3444','78');

1 row created.

SQL> insert into tab2 values('6777','45');

1 row created.

SQL> insert into tab2 values('2333','87');

1 row created.

SQL> insert into tab2 values('8779','98');

1 row created.

SQL> insert into tab2 values('5665','65');

1 row created.

SQL> select * from tab2;

ROLLNO MARKS

\--------------- \--------------

3444 78

6777 45

2333 87

8779 98

5665 65

Inner Join

SQL> select * from

2 tab1,tab2

3 where tab1.rollno=tab2.rollno;

ROLLNO NAME ROLLNO MARKS

\----------------- \------------- ---------------- ------------------

3444 raj 3444 78

6777 kak 6777 45

2333 ram 2333 87

SQL> select tab1.name,tab2.marks

2 from tab1,tab2

3 where tab1.rollno=tab2.rollno;

NAME MARKS

\------------ \-----------------

raj 78

kak 45

ram 87

Outer Join

Left Outer Join

SQL> select * from

2 tab1,tab2

3 where tab1.rollno(+)=tab2.rollno;

ROLLNO NAME ROLLNO MARKS

\---------------- \------------- -------------- -------------

3444 raj 3444 78

6777 kak 6777 45

2333 ram 2333 87

5665 65

8779 98

SQL> select tab1.name,tab2.marks

2 from tab1,tab2

3 where tab1.rollno(+)=tab2.rollno;

NAME MARKS

\------------ \---------------

raj 78

kak 45

ram 87

65

98

Right Outer Join

SQL> select * from

2 tab1,tab2

3 where tab1.rollno=tab2.rollno(+);

ROLLNO NAME ROLLNO MARKS

\---------------- \------------- -------------- -------------

3444 raj 3444 78

6777 kak 6777 45

2333 ram 2333 87

5666 das

6788 riya

SQL> select tab1.name,tab2.marks

2 from tab1,tab2

3 where tab1.rollno=tab2.rollno(+);

NAME MARKS

\------------ \---------------

raj 78

kak 45

ram 87

das

riya

OPERATORS

Oracle allows several types of operator they are arithmetic, comparison, set and logical operators.

Arithmetic operators | \+ - * /

---|---

Comparison operators | = != <><= >=

Between, like, is null, not between, not like

Logical operators | And, or, not

Set operators | Union, Union all, Intersect, Minus

Example:

TABLE DESCRIPTION

SQL> CREATE TABLE tab1

2 (name varchar2(20),m1 number(2),m2 number(2),m3 number(2));

Table created.

SQL> SELECT * FROM tab1;

NAME M1 M2 M3 TOTAL

\-------------------- \---------- ---------- ---------- ------------

Babu 70 88 98 256

Ravi 78 99 98 275

Rajesh 98 99 99 296

Kavi 59 79 60 198

Ram 50 90 70 210

Ramu 35 40 50 125

6 rows selected.

SQL> CREATE TABLE tab2(rollno number(3) UNIQUE,name varchar2(20));

Table created.

SQL> SELECT * FROM tab2;

ROLLNO NAME

\--------------- \----------------

100 Babu

101 Banu

102 Ganesh

103 Goutham

104 Kavi

105 Rajesh

106 Ram

107 Ramu

108 Ravi

109 Yuvaraj

110 Zakir

111

11 rows selected.

1) ARITHMETIC OPERATORS

SQL> SELECT name,m1+m2+m3 total FROM tab1;

NAME TOTAL

\--------------- \--------------

Babu 256

Ravi 275

Rajesh 296

Kavi 198

Ram 210

Ramu 125

6 rows selected.

SQL> SELECT name,total/3 avg FROM tab1;

NAME AVG

\-------------- \----------------

Babu 85.3333333

Ravi 91.6666667

Rajesh 98.6666667

Kavi 66

Ram 70

Ramu 41.6666667

6 rows selected.

2) COMPARISON OPERATORS

SQL> SELECT name FROM tab1

2 WHERE m3>=m1;

NAME

\--------------------

Babu

Ravi

Rajesh

Kavi

Ram

Ramu

6 rows selected

BETWEEN

SQL> SELECT name FROM tab1

2 WHERE m1 BETWEEN 60 AND 90;

NAME

\--------------------

Babu

Ravi

IN

SQL> SELECT name FROM tab1

2 WHERE m1 IN(50,60,70,80,90);

NAME

\--------------------

Babu

Ram

LIKE

SQL> SELECT * FROM tab1

  2. WHERE name LIKE 'R%';

  3.

NAME M1 M2 M3 TOTAL

\-------------------- \---------- ---------- ---------- ------------

Ravi 78 99 98 275

Rajesh 98 99 99 296

Ram 50 90 70 210

Ramu 35 40 50 125

IS NULL

SQL> select * from tab2

2 WHERE name IS NULL;

ROLLNO NAME

\----------------- \--------------

111

NOT BETWEEN

SQL> SELECT * FROM tab1

2 WHERE m1 NOT BETWEEN 50 AND 70;

NAME M1 M2 M3 TOTAL

\-------------------- \---------- ---------- ---------- ------------

Ravi 78 99 98 275

Rajesh 98 99 99 296

Ramu 35 40 50 125

3) LOGICAL OPERATORS

SQL> SELECT * FROM tab1

2 WHERE NOT m2>m3;

NAME M1 M2 M3 TOTAL

\-------------------- \---------- ---------- ---------- ------------

Babu 70 88 98 256

Rajesh 98 99 99 296

Ramu 35 40 50 125

SQL> SELECT * FROM tab1

2 WHERE m2>m3 AND total>200;

NAME M1 M2 M3 TOTAL

\-------------------- \---------- ---------- ---------- ------------

Ravi 78 99 98 275

Ram 50 90 70 210

SQL> SELECT * FROM tab1

2 WHERE m3>m2 OR total>200;

NAME M1 M2 M3 TOTAL

\-------------------- \---------- ---------- ---------- ------------

Babu 70 88 98 256

Ravi 78 99 98 275

Rajesh 98 99 99 296

Ram 50 90 70 210

Ramu 35 40 50 125

4) SET OPERATORS

UNION

SQL> SELECT name FROM tab1 UNION SELECT name FROM tab2;

NAME

\--------------------

Babu

Banu

Ganesh

Goutham

Kavi

Rajesh

Ram

Ramu

Ravi

Yuvaraj

Zakir

11 rows selected.

UNION ALL

SQL> SELECT name FROM tab1 UNION ALL SELECT name FROM tab2;

NAME

\--------------------

Babu

Ravi

Rajesh

Kavi

Ram

Ramu

Babu

Banu

Ganesh

Goutham

Kavi

NAME

\--------------------

Rajesh

Ram

Ramu

Ravi

Yuvaraj

Zakir

17 rows selected.

SQL> SELECT name FROM tab1 INTERSECT SELECT name FROM tab2;

NAME

\--------------------

Babu

Kavi

Rajesh

Ram

Ramu

Ravi

6 rows selected.

INTERSECT

SQL> SELECT name FROM tab1 INTERSECT SELECT name FROM tab2;

NAME

\--------------------

Babu

Kavi

Rajesh

Ram

Ramu

Ravi

6 rows selected.

MINUS

SQL> SELECT name FROM tab2 MINUS SELECT name FROM tab1;

NAME

\--------------------

Banu

Ganesh

Goutham

Yuvaraj

Zakir

VIEWS

A view is otherwise known as a Virtual table. It is tailored representation of the data contained in one or more table and can also be said a restricted view to the data in the table. It's also called as stored query. The table upon which a view is created is called as base table

There are two types of views,

  * Horizontal view (on rows)

  * Vertical view (on column)

OPERATION ON VIEWS

  1. CREATING A VIEW  
To create a new view in the database for an existing table.  
Syntax:  
CREATE VIEW <view> AS SELECT <col1>, <col2>... FROM <basetable> [WHERE clause];

  2. DESCRIBING THE VIEW  
To view a detailed description of the view  
Syntax:  
DESC <view>;

  3. SELECTING RECORDS FROM VIEW  
To view the contents of the view. Similar to the operation on tables. But note that the data to be moved to view are computed on each select statement.  
Syntax:  
SELECT * FROM <view>;

  4. UPDATING VIEW  
To update the rows in the view. Note that the updating of value in view causes updating in base table. If the updating value causes the view to violate its constraints then its removed from view but still avails in the base table.  
Syntax:  
UPDATE <view> SET <col>=<value> [WHERE clause];

  5. DROPPING THE VIEW  
To delete the view from the database  
Syntax:  
DROP VIEW <view>;

TABLE DESCRIPTION

SQL> CREATE TABLE stddetails (rno number(3),regno number(5),sname varchar2(20),m1 number(2),m2 number(2),m3 number(2

),tot number(3),avg number(5,2));

Table created.

SQL> select * from stddetails;

REGNO SNAME M1 M2 M3 TOT

\---------- \-------------------- ---------- ---------- ---------- \----------

11101 Aravind 59 76 66 201

11102 Bharath 59 54 46 159

11103 David 77 83 76 236

11104 Dinesh 73 95 54 222

11105 Deva 88 51 56 195

CREATING A VIEW

SQL> CREATE VIEW stdlist

2 AS SELECT regno,sname FROM stddetails;

View created.

CREATING A VIEW CONSTRAINTS

SQL> CREATE VIEW m200

2 AS SELECT sname,tot FROM stddetails

3 WHERE tot>200;

View created.

DESCRIBING THE VIEW

SQL> DESC stdlist;

Name Null? Type

\----------------------------------------- -------- \----------------------------

REGNO NUMBER(5)

SNAME VARCHAR2(20)

SELECTING RECORDS FROM VIEW

SQL> SELECT * FROM stdlist;

REGNO SNAME

\---------- \--------------------

11101 Aravind

11102 Bharath

11103 David

11104 Dinesh

11105 Deva

SQL> SELECT * FROM m200;

SNAME TOT

\-------------------- \----------

Aravind 201

David 236

Dinesh 222

UPDATING THE VIEW

SQL> UPDATE m200

2 SETsname='Aravinda'

3 WHERE tot=201;

1 row updated.

SQL> SELECT * FROM m200;

SNAME TOT

\-------------------- \----------

Aravinda 201

David 236

Dinesh 222

SQL> SELECT * FROM stddetails;

REGNO SNAME M1 M2 M3 TOT

\---------- \-------------------- ---------- ---------- ---------- \----------

11101 Aravinda 59 76 66 201

11102 Bharath 59 54 46 159

11103 David 77 83 76 236

11104 Dinesh 73 95 54 222

11105 Deva 88 51 56 195

UPDATING THE VIEW BY VIOLATING THE CONSTRAINTS

SQL> UPDATE m200

2 SET tot=199

3 WHERE tot=201;

1 row updated.

SQL> SELECT * FROM m200;

SNAME TOT

\-------------------- \----------

David 236

Dinesh 222

DROPPING THE VIEW

SQL> DROP VIEW m200;

View dropped.

SQL> SELECT * FROM m200;

SELECT * FROM m200

*

ERROR at line 1:

ORA-00942: table or view does not exist

CHAPTER 05  
HYPERTEXT PREPROCESSOR [PHP]

PHP that refers to hypertext pre-processor is a powerful server side scripting language. (Refer chapter 01 for server side and client side scripting techniques). The Hypertext pre-processor will provide technologies to implement the dynamic webpage. The client side interaction form is provided by the HTML. Now, by using forms user can enter the form details and then he has to click the submit button. At the end of submission, the user form fields are validated by using special sort of script called "Javascript" (Chapter 03 in our book) then after validation, if the validation returns success result, then the form fields are stored into the database. (Hence, we studied the database concepts in Chapter 04). In this chapter, PHP explains how to store the data's into the database. Hence, by the above scenario, we conclude that, PHP is a tool-kit language for interacting with the database.

Features of PHP:

  * Used for making Dynamic web-pages.

  * PHP is powerful technique for accessing database.

  * Ultimately free resource.

  * Simple to learn and easy to implement.

Protocols supported by PHP:

  * IMAP (Internet Message Access Protocol)

  * POP3 (Post Office Protocol)

Advantages of PHP:

  * Highly integrated.

  * Simple structure of coding.

  * Code is quite similar to that of C language.

  * Provides security.

  * Gives effective front-end when combined with CSS.

Facebook Trick!!

  * The Facebook pages are created by using PHP!

  * To create an interest, before going to start PHP study, we would like to explain Facebookis implemented using PHP.

  * Can you accept n number of friend requests at a single enter? Do you think it is practically not possible at all? If you think so, change your ideology. Because, it is possible to accept or even reject all the friend requests at a single click. It's by use of simple javascript code that works on a PHP page.

Steps :

  1. Login to Facebook account.

  2. Go to the page: https://www.facebook.com/reqs.php

  3. If you want to accept all the request, paste the following code on the address bar,

  4. javascript:for( i = 0;i<document.getElementsByName("actions[accept]").

length;i++){document.getElementsByName("actions[accept]")[i].click();}void(0);

  5. If you want to reject all the request, paste the following code on the address bar,

  6. javascript:for( i = 0;i<document.getElementsByName("actions[reject]").length;i++){document.getElementsByName("actions[accept]")[i].click();}void(0);

From the above example itself, we can understand the effect of the PHP code on webpages. It's ultimately a powerful programming language! It can add, delete, update database contents;it can perform various file operations and also encrypts the data.

First Program in PHP:

As seen before in the Chapter 03, the PHP also have two types of implementation. They are,

  1. Implementation by a separate file (with .php extension)

  2. Implementation into the HTML (embedding) file.

The PHP code starts with <? and ends with ?>. All the php codings will go around these two symbols. We have to install the XAMPP (the PHP development environment apache) before performing codings with PHP. Note that, PHP is case-sensitive.

Example: Welcome Program in PHP:

<html>

<head>

<body>

<?php

echo "Welcome to the PHP Program";

?>

</body>

</head>

</html>

Result: Prints "Welcome to PHP Program on the web-browser.

Comment Lines in PHP:

There are two different types of comment lines available in PHP. They are,

  1. Single Line Comment.

  2. Multi Line Comment.

Single Line Comment:

  * Single line comments are used for specifying the description about the program in a single line.

  * Syntax: // Comment goes here...

Example:

<html>

<head>

<body>

<?php

//php code goes here...

echo "Welcome to the PHP Program";

?>

</body>

</head>

</html>

Multi Line Comment:

  * Multi line comments are used for specifying the description about the program in more than two lines (or) interms of paragraph.

  * Syntax: /* Line 1

Line 2 */

Example:

<html>

<head>

<body>

<?php

/* This is a simple program

that prints "Welcome" on the screen" */

echo "Welcome to the PHP Program";

?>

</body>

</head>

</html>

Data types of PHP:

Data Type Name | Explanation

---|---

Integer | Represents a non-decimal number.

Example : 45

Boolean | Represent 0 and 1 states

Example: True/False

NULL | Represents single state

Strings | Collection of character(s)

Example: "Cartesian"

Arrays | Collection of elements in contiguous memory locations

Example:

Double | Defines the decimal number. Example: 4.56

Variables:

  * Variables are used for storing some data. It acts as a box that holds some items.

Rules for writing a variable in PHP:

  * Variables should be started with a special symbol called as '$' followed by variable name. +, %, (, ), , are not allowed.

  * It should not start with number/underscore.

Syntax:

$variable_name = value;

Example:

<html>

<head>

<body>

<?php

$a=5;

echo "a value is $a";

?>

</body>

</head>

</html>

Result:a value is 5.

Case Study: Some Simple Errors:

<html>

<head>

<body>

<?php

$6a=5; //Variable name started with a number.

echo "a value is $a";

?>

</body>

</head>

</html>

Result: (Error 1)

Parse error: syntax error, unexpected '6' (T_LNUMBER), expecting variable (T_VARIABLE) or '$' in C:\Program Files\xamp\htdocs\wa.php on line 5

Escape sequences in PHP:

  * Escape sequences are one which are not actually printed as it is on the screen rather it is used for alignment operations at best cases.

  * Some of the escape sequences are \n (or) "<br">– for new line, \t – used for implementation of tab space, \ " – printing double quotes on the screen, \ ' – printing single quote on the screen, \\\ - print single slash on screen, \$ - prints dollar on the screen.

Implementation Example:

<html>

<head>

<body>

<?php

echo "\$5000 is requested";

echo "<br>";

echo "\\\t is used for tab space";

echo "The tab space \t gives the gap like this";

?>

</body>

</head>

</html>

Result:

$5000 is requested  
\t is used for tab space. The tab space gives the gap like this

Case Study: Some Simple Errors!

Error 2: If you missed to use ?> at the end of PHP code, then it results to the following error:

Parse error: syntax error, unexpected '?' in C:\Program Files\xamp\htdocs\wa.php on line 9

Error 3: If the semi-colon is not closed in any of the line, then it results to the following error:

Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';' in C:\Program Files\xamp\htdocs\wa.php on line 6

Operators:

Operators are one which is used for operating different operands. The following operators are available in the PHP. They are,

  * Arithmetic Operator

  * Comparison Operator

  * Assignment Operator

  * Logical Operator

Arithmetic Operators:

Operator | Description

---|---

+ | Performs addition operation on given operands.

- | Performs subtraction.

* | Multiply the given operand values

/ | Performs simple division.

% | Modulus Operation which gives the remainder as the result.

++ | Increments value by 1

\-- | Decrements value by 1

Example:

<html>

<head>

<body>

<?php

$a=5;

$b=10;

echo $a+$b;

echo"<br>";

echo $a-$b;

echo"<br>";

echo $a*$b;

echo"<br>";

echo $a/$b;

echo"<br>";

echo $a%$b;

echo"<br>";

echo $a++;

echo"<br>";

echo $b++;

?>

</body>

</head>

</html>

Result:

15  
-5  
50  
0.5  
5  
5  
10

Logical Operators:

Operator | Description

---|---

and | If the both of the operands are true then the condition will returns a true value.

or | It is not necessary that both operands should be true, if any one of the operand is true, then the result is true.

&& | Returns true value if both the operands are non-zero.

|| | Returns true value if any one of the operands is non-zero.

! | Used for complementing purpose, if result is true, then !(result) returns false value.

Comparison Operator:

Operator | Description

---|---

!= | Checks whether the operands are not same.

> | Checks whether left operand is greater or not.

< | Checks whether left operand is lesser than right one.

== | Checks for equality of both the operands.

>= | Checks whether left operand is greater than or equal to the right one.

<= | Checks if the value of left operand is less than or equal to the value of right operand.

Example:

<html>

<head>

<body>

<?php

$a=5;

$b=10;

if($a==$b)

echo "A and B are same";

else

echo "A and B are not same!";

?>

</body>

</head>

</html>

Result:

A and B are not same!

Assignment Operators:

Assignment operators will store the result into a variable after the operation is performed.

Operators | Description

---|---

= | A simple assignment.

Example: $a=20; which will assign the value of the variable a as 20.

+= | Assignment performed after addition operation.

Example: a+=20, this code will be expanded as a = a + 20 (Assume that, a is already initialized to 1) then current value of a is 21.

-= | Assignment performed after subtraction operation.

Example: a-=20, this code will be expanded as a = a - 20 (Assume that, a is already initialized to 21) then current value of a is 1.

*= | Assignment performed after multiplication operation.

Example: a*=10, this code will be expanded as a = a *10 (Assume that, a is already initialized to 10) then current value of a is 100.

/= | Assignment performed after addition operation.

Example: a/=20, this code will be expanded as a = a /20 (Assume that, a is already initialized to 10) then current value of a is 0.5.

Example:

<html>

<head>

<body>

<?php

$a=5;

$b=10;

$a+=5;

$b*=3;

echo "Now the A value is".$a;

echo "Now the B value is".$b;

?>

</body>

</head>

</html>

Result:

Now the A value is 10

Now the B value is 30

Order of Precedence!

The above figure explains the order of precedence of various operators in PHP. The unary operator has highest priority and assignment operator has lowest precedence.

The conditional, looping statements are very similar to the C programming. The main goal of PHP is to connect database with the HTML. Let us see now to getting connected?

Connecting database:

Syntax:

<?php

mysql_connect("localhost", "root", "db_password") or die(mysql_error());

mysql_select_db("database_name") or die(mysql_error());

?>

Example:

<?php

mysql_connect("localhost", "root", "2211") or die(mysql_error());

mysql_select_db("hari") or die(mysql_error());

?>

That's all ! If you clear with the above syntax you can easily understand the concepts of PHP by studying the upcoming examples.

Project 1:

Create a Project on PHP for a question paper setting company, which will sets a question paper for Python programming language. The question paper setting software should generate 5 questions randomly from a set of questions.

Hint:

  1. Create UI to store the questions.

  2. Randomly generate questions.

Source Code:

qes.php

<< This serves as a front – end for entering the question >>

<html>

<form action="i1.php" method="post"><center>

<h3>Enter question here:<br><center>

<textarea rows="6" cols="50" name="e"></textarea><br><br>

<input type="submit"/>

<body bgcolor="lightgreen">

i1.php

<< saving the questions to the database>>

<?php

$e=$_POST['e'];

$e=nl2br($e);

mysql_connect("localhost", "root", "2211") or die(mysql_error());

mysql_select_db("hari") or die(mysql_error());

mysql_query("INSERT INTO `questions` VALUES ('$e')");

header('location:qes.php');

?>

<body bgcolor="lightgreen">

Note that: location:qes.php will hide the internal works and return the user to qes.php page in order to enter next question.

a1.php

<<For Displaying the question paper that generates random questions>>

<?php

mysql_connect("localhost", "root", "2211") or die(mysql_error());

mysql_select_db("hari") or die(mysql_error());

echo "<center>";

// printing table headers

for($i=1; $i<6; $i++)

{

$result = mysql_query("SELECT q FROM questions ORDER BY RAND() LIMIT 1 ");

$fields_num = mysql_num_fields($result);

echo "<td>$i.</td>";

echo "\n";

$row=mysql_fetch_row($result);

echo $row[0];

echo "<br>";

} ?>

</html>

Result:

Step 1: Entering the questions (Front End)

Step 2: Generating question paper (random questions):

If you are familiar with Chapter 1 – 2 – 3 – 4, you can easily frame out the meaning for the above source code.

Project 2:

The English Department of Panimalar Engineering College wants to display the student's English Exam results via PHP. By entering the registration number candidates can get their results. Code a PHP project for this scenario.

Hint: The English Examination consists of 15 sections. 15 section marks and total marks should be displayed on the console.

Source Code:

#Getting Register Number:

resul.php

<h1><CENTER>ENGLISH RESULTS</H1>

<body bgcolor="lightgreen">

<form action="fin.php" method="post">

<h2>Enter the Registration Number:<br>

<input type="text" name="reg"><br><br>

<input type="submit"/>

<input type="reset"/>

#Displaying results:

fin.php

<H2><center><H2>ENGLISH EXAM RESULTS</CENTER>

<?php

$reg=$_POST['reg'];

$dbhost = 'localhost';

$dbuser = 'root';

$dbpass = '2211';

$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn )

{

die('Could not connect: ' . mysql_error());

}

$reg=$_POST['reg'];

$sql = "SELECT * FROM tab where regno='$reg' ";

mysql_select_db('hari');

$retval = mysql_query( $sql, $conn );

if(! $retval )

{

die('Could not get data: ' . mysql_error());

}

while($row = mysql_fetch_array($retval, MYSQL_ASSOC))

{

echo "<h1>Student Name &nbsp &nbsp &nbsp &nbsp:&nbsp &nbsp &nbsp &nbsp{$row['name']} <br> ".

"<h2>Registration Number &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['regno']} <br> ".

"<h2>\----------------------------------------------------------------------------------------------------------------------<br>".

"<h3>Section I (Plural Form - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s1']} <br> ".

"Section II (Abbreviation \- Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s2']} <br> ".

"Section III (Confusables \- Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s3']} <br> ".

"Section IV (Blended Words - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s4']} <br> ".

"Section V (Syllabification - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s5']} <br> ".

"Section VI (American/British English - Marks: 5)&nbsp &nbsp &nbsp &nbsp : &nbsp &nbsp &nbsp &nbsp{$row['s6']} <br> ".

"Section VII (Compound - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s7']} <br> ".

"Section VIII (Prefix /Sufix - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s8']} <br> ".

"Section IX (Clipped Word \- Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s9']} <br> ".

"Section X (Field Match - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s10']} <br> ".

"Section XI (Passage Answer - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s11']} <br> ".

"Section XII (Question Answer - Marks: 10) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s12']} <br> ".

"Section XIII (Error Spotting - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s13']} <br> ".

"Section XIV (Map Directing - Marks: 5) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s14']} <br> ".

"Section XV (Match the following - Marks: 10) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['s15']} <br> ".

"<h1>Grand Total (Marks: 85) &nbsp &nbsp &nbsp &nbsp: &nbsp &nbsp &nbsp &nbsp{$row['tot']} <br>".

"--------------------------------------------------------------------------------------------<br>";

}

?>

<body bgcolor="yellow">

Result:

Step 1: Getting the Register Number:

Step 2: Displaying Results:

Do by yourself!

  1. Create a PHP project for implementation of simple debugging system.

  2. Create a PHP project for voting system.

  3. Create a PHP project for attendance management system.

  4. Create a PHP project for the online course reservation system.

Our Next Book...

(Object Oriented Analysis and Design)

Promo Chapter...

Promo Chapter (OOAD)

AN INTRODUCTION TO OOAD CONCEPTS

Object Oriented Analysis and Design (OOAD) is the methodology used by the software engineers to analyse and to create a blue print for the software that has to be developed. It gives a diagrammatic representation of various modules that are available in the software so that the logical relationships can be easily identified.

Object:

Object is a run-time entity or run time instance of a class. Object is anything and using that we can enhance the interaction. Consider the real time situation of Class room; the objects include Exam papers, Staff's, Students, Board, Attendance and so on. The interaction between these objects will result to a meaningful task or activity.

Advantages of Objects:

  * Data Abstraction

  * Data Encapsulation

  * Inheritance

  * Polymorphism

  * Message Passing

  * Reliability and Flexibility.

OOA: (Object Oriented Analysis)

OOA is used for the purpose of identifying and organizing the objects in the problem. OOA deals with finding objects. It is similar to analysing the requirement in the analysis phase of SDLC. (Software Development Life Cycle).

Consider that if you're creating software for the online course reservation system, then the outcome of the OOA (requirement study) is student, system etc. Hence both student and system are considered as objects for the system since it is an object oriented analysis technique.

OOD: (Object Oriented Design)

Object Oriented Design (OOD) deals with establishing the interactions between the objects in meaningful way. The OOA acts as an input to OOD. In the previous quoted example, the outcome of OOA is student and system (essential requirements) and they are treated as the objects. If the objects are defined logically with the programming language implementation it is said to be OOD.

In our example, the attributes of student includes name of student, DOB etc.. (Information about the student) and the attributes of system includes system_ID, password of the system and so on.

Both system and student is allocated with their pre-defined roles they are meant by a term called "functions". The functions of student in the system include getForm() – for getting form from system, fillForm() – submitting the form to the system and payFee() – for paying the fee to the system. Essentially, the system should also have some functions like provideForm() – to provide the form to the system,validateForm() –Validating the form and so on. This schema was identified by OOD technique.

OOAD: (Object Oriented Analysis and Design)

It is the process or activity of designing the project or software by applying the principles of OOA and OOD. The object oriented analysis and design methodology is used to identify the original logic of the system. After identifying the original logic, the construction phase takes the coding operation where the source code of the project is to be developed. It helps to find relevant objects in system.

Needs of OOAD:

  * It acts as a tool to support the software engineering activities.

  * Recovers the problem of finding the customer stated logic.

  * Notations provide more and effective communication.

UML (Unified Modelling Language)

UML was created by Grady Booch which is used for describing the logic's of the system in the diagrammatic approach. It is used to derive the blue-print of the system that has to be developed. It's not actually a programming language rather it is the visual language (logical diagrammatic representation) of the software system.Using UML standard notations, the schema or logic of the system can be visually represented.

Needs of UML:

  * Provides Pictorial representation of system to be developed.

  * Resolves the complexity problems during software design.

  * Acts as a blue-print.

UML Diagrams:

There are various UML diagrams available to represent the schema of the software system. There are three important perspectives to apply UML. They are,

  1. Conceptual View – Conceptual view is the simplest representation of the system with real world concepts. There is no logical connection established here. In our online course reservation system, the student and the system relationships are just quoted with a tag "interacts" and there is no more detailed description was stated here.

Technically, it is the view in which diagrams are drawn in such a way that they are similar to the real world.

  2. Specification View: It is the enhanced version of conceptual view where the logical descriptions are stated in the diagrammatic representation.The system components are specified with their attributes and methods in this view.

Figure: Specification View for Online Course Reservation System

  3. Implementation View: If the above system is defined with implementation in particular programming language it is called as implementation view. The programming language may be anything like C++, Perl, Python, and Java etc.

Figure: Implementation View for Online Course Reservation System (JAVA)

Types of UML Diagrams:

The UML diagrams are broadly classified into two categories. They are,

  * Structural Diagrams

  * Behavioural Diagrams

Figure: Representation of Types of UML Diagrams with their sub-types

Structural UML Diagrams:

  * Structural UML diagram comprises of class diagram and device notating diagrams (component and deployment diagrams).

  * Structural UML diagram are used for the purpose of notating the logical implementation of the system regards how they are structurally organised.

  * As the name implies, how the system is really organized logically and physically are described with the help of structural UML's.

  * For example, in order to represent the online-course reservation system as structural UML diagram, the logical interconnections are represented by class diagrams (using association concept – the link will be provided between every classes) and the physical interconnections are stated by the component diagram.

Behavioural UML Diagrams:

  * Behavioural UML's are used for the purpose of representing the logical flow in the system. The structural diagram provides the logical as well as physical interconnection of the system but it doesn't state how the change occurs due to the actions.

  * The change of state due to the effect of applied action can be explained by behavioural UML's. It includes activity diagram, Use-case diagram, State Transition diagram, Interaction diagrams etc.

  * For example, consider the online-course reservation system –the request activity of the form by the student will trigger the event providing form by the server. Like-wise, the similar processes are represented by the behavioural UML diagrams.

Review to Software Engineering:

Software Engineering is a discipline of engineering which states the approach that has to be followed to develop effective software. It has pre-defined set of principles and procedures that has to be followed to create software. As simply, Software Engineering (SE) applies various steps for creating software with higher degree of worth-vileness.

Needs of SE:

  * By applying SE principles we can create effective software.

  * Acts as a blue-print for the developers to create software.

  * The software that has developed by applying SE principles was free from error.

Software Development Life Cycle – SDLC:

Software Development Life Cycle provides a standard steps that are to be followed in order to create an effective software. It includes major five phase. They are analysis, design, construction, testing and deployment.

During analysis phase, the various requirements are gathered from the user. This is the most important phase where the meeting will be conducted in order to gather the requirements. The user stated requirements are analysed and the Software Requirement Specification Document (SRS) will be prepared.

Using the SRS, the design will be implemented. The design will be in forms of diagrams that include DFD's, UML diagrams etc.After the effective implementation of design using these diagrammatic tools, the original source code is developed.

The source code may develop in any languages that include C, C++, Pascal, Java, Python, Perl etc. After the software was developed, it should be tested for the correctness. The testing process includes verification and validation. Checking with the sample inputs or imaginary inputs at the developer side is called verification. Checking the worth-vile property of software by the original input at the client side is called as validation process.

If the testing holds good, then the software has to be maintained and if necessary the software has to be updated with the essentials that are stated by the customer. Different life-cycle models are used for the purpose of designing the software in an effective way. They includes,

  1. Waterfall Model

  2. Iterative Model

  3. Spiral Model

  4. RAD Model

  5. WIN-WIN Spiral Model

Role of OOAD in SDLC:

The above stated concepts will give a clear-cut idea on SDLC phases. The OOAD plays a vital role in SDLC Design phase where the DFD's, ER Notations are understandable only by the programmer or developer's but the OOAD provides an optional way that it can be understandable even by the end-users.

It maps the problem with the real-world problem so that complexity in software design will be reduced at the greater extent.

The UP Phases:

The Unified Process provides an effective way to create the object oriented systems. It provides iterative development of the software and also it follows incremental development of the system. The major characteristics of UP includes that they are architecture-centric, use case driven. It is an extensible framework.

Phases of Unified Process:

The Unified Process includes the following phases,

  1. Inception

  2. Elaboration

  3. Construction

  4. Transition and Implementation

Inception:

  * Inception is the first and minute phase of the UP. It is very similar to the analysis phase of the SDLC. Inception phase will responsible for collecting the scope of the system that has to be developed, finding the possible risks that may incur while developing the system, the major goals of the system will be identified in this phase.

  * The inception phase also target on estimation of budget for the developing the system. Inception phase is essential because it tells whether the software product can be derivable or not with the current business constraints of the company that is going to develop the product.

  * Inception phase will identify the functional and non-functional requirements of the system.

Elaboration:

  * Elaboration phase is the next phase in the UP. The depth study of the system has been made by the inception phase and the functional and non-functional requirements that are gathered from the system have been verified for worth-vileness property.

  * The major ideology of OOA/D i.e, creation of UML diagrams that includes structured UML's (class, package)are derived in this phase.

  * A comparison will be made in between the already existing model in order to identify the pre-existing drawbacks of the system. The ultimate aim is to recover the drawbacks with the version that has to be created.

Construction Phase:

  * Behavioural UML diagrams are used in this phase. Construction involves identifying inputs, outputs, hardware specifications and tool specifications to develop the source code.

  * It is the largest phase in which the code of the system will be developed.

  * Each and every use cases are implemented with source code.

Transition or Implementation Phase:

  * It is the final phase in which the developed software is tested with the sample inputs. The testing tells whether the developed system is efficient or not. If any lack in efficiency of system, then it is to be redeveloped else it is should be submitted to the client.

  * After submission, the maintenance should be takes place periodically that includes taking back-up's, updating additional options in the system etc.

UP- Varieties:

The above stated UP Phases are the standard steps that are required to design an OO Systems. But actually, different organization(s) follows different steps of UP to develop an OO System. Hence it leads to various UP varieties. Some of them are,

  1. Agile Unified Process

  2. Open Unified Process

  3. Rational Unified Process

Agile Unified Process:

  * Agile Unified Process is the basic UP that are easy to implement.

  * They include seven different phases' starts from model and ends with environment.

  * It deals with requirement gathering process, developing the code, testing the code, management of system.

********

Authors: MRS.D.ANURADHA, P.HARIPRASATH, S.GOKULAMUTHAN
