BCA - (WEB PROGRAMMING) (Total 5 Units PDF
BCA - (WEB PROGRAMMING) (Total 5 Units PDF
WEB PROGRAMMING
2023-2024
II BCA IV Semester
SYLLABUS
Advanced PHP: Functions, Advantages of Using functions, Types of functions, creating and
invoking functions, returning values, recursive functions Object Oriented Concepts, File
handling and Data Storage: creating, open/close a file, file operations: read, write, append. File
truncate, file uploading, EOF in PHP.
Unit-IV: Working with Forms in PHP
Creating Forms, Accessing Form - Input with User defined Arrays, Combining HTML and PHP
code on a single Page, Using Hidden Fields to save state, Redirecting the user.
PHP with MySQL: Creating Database in MySQL, Connecting to MYSQL, Reading and Writing
form data from MYSQL
Unit-V: Working with Cookies and User Session
Working with Cookies and User Sessions: Introducing Cookies, Setting a Cookie with PHP,
Session Function Overview, Starting a Session, Working with session variables, passing session
IDs in the Query String, Destroying Sessions and Unsettling Variables, Using Sessions in an
Environment with Registered Users.
3
HTML is the lang ua g e designed for crea ting web- page s. Html pro vides
a way for create web pages with text, i mages, or mul timedia content using
pr ed ef in ed tags saved as HTML f i le. The langua ge used to displa y web pages
is called HTML. Html is a syntax used to format a text document on the web
HTML is the langua g e in te rp re t ed by a b rowser. Such as 1 ) internet ex plorer
2 ) Netscape n avi gator 3 ) mozi lla Fire fox 4 ) opera
HISTORY OF HTML
In 1980, physicist Tim Berners- Lee, who was a contractor at CER N, proposed and
prototyped ENQUIRE, a system for CERN researchers to use and share documents. In
1989, Berners-Lee wrote a memo proposing an Internet-based hypertext system.
Berners-Lee specified HTML and wrote the browser and server software in late 1990. That
year, Berners-Lee and CERN data systems engineer Robert Cailliau collaborated on a joint
request for funding, but the project was not formally adopted by CERN. The first publicly
available description of HTML was a document called "HTML Tags", first mentioned on the
Internet by Berners-Lee in late 1991
HTML Versions
Since the early days of the web, there have been many versions of HTML:
Version Year
HTML 1991
HTML+ 1993
4
XHTML 2000
HTML5 2012
Html is used to define document stru cture with the help of a single or a pair
of tags. A tag is a stri ng in the language su rrou nded by a less than ( <) and
a gr eat er than ( >) sign. An opening tag is spe cified as tag name and ending
tag is begin with slash (/), </ tag name)
PAIRED TAGS : a tag is said to be a paired tag i f the text is placed betwe en
a tag and its compani on tag ( end tag). In paired tags, the f i rst tag is
referred to as opening tag and the second tag is referred to as closing tag.
UNPAIRED TAGS: An unpai red tag does not have a companion tag. Un
paired tags are also know as singular or stand- al one tags.
Exampl e: <br>
<hr>
DOCUMENT HEAD SECTION: Information placed in this section is essential to the inner
workings of the documents and has nothing to do with the content of the document. With
the exception of information contained within the <TITLE>…</TITLE> tags, all information
placed with in the <HEAD>…</HEAD>tags is not displayed in the browser.
DOCUMENT BODY SECTION: This area is used to display the content of the webpage with
required formats presented in the form of
sub tags inside the start and end of the
main body of textual information
<BODY>….</BODY>
Attributes allow to add extra instruction to selected tag. Because each tag has its
own unique attributes.
Title Spe cifies extra i nfo r m a tio n about an elem ent ( displ ay ed as a tool tip)
( OR)
Surrounding all the text in the entire file are the beginning and ending HTML tags <HTML>
AND </HTML>. These tags let the browser know that the file is indeed an HTML file.
A title tag <TITLE> is contained wit in te head of the document to provide a tile for
document with have end tag </title> we can include any HTML formatting with in the title
tag.
EXAMPLE:
<HTML>
<HEAD>
</HEAD>
<BODY>
</BODY>
</HTML>
HTML, which stands for Hypertext Markup Language, is the predominant markup language
for web pages. With HTML you can create your own website. It is written in the form of
HTML elements consisting of “tags” surrounded by angle brackets with in the web page
content.
It allows images and objects to be embedded and can be used to create interactive
forms. It provides a means to create structured documents by denoting structural semantics
for text such as headings, paragraphs, lists, links, quotes and other items. It can embed
scripts in languages such as JavaScript which affect the behavior of HTML web pages
HTML can also be used to include Cascading Style Sheets (CSS) to define the
appearance and layout of text and other material. The W3C, maintainer of both HTML and
CSS standards, encourages the use of CSS over explicit presentational markup
(OR)
(OR)
The body tag is the second & main part of every html document. The tags
used to indicate the start and end of the main body of textual information. This is a paired
element it contains start and end tag <BODY>…. </BODY>
The data given in between these tag is displayed in the work area of the browser
window.
9
By default the background color of the body is displayed in white and the text color is
indicated with black. In order to change the default properties and formats the display
structure of the body tag & it’s attributes to change The attributes of the <body> are
BGCOLOR: it changes the default background color to user defined color specified in the
tag. The user can specify the color name or hexadecimal number
<html>
<head>
<title> adcwbgcolor</title>
</head>
<body bgcolor="green">
</body>
</html>
BACKGROUND: it is used to change background according to user specified image file used
as the background of the document (i.e. GIF or jpeg file etc)
<html>
<head>
10
<title> adcwbgcolor</title>
</head>
<body background="C:\Users\Public\Pictures\mum.jpg">
</body>
</html>
TEXT : Changes the body text color from its default color to user defined color
<HTML>
<HEAD>
<TITLE>MSTCSIIIRD</TITLE>
</HEAD>
</BODY>
</HTML>
ALINK, VLINK, and LINK: It specifies the color of Active link, Visited link and link which is
not visited.
<HTML>
<HEAD>
</BODY>
</HTML>
BGPROPERTIES: This property indicates horizontal scroll bar for the web pages i.e. values
(FIXED / SCROLL)
<html>
<head>
<title>m</title>
</head>
<body bgproperties="scroll"
scroll="yes">
<img src="D:\WEB_GSK\IM.jpg">
</body>
</html>
MARGIN HEIGHT/WIDTH: Give the height and the width of the document towards right
left top bottom
Syntax: MARGINHEIGHT=<VALUE>
RIGHT/LEFT MARGIN: It shows margin distance from the border of the webpage and text
and user want to give integer value
Syntax: RIGHTMARGIN=<VALUE>
12
<html>
<head>
<title>aditya </title>
</head>
<body BGPROPERTIES="SCROLL"
LEFTMARGIN=10
MARGINHEIGHT=10
MARGINWIDTH=10
RIGHTMARGIN=10
SCROLL="no">
</BODY>
</HTML>
<html>
<head>
<title>aditya </title>
13
</head>
bgcolor="#010101"
text=white
bgproperties="scroll"
LEFTMARGIN=50
MARGINHEIGHT=30
MARGINWIDTH=20
RIGHTMARGIN=30
SCROLL="yes">
<CENTER>
</BODY>
</HTML>
(OR)
EXPLAIN ABOUT VARIOUS TEXT FORMATTING TAGS OF HTML WITH EXAMPLE AND
SYNTAX?
The text formatting tags are used to format the appearance of the text on your web
page. They are several formatting tags to change the appearance of the text according
specified tag given in it.
14
PARAGRAPH: It provides a blank line and separates paragraphs in the textual. This
paragraph tag provides same functionality.
Syntax: <P>……</P>
LINEBREAK: it provides breaks between the text line if user want to start a text in new
line. i.e. it simply jumps to next line of the page. It doesn’t have no end tag
CENTER: It is used to center everything in between them i.e. text, images, tables, etc.
STRONG: it is also work as a bold tag, it displays the text in bold style only. But some of
the web browsers that cannot render the text as bold. So that purpose we want to use
strong tag.
Syntax: <STRONG>….</STRONG>
TYPEWRITER: The text appears to have been typed by a typewriter, in a fixed-width font.
Syntax: <TT>…..</TT>
STRIKE: Puts a line right through the centre of the text, crossing it out. Often used to show
that text is old and no longer relevant.
Syntax: <S>….</S>
SUBSCRIPT: it is used to generate a subscript function which displays the text in lower
position enclosed in <sub>…</sub>.
Syntax: text/number<sub>text/number
BLINK: it is used to display the flashing text. But it is browser dependent element.
Syntax: <BLINK>…..</BLINK>
HEADER TAGS: It supports six different levels of headings. In this the highest level header
tag is <H1> and lowest tag is <H6>. All styles appear in boldface and the size is depending
on tag used by the user.
FONTFACE/COLOR/SIZE: It displays text in a particular font, use the font name such
"Helvetica" or "Arial" or "Courier". So that also color. Its display’s the color according to
specify in the tag same as the size also it display the size according to specify in the tag
NOTE: The font size is in between 1 to 7 only i.e. minimum value is 1 and maximum
value is 7 where are default value is 3
17
BR (BREAK) A br tag will insert a line break which means the text/image following the tag
will be moved to the next line when displayed in the browser.
<PRE>: This element display the text as it is given in the source code with all formats that
means spacing, tabulation etc.
BGSOUND: its play a background sound when your webpage is opened. This tag must be
placed in <head> tag and the user must mention file extension of the audio
<HTML>
<HEAD>
</HEAD>
<HTML>
A hyperlink is a special tag can contain links that takes directly to other pages and even
specific parts of a given page. These links are known as hyperlinks. Hyperlinks allow visitors
to navigate between websites by clicking on words, phrases, and images. Thus one can
create hyperlink by using data available in the webpage. We can create multiple pages with
the clickable hyperlinked text is considered as hyperlinks. In hyperlink tag consists start tag
and end tag (<a> </a>) is used to create a hyperlink
1) Text hyperlink
2) Image hyperlink
3) Mailto hyperlink
4) Intra Document hyperlink
TEXT HYPERLINKS: It is created to the selected text written between <a></a> tag is
considered as hyper text and by clicking on the text the page is connected dynamically.
19
1) In the text hyperlink, a page in the same folder
2) A page in the system i.e. by specifying the full path of the file.
3) A web page, by specifying the URL of the webpage
<HTML>
<HEAD>
</HEAD>
<BR>
<H1><CENTER><AHREF="https://www.google.co.in">GOOGLE</A></H1></CENT
ER>
</BODY>
</HTML>
20
IMAGE HYPERLINKS:
The image hyperlink is same as the text hyperlink. For a image, one mouse click
returns an HTML document or any related image file or file. It is simply replace as text
hyperlink with an image hyperlink. The image is displayed with default border of blue color
and with a linkable cursor pointer.
<HTML>
<HEAD>
</HEAD>
<BODY>
<A HREF="https://www.google.co.in">
</CENTER>
</BODY>
</HTML>
MAILTO HYPERLINK: This tag provides you facility to specify an email address to send an
email. While anchor tag as an email tag then we sue mailto:emailaddress along with
properties of HREF. It is the common to add a mailto hyperlink to a webpage. It provides
you send email by opening a default mailbox with the id in sender URL
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1> <CENTER>
</BODY> </HTML>
The tag give you create a hyperlink to any part of your document, rather than just
the beginning i.e., any portion of the document can automatically be displayed at the top of
the browser’s document area. This is particularly useful if you have a long webpage and
user would like to be able to jump to various section of it without scrolling.
The internal links will specified with # symbol followed by link attribute
22
<HTML>
<HEAD>
</HEAD>
<BODY>
</a>
</a>
Visual basic
</a>
</BODY>
</HTML>
The <a> tag defines a hyperlink, which is used to link from one page to another is
know as Anchor tag. The most important attribute of the <a> element is the href attribute,
which indicates the link's destination. The term “anchor” is used because it indicates the
static positioning of a hyperlink.
23
Program: <html>
<head>
<body>
</body> </html>
(OR)
PATHS: path is the location of the file which is linked to the text given between <a>….
</a> element. The location can be local or
external address can be specified using absolute /
relative reference.
Absolute Path: It is used if the file is located on the remote area that means outside of
the folder. In this path we will give complete location reference which includes Drive, Folder
name, Filename with extension.
(OR)
List is the process of displaying the data in bullets / numbering format. It have 3
types of lists 1) Unordered list 2) Ordered list 3) Definition list
Here in the list <LI> tag is considered as the list item for all lists. In list tags the
closing tag is not compulsory for <LI>tag
UNORDERED LISTS: It is a collection of related items that have no order or sequence. This
list is created by using <UL>tag. Each item in the list is marked as a bullet.
The list types are DISC, SQUARE, and CIRCLE in this the default list is DISC Most of
the browsers will display disc. An unordered list starts with <UL>tag and end with </UL>
<html>
<body>
<H3>GROUP</H4>
<ul>
<li>MSTCS</li>
<li>BBM</li>
25
<li>MPCS</li>
</ul>
</body>
</html>
ORDERED LIST: The content of an ordered list just like an unordered list, except that the
items are numbered instead of bullets. The number starts from one and incremented by one
presented in the <li> tag. The list is created by using <ol> tag.
<html>
<body>
<H5>GROUP</H5>
<li>MSTCS</li>
<li>BBM</li>
<li>MPCS</li>
</ol>
26
</body>
</html>
The list is works just like a entries find in a dictionary or encyclopedia, complete with
text and other elements. The elements used to create in Definition list
<dl> it is the start tag in the list it contains end tag also </dl>
<dt> it determines the Definition term
<dd> it determines the Definition data
Syntax: <dl>
<dd>[text] </dd>
</dl>
Example: <dl>
<dt>Mstcs</dt>
<dt>BBM</dt>
</dl>
<html>
<body>
27
<dl>
<dt>Mstcs</dt>
<dt>BBM</dt>
</dl>
</body>
</html>
NESTED LIST: It is method of combining more than one list in a selected list the list can
be nested to display the sub list details. It may contains ordered and unordered lists in a
nested list
Syntax:
<ul>
<Li>List item one</li>
<li>List item two with subitems :</li>
<ul>
<li>Subitem 1</li>
<li>Subitem 2</li>
</ul>
<li>Final list item</li>
</ul>
Example: <ul>
<li>GROUP</li>
<li>MSTCS
<ul>
<li>IST YEAR</li>
<li>IIND YEAR</li>
28
</ul>
</li>
<li>BBM</li>
</ul>
<html>
<body>
<ul>
<li>GROUP</li>
<li>MSTCS
<ul>
<li>IST YEAR</li>
<li>IIND YEAR</li>
</ul>
</li>
<li>BBM</li>
</ul>
</body>
</html>
29
<html>
<body BGCOLOR=ORANGE>
<H2>
<OL TYPE=I>
<UL TYPE=SQUARE>
<LI>B.COM
<OL>
<LI>COMPUTERS
<LI>REGULAR
<LI>HONORS
</OL>
<BR><LI>B.SC
<UL TYPE=DISC>
<LI>MPCS
<LI>MSTCS
<LI>MECS
</UL><BR>
<LI>PROFESSIONAL COURSES
<UL TYPE=CIRCLE>
<LI>BCA
<LI>BBM
</UL><BR>
<LI>PG COURSES
30
<OL TYPE=A>
<LI>MCA
<LI>MBA
</OL></OL>
</body>
</html>
(OR)
Tables in HTML pages allow you to organize information in a row and column format.
The HTML table model allows authors to arrange data text, preformatted text, images, links,
forms, form fields, other tables, etc. into rows and columns of cells. HTML table are used to
present any type of information for which you want a lot of control over the positioning of
the material
There are many ways to use tables to format information on the web. There is a
good chance it was produced using tables. They are some points to use in tables.
CONTROL LAYOUT: if you want to control the layout of text position a group of images, or
present an extensive menu, you may decide to use tables to achieve desired appearance
CREATION OF TABLE
To construct tables in HTML, the basic element <table> is used to create the
structure of the table. Then the number of rows and columns are decided with TR and TD
elements.<TR> this element is used to create a table row where as <TD>&<TH> are used
to to insert the cells in the selected row
Table Row <TR>: The TR (table row) elements act as a container for a row of table cells.
Used to create table row, A horizontal structure is available to insert the data. A table can
contain an infinite number of table rows. Each table row of table element itself, with an
opening and closing tag <tr>….</tr>.where as columns are considered child elements of
Html tables. Where as table may contain an infinite number of table data cells (<td><tr>)
Table Cells: The TH and TD elements are used to define the cells in the selected row of the
table. TH is used to create a table header displayed with bold style and TD used to display
the table data in normal font
<html>
<head>
<tr> <td>1<td>ABC</TR>
<tr> <td>2<td>GSK</TR>
<tr> <td>3<td>XYZ</TR>
</body>
</table></html>
COLSPAN This is used to merge the selected number of columns in the given row. The
horizontal cell are combined together to give a merging display
ROWSPAN: The rowspan works in the same way as colspan. It combines multiple vertical
cells and displays the content in horizontal format
ALIGN: it aligns of the caption with respect to the table. It has values i.e. BOTTOM, TOP,
CENTER
<html>
<head>
<body>
<tr><th rowspan=4>MSTCS</th></tr>
<tr> <td>2<td>GSK<td>IInd</TR>
<tr> <td>3<td>XYZ<td>IIIrd</TR>
</body>
</table>
</html>
(OR)
(OR)
Frames are an HTML feature introduced by Netscape communications they allow your
to divide the browser window into several independent parts. Frames in an HTML document
can cause a web page to appear to be divided into scrollable regions. Each frame can be
assigned a name, a source document locater, dimensions, border alignments and style
sheets etc.
The frame is a similarity with window frame. A group of frames in a single browser
window is called a frameset. The frameset tag <FRAMESET> and corresponding ending tag
</FRAMESET> are used for creating a set of frames. The frameset tag in an HTML
document replaces the body tag.
3) The noframes defines no frame section for browsers that do not handle frames.
Once the browser window is partitioned, you need to tell the browser what to load
into the different frames. This is using the frame tag <FRAME>.no ending tag is necessary
to the frame tag. For example there are two frames in which the browsers window is
vertically divided into two equally parts
<html>
<head>
</title> </head>
<frame name=sri>
<frame src="5.HTML"NAME=TOP>
<frame src="6.HTML"NAME=BOTTOM>
</frameset>
</html>
The <cols> attribute of the frameset tag is used to specify that for creating columns,
where a column is vertically oriented frame. The cols attribute can take values as a
percentage of the browser’s window or you can specify the column width using fixed pixel
amount. You can use the wildcard symbol “*” to assign left over amount of space, and to
divide the browser’s window in two proportions.
The <ROW> attribute of the frameset tag is work like <COL> tag. But it divided the
window horizontally using <ROW>attribute. The row attribute can take the value as a
percentage of the browser window or user specify pixel amount. We can also use wild card
symbol “*”to assign left over space The example shows the row section
<html>
<head>
</title> </head>
<frame name=sri>
<frame src="5.HTML"NAME=TOP>
<frame src="6.HTML"NAME=BOTTOM>
</frameset>
</html>
<NOFRAMES>: We can also include the Noframes tag it also have a corresponding tag that
means end tag <noframes>……</noframes>.The browsers which are capable of displaying
frames will ignore the NOFRAME tag. Browsers not capable of displaying frames render the
information appearing between NOFRAMES tag and its ending tag.
NAME: Assigns a name to a frame. It is used to load the content from one to
another frame.
FRAME BORDER: It set the border to page the values are 1 and no border
(OR)
Forms are a mechanism that allow you to type information into fields on a browser
screen and submit the information to a web server. They allow your to create interactive
web pages. That is you can fill out a form, submit it and then the information is uploaded to
the designated serer to handle a form. A program on the server processes the information
and then returns a new HTML DOCUMENT.
Forms have may functions. They can be used for gathering information about a user,
survey, order online etc. submitting a query to a search engine and so on. In each case,
when the user submits a form, values are uploaded to the receiving server. If user filled out
the form correctly, the HTML document may a message the user to redo the form and
resubmit it.
FORM TAGS: Forms provide an interface for collecting, displaying, and delivering
information and are used as a key component of HTML. Forms have different types of fields
such as text input fields, radio buttons, checkboxes, submit and reset button etc.
Form is created by using <FORM>tag. it is also a paired tag. i.e. it have end tag. i.e.
<FORM>…..</FORM>. The most important property in the form is action and method
….Form fields…
….Form fields…
</form>
</form>
FORM METHODS:
The "method" attribute establishes how the form's data will be sent to the processing
agent. There are two possible values for this attribute (case-insensitive)
1) get: The form's data is added to the URI defined in the action attribute
</form>
The primary element of html forms which helps user to create various controls using
its type attributes. It is an independent tag which means it does not have closing tags. It
supports 13 form controls with different structure.
Each input element with in the form is sent to the server as name/value pairs.
TEXT BOX: A rectangular shaped field in which a user can enter text is considered as text
box. A text box is the type of input tag with name, size max length and values. Example
<HTML>
<HEAD>
<TITLE>XYZ</TITLE>
</HEAD>
<body>
<FORM>
</font>
</body>
</FORM>
</HTML>
PASSWORD: The password input type creates a single line empty text box where the user
can enter text into it. It is similar to text fields. It display the text in the fields like stars (*)
and dot (.) that means it creates masked fields in passwords.
<html>
<body>
<form action="">
</form>
</body>
</html>
<html>
<body>
<form action="">
</form>
</body>
</html>
RADIO BUTTONS: Radio buttons are a group of buttons from which only one can be
selected at a time.
Ex: <html>
<body>
<form action="">
<H4>GENDER</H4>
</form>
</body>
</html>
ACTION BUTTONS: - They are two types actions buttons they are submit and reset. Where
the user clicks on the submit button, the values that have been entered into the form are
sent the program that process the form. where as reset button is to allow to clear all of the
input entered in the form and starts from the first.
Ex: <html>
<body>
</form>
</body>
</html>
FILE: The file type of input tag provides a file upload form box for HTML forms. It allows to
solicit (request) files from the readers such as images or videos.
Ex: <html>
<body>
<input type="submit">
</form>
</body>
</html>
SELECT: The select tag allow to choose any subset of items from a group, the items given
in select tag are usually rendered in the style of a pop-up menu. The items are indicated by
using <option> tag. Here in <option>tag the end tag is optional
<html>
<body>
<select>
<option value="MSTCS">MSTCS</option>
<option value="B.COM">B.COM</option>
<option value="MPCS">MPCS</option>
<option value="BBM">BBM</option>
</select>
</body>
</html>
TEXT AREA: The <text area> tag defines a multi-line text input control. A text area can
hold an unlimited number of characters, and with fixed-width font (i.e. courier) the area can
be specified by the cols and rows attributes.
Ex: <html>
<body>
The good teacher explains. The superior teacher demonstrates. The great teacher
inspires.
</textarea>
</body>
</html>
<html>
<body BGCOLOR="OLIVE">
<fieldset>
<legend>Personal information:</legend>
Places<Select>
<option value="KKD">Kakinada</option>
<option value="HYD">Hyderabad</option>
<option value="CH">Chennai</option>
</select><br><br>
</fieldset>
</form></body></html>
(OR)
The head is first section of any HTML page, it contains lots of control information that
is needed by browsers and servers. Many people do write the <title> tag in head section.
Information placed in this section is essential to the inner workings of the document the
information placed with in the <head>….</head> expect <title> tag is not displayed by the
browser.
<BASE>: This tag is used to enforce relative links. Between pages and documents.
o Ex: <BASE HREF=”URL”>
<BASEFONT>: This tag defines the font size to be used in the html document. The
attributes of this tag is (size, color, face)
o Ex: <BASEFONT SIZE=”4” COLOR=”BLUE” FACE=”ARIAL”>
<BGSOUND>: This tag is used to play a sound track in the background. This tag is
for internet explorer document only.
o Ex: <BGSOUND SRC=”SRI.WAV”> </BGSOUND>
<ISINDEX>: This tag is used for take simple and single line of text input.
<LINK>: This tag is used to allow other documents to be linked to, or included in, in
the document
o Ex: <LINK REL=”TYPE” HREF=”URL” TYPE=”STRING” MEDIA=”STRING”>
<META>: This tag is used to describes the whole document should be included
using one of alternatives
o Ex: <META NAME=”STRING” CONTENT=”STRING”>
<NOSCRIPT>: This tag is used to hold text that only appears if the browser does
not support the script tag.
<SCRIPT>: This tag is used to holds programming scripts statements like Java
script, VBscript.
TITLE> The webpage title which appear in the title bar of the web browser
JAVA SCRIPT
EXPLAIN ABOUT SCRIPTING?
Script is the abbreviation for “SCOTTISH CENTRE FOR RESEARCH IN INTELLECTUAL
PROPERTY TECHNOLOGIES.
Any program run by web server in response to the user’s request is termed as script.
Scripting languages are the basis o the CGI-BIN( common gate way programming.
Webpages are two types 1) server side script 2) client side script
languages. In that the most popular is client side script i.e. JavaScript
BENEFITS OF JAVASCRIPT:
1) It is widely supported by web browsers
2) It gives easy access to the document objects and can manipulate most of them.
3) We can create animations with out the long downloading
4) It is relatively secure, JavaScript can neither read from your local hard drive nor write
to it,
5) It can’t get a infected by virus directly to JavaScript.
6) It allow page effects to create
1) User’s time on page 2) Popups and tool tips 3) page timeout
4) Color changes 5) font sizing 6) embedded audio
7) Scrolling banners 8) Toggle buttons 9) Image transitions
10) Automated popup
7) JavaScript will add user interactivity, because we add special effects to the webpage so
that it will make more interactive.
8) JavaScript will provide seamless integration with user plug-ins (JavaScript not only
provides access to HTML objects, it also gives access to browser and platform-specific
objects like browser plug-ins (e.g. Adobe Acrobat, Media Player).
9) JavaScript will allow client-side user form validation (to check for simple errors such as
missing information)
Embedded within html: it does not require any special editor for written programs,
are normally not programmers, but the script is very simple syntax any one write
JavaScript can react to events: It can be set to execute, when things happens,
JavaScript can read and write HTML elements: it can read and change the
JavaScript Can be used to Validate Data: it can be used to validate from data
JavaScript can be used to create cookies: JavaScript can be used to store and
<script language=”JavaScript”>
</script>
Rules: The key points are to follow when a writing a scripts programs
Sk */
Including java script: After writing the script we need to include in an html page.
Script can be executed with an interpreter it is part of a browser. The browser also
debug the script and display errors if any.
<head>
2) External i.e. we can create the script in separate file & save it (filename.js) and
then create HTML file and include in the file by using “src” element i.e. <script
language=”JavaScript” src=”filename.js”>
Ex: <html>
<head>
<body>
……</body></html>
1) IN HEAD SECTON
2) IN BODY SECTION
3) IN BOTH HEAD AND BODY SECTION
4) IN EXTERNAL FILE
(OR)
var gsk=14.25;
BOOLEAN: it holds the values of “TRUE/ FALSE”. These are used to hold the results of
conditional tests.
NULL: In JavaScript the null represents nothing the null value in JavaScript term as null.
It doesn’t mean NIL or ZERO
Var age=null;
A variable is a data item that can be manipulated at any time. In javascript the
variable are same as the other programming languages. Variables are used to hold data
in memory.
Arithmetic Operators: These operators takes numerical values as their operands and
return a value. The operators are
OPERATOR DESCRIPTION EXAMPLE
+ Addition (add two operands) A+b=c; 10+20=30
- Subtraction (subtract second operand from the first a-b=c 10-20=-10
* Multiplication (multiply both operands) a*b=c 5*2=20
/ Division (divide the first number by the number b/a=c 4/2=2
% Remainder ( divides left by right and leave remainder b%a=c 3%2=1
++ Increment operator ( increases the integer value) A++ 10++=11
-- Decrement operator (decreases the integer value) A—10--=9
COMPARISON OPERATORS: A comparison operator compares the operands and returns the
value based on the condition whether it is true or not .
EXAMP
OPERATOR DESCRIPTION
LE
== Returns true if the operands are equal (A==b)
!= Returns true if the two operands are not equal (a!=b)
> Greater than ( returns true if the left operand is greater than the right (a>b)
>= Returns true if the left operand is greater than or equal to the right one (a>=b)
< Returns true if the left operand is less than right (a<b)
<= Returns true if the left operand is less than or equal to the right one (a<=b)
LOGICAL OPERATORS
These operators used with Boolean values. They return a Boolean value.
OPERATOR DESCRIPTION EXAMPLE
&& AND operator. if both operands are non zero then become true (a&&b)
|| OR operator. If any of the two operands are non zero it become true (a||b)
! Logical Not returns false if operand value evaluates true !(a&&b)
ASSIGNMENT OPERATORS:
These operators are to assign a value to a variable or constant or expression assigned for
given variable.
OPERATOR DESCRIPTION EXAMPLE
= Assigns the value of the right operand to the left operand c=a+b
+= Adds together the operands and assigns the result to the left c+=a /c=c+a
Subtract the right from the left operand and assigns the result to
-= c-=a / c=c-a
the left
*= Multiplies the operands and assigns the result to the left C*=a / c=c*a
/= Divides the left by the right operand and assigns the result to left c/=a / c=c/a
Divides the left by the right operand and assigns the remainder to
%= C%=a / c=c%a
left
CONDITIONAL OPERATOR (? :)
It used for comparing two expressions also contains a conditional operator that
assigns a value to a variable based on some condition
THE + OPERATOR USED ON STRINGS: The + operator can also be used to add string
variable or text values together. To add two or more string variables together, use the
operator.
SYNTAX: TXT1=”WHAT A VERY”; TXT2=”NICEDAY”;;
EXAMPLE: TXT3=TXT1+TXT2;
CONDITIONAL STATEMENTS:
Syntax: if (expression) {
Statement(s) to be executed if expression is true
Here JavaScript expression is evaluated. If the resulting value is true, given statement(s)
are executed. If expression is false then no statement would be not executed.
IF...ELSE STATEMENT: The if...else statement is the next form of control statement that
allows JavaScript to execute statements in more controlled way.
Syntax: if (expression){
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) in
the if block, are executed. If expression is false then given statement(s) in the else block,
are executed.
The if...else if... statement is the one level advance form of control statement that allows
JavaScript to make correct decision out of several conditions.
It is just a series of if statements, where each if is part of the else clause of the previous
statement. Statement(s) are executed based on the true condition, if non of the condition is
true then else block is executed.
EXAMPLE:
<script type="text/javascript">
var book = "COMPUTERS";
if( book == "MATHS" ){
document.write("<b>MATHS Book</b>");
}else if( book == "COMPUTERS" ){
document.write("<b>COMPUTERS Book</b>");
}else if( book == "economics" ){
document.write("<b>STATISTICS Book</b>");
}else{
document.write("<b>Unknown Book</b>");
}
</script>
SWITCH STATEMENT: switch statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression. The interpreter
checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used.
SYNTAX
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate to the interpreter the end of that particular case. If they were
omitted, the interpreter would continue executing each statement in each of the following
cases.
EXAMPLE
<script type="text/javascript">
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("A+GRADE<br />");
break;
case 'B': document.write("A GRADE<br />");
break;
case 'C': document.write("B GRADE<br />");
break;
case 'D': document.write("C GRADE<br />");
break;
case 'F': document.write("D GRADE<br />");
break;
default: document.write("FAIL<br />")
}
document.write("Exiting switch block");
</script>
LOOPING STATEMENTS:
Loops execute a block of code, a specified number of times, or while a specified
condition is true.
In java script, there are three different kind of loop
1) for 2) while 3) do while
FOR LOOP:
For loop is the most compact form of looping and includes the following three important
parts:
1) The loop initialization
2) The test statement which will test if the given condition is true or not
3) The iteration statement where you can increase or decrease your counter
Syntax:
EXAMPLE:
<script type="text/javascript">
var I;
document.write("<br />");
document.write("Loop stopped!");
</script>
WHILE LOOP: The most basic loop in JavaScript is the while loop.
Syntax:
while (expression)
The purpose of a while loop is to execute a statement or code block repeatedly as long as
expression is true. Once expression becomes false, the loop will be exited.
EXAMPLE:
<script type="text/javascript">
var SRIK= 0;
SRIK++;
document.write("Loop stopped!");
</script>
DO...WHILE LOOP:
The do...while loop is similar to the while loop except that the condition check happens at
the end of the loop. This means that the loop will always be executed at least once, even if
the condition is false.
Syntax:
do{
Statement(s) to be executed;
while (expression);
Example:
<script type="text/javascript">
var GSK = 0;
do{
GSK++;
document.write("Loop stopped!");
</script>
BREAK STATEMENT:
The break statement will break the loop and continue executing the code that follows
after the loop if any.
Example
<script type="text/javascript">
var gn= 1;
if (gn == 5){
gn = gn+ 1;
</script>
CONTINUE STATEMENT:
The continue statement tells the interpreter to immediately start the next iteration of the
loop and skip remaining code block.
When a continue statement is encountered, program flow will move to the loop check
expression immediately and if condition remain true then it start next iteration otherwise
control comes out of the loop.
EXAMPLE:
<script type="text/javascript">
var GS = 1;
GS =GS + 1;
if (GS == 5){
</script>
<html
<body>
<script type="text/javascript">
var i;
document.write(+i);
document.write("<br>");
</script>
</body>
</html>
<html>
<body>
function fact(n)
if(n == 0)
return 1;
else
return (n*fact(n-1));
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
var a=0,b=1,c;
document.write("Fibonacci");
while (b<=13)
document.write(c);
document.write("<br/>");
c=a+b;
a=b;
b=c;
</script>
</body>
</html>
ARRAYS
(OR)
(OR)
1) The first way to declare array is to declare a variable and pass it some elements.
It creates an array three elements, each holding a text string. In this type of array
the elements will surrounded by square brackets.
2) The second way to declare an array is to create array object using the keyword “new”
and a set of elements
Using this construct, the contents of the array is surrounded by small braces.
Because they are parameters to the constructor of the array object
3) The Third way to declare an empty array object which has space for a number of
elements can be created.
Ex: var days = new Array(4);
ADDING ELEMENTS TO AN ARRAY: Array elements are accessed by their index. The
index is denotes the position of the element in the array and, as in for loops. These are
starting from “0”
We can’t new item now because it is already full many languages faced this problem
can’t solve it. But JavaScript has a good option because the interpreter simply extends
the array and inserts the new item.
ACCESSING ARRAY MEMBERS: The elements in the array are accessed through their
index the same access method is used to find elements and to change their value.
(OR)
CONCAT: The concat() method is used to join two or more arrays.This method does not
change the existing arrays, but returns a new array, containing the values of the joined
arrays.
EXAMPLE: var h = ["s", "r"]; var s = ["i", "k", "a"]; var n = h.concat(s);
document.write(n);
<!DOCTYPE html>
<html>
<body><script>
var n = h.concat(s);
document.write(n);
</script></body></html>
JOIN (STRING): The join() method joins the elements of an array into a string, and
returns the string. The elements will be separated by a specified separator. The default
separator is comma (,).
SYNTAX: array.join(separator);
POP(): The pop() method removes the last element of an array, and returns that element.
SYNTAX: array.pop()
fruits.pop();
PUSH(): The push() method adds new items to the end of an array, and returns the new
length. The new item(s) will be added at the end of the array.
fruits.push("Kiwi");
SYNTAX: array.reverse()
fruits.reverse();
SHIFT():The shift() method removes the first item of an array, and returns that item.This
method changes the length of an array.
SYNTAX: array.shift();
fruits.shift();
SLICE(): The slice() method returns the selected elements in an array, as a new array
object. The slice() method selects the elements starting at the given start argument, and
ends at, but does not include, the given end argument.
SYNTAX: array.slice(start,end);
SORT():The sort() method sorts the items of an array.The sort order can be either
alphabetic or numeric, and either ascending or descending.
SYNTAX: array.sort(sortfunction);
fruits.sort();
UNSHIFT(): The unshift() method adds new items to the beginning of an array, and
returns the new length.
fruits.unshift("Lemon","Pineapple");
<html>
<head>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
JavaScript supports three important types of dialog boxes. These dialog boxes can be
used to raise and alert, or to get confirmation on any input or to have a kind of input from
the users.
1) Alert box 2) Confirm box 3) Prompt box
ALERT BOX: An alert dialog box is mostly used to give a warning message to the users.
Like if one input field requires to enter some text but user does not enter that field then as
a part of validation you can use alert box to give warning message
Syntax: alert(“textmessage”);
Example: alert(“Welcome to Mstcs”);
<HTML>
<head>
<script type="text/javascript">
alert("Warning Message");
</script>
</head>
</HTML>
CONFIRM B0XA confirm box is often used if you want the user to verify or accept
something. When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Syntax: confirm(“TEXT MESSAGE);
Ex: confirm (“har”);
WRITE A PROGRAM TO DISPLAY PROMPT BOX IN JAVASCRIPT
<!DOCTYPE html>
<html>
<body>
<script language="javascript">
var x=confirm ("if u work hard");
if(x)
alert("u will get good marks");
else
alert("will get less marks");
</script>
</body> </html>
PROMPT BOX: A prompt box is often used if you want the user to input a value before
entering a page. When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the
box returns null.
Syntax: prompt (“text message”,default_value”);
<HTML>
<body>
<script type="text/javascript">
</script>
</body>
</HTML>
(OR)
(OR)
(OR)
JavaScript simply stores a series of characters. A string can be any text inside
quotes. You can use single or double quotes.
String manipulation can be done joining of strings, splitting of strings and search
through strings. In order to perform these manipulations functions JavaScript has used
following functions.
charAt(): This function returns the character at the specified index. Characters in a string
are indexed from left to right. First character is 0 last character in string called string name
-1 .
<html>
<body>
document.writeln(str.charAt(5));
</script>
</body>
</html>
concat(): In JavaScript the concat function is used for combines the text of two strings
and returns a new string.
Syntax: string.concat(string1,string2,…stringx);
<html>
<body>
document.writeln(str.concat(str1));
</script>
</body>
</html>
INDEXOF(): Searches and (if found) returns the index number of the searched character or
substring within the string. If not found, -1 is returned. “Start” is an optional argument
specifying the position within string to begin the search. Default is 0.
Syntax: string.indexOf(searchvalue,start)
var n = str.indexOf("welcome");
LASTINDEXOF(): It returns the index within the calling string object of the first occurrence
of the specified value or -1 if not found.
SYNTAX: string.lastIndexOf(searchvalue,start)
document.write(myString.lastIndexOf('k'));
<!DOCTYPE html>
<html>
<body>
document.write(myString.lastIndexOf('k'));
</script>
</body>
</html>
SPLIT():The split() method is used to split a string object into an array of strings by
separating the string into substrings.
SYNTAX: string.split(separator,limit)
<!DOCTYPE html>
<html>
<body>
document.write(res);
</script>
</body>
</html>
SUBSTR(); :it returns the characters in a string beginning at the specified location through
the specified number of characters.
SYNTAX: string.substr(start,length)
<!DOCTYPE html>
<html>
<body>
document.write(res);
</body>
</html>
SUBSTRING():
The substring() method extracts the characters from a string, between two specified
indices, and returns the new sub string.
This method extracts the characters in a string between "start" and "end", not
including "end" itself.
SYNTAX: string.substring(start,end)
<!DOCTYPE html>
<html>
<body>
document.write(res);
</script>
</body>
</html>
SYNTAX: string.toLowerCase()
<!DOCTYPE html>
<html>
<body>
document.write(res);
</script>
</body>
</html>
SYNTAX: string.toUpperCase()
<!DOCTYPE html>
<html>
<body>
document.write(res);
</script>
</body>
</html>
SYNTAX: boolean.valueOf()
<!DOCTYPE html>
<html> <body>
The math object provides properties and methods for mathematical constants and functions.
Unlike the global objects. math is not a constructor. Mathematical functions and values are
part of built in JavaScript object called Math. All functions and attributes used in
mathematics must be accessed through this object only as
MATH METHODS
1) abs(value): Returns the absolute value of a number.
2) acos(value): Returns the arccosine (in radians) of a number.
3) asin(value): Retuns the arctangent ( in radians) of a number.
4) atan(value): Returns the arctangent (in radians) of a number.
5) Atan2(value1,value2): Returns the arctangent of the quotient of its
arguments.
6) ceil(value): Returns the smallest integer greater than or equal to a number.
7) cos(value):returns the cosine of a number.
8) sin(value) :Returns the sine of a number.
9) Tan(value): Returns the tangent of a number.
10) Log(value): Returns the natural logarithm of a number.
11) Max(val1,val2): Returns the biggest of the two values passed in
12) Min(val1,va2):Returns the smallest of zero or more numbers.
13) Pow(value power): Returns base to the exponent power, that is, base
exponent.
var value=Math.floor(10.23);
document.write("<br> fouth value:"+value);
var value=Math.round(0.5);
document.write("<br> fifth value:"+value);
var value=Math.acos(-1);
document.write("<br> sixth value:"+value);
var value=Math.asin(-1);
document.write("<br> seventh value:"+value);
var value=Math.log(3);
document.write("<br> eight value:"+value);
var value=Math.max(1,5);
document.write("<br> ninth value:"+value);
var value=Math.min(1,9);
document.write("<br> tenth value:"+value);
var value=Math.sqrt(2);
document.write("<br> elevnth value:"+value);
var value=Math.exp(3)
document.write("<br> twelth value:"+value);
}
</script>
</body>
</html>
Most of the objects that you will use in your scripting will be pre built ones that came
with the browser.
The document object: A document is a webpage that is being either displayed or created
the document has a number of properties that can be accessed by JavaScript programs and
used to manipulate the content of the page.
JavaScript document object provides the access of the entire webpage. That includes the
<head>section and <body>definition and various objects with in the page, such as links
and forms and anchors.
. layers . close()
The Window object: The browser window is a mutable(changeable) object that can be
addressed by javascript code. Some of the properties and methods that are available from
window objects.
. width=pixels . height=pixels
The Form object: Two aspects of the form can be manipulated through javascript. First the
data is entered onto your form can be checked at submission. Second you an actually build
forms through javascript
. onclick = “method”
. onSubmit = “method”
. onReset = “method”
The browser object: The browser is a JavaScript object can be queried from within your
code. For historical reasons the browser object is actually called the navigator object. The
following are the properties
The Date object: JavaScript includes a well developed date class which provides functions
to perform many different date manipulations. In java script data and time represent the
number of milliseconds since 1 st January 1970 UTC. It has two separate notions i.e. UTC
and LOCAL
UTC: UNIVERSAL TIME also know as Greenwich Mean Time which is the standard time
throughout the world
. Date() . Date(milliseconds)
. Date(string) . Date(year,month,day[,hour,minute,second])
. Parse(string)
JavaScript document object provides the access of the entire webpage. That includes the
<head>section and <body>definition and various objects with in the page, such as links
and forms and anchors.
PROPERTY DESCRIPTION
bgcolor It is used to set / get the background color attribute of body tag
fgcolor It is used to set / get the foreground color attribute of body tag
forms It is used to get an array of all the form objects in the document page
links It is used to get an array of all the link objects in the document or webpage
vlinkColor It is used to get/set the “visited link” color attribute of body tag
Title It is used to set / get the tile of the document using JavaScript
Methods: The methods are surrounding a parameter “[]” but the parameters are optional.
METHODS DESCRIPTION
writeln(“string”) Wrties to the document or document stream the “string” entered and
inserts a new line character at the end.
<!DOCTYPE html>
<html>
<title>javascript</title>
<body>
<script>
document.bgColor = "green";
document.fgColor="yellow";
document.write("document.bgColor = "+document.bgColor+"<br>");
document.write("document.fgColor = "+document.fgColor+"<br>");
document.write("document.title = "+document.title+"<br>");
document.write("document.location = "+document.location+"<br>");
document.write("document.alinkColor = "+document.alinkColor+"<br>");
document.write("docuemnt.lastModified = "+document.lastModified+"<br>");
</script>
</body>
</html>
(or)
A window object is the top-level for each document, location and history object. The
browser window is a changeable object that can be addressed by JavaScript code.
Syntax: [windowVar=][window].open(“URL”,”windowName”,[“windowFeatures”])
windowVar is the name that you create for the new window.
WindowName portion respresents window name to use in the target attribute of <form> or
<A>tag.
WINDOW FEATURES
Location Used to display / hide the location bar in the new window [yes/no] or [1/0]
Status It is used to display / hide the status bar in the new window [yes/no] or [1/0]
Property Description
closed Returns a Boolean value indicating whether a window has been closed or not
defaultStatus Sets or returns the default text in the status bar of a window
frames Returns an array of all the frames (including iframes) in the current window
Method Description
confirm() Displays a dialog box with a message and an OK and a Cancel button
prompt() Displays a dialog box that prompts the user for input
<!DOCTYPE html>
<html>
<head>
<script>
ob='toolbar=yes,location=yes,directories=no,status=no,menubar=yes,'
ob+='scrollbars=no,resizable=yes,width=500,height=300';
x.document.write("<H2><CENTER>"+msg+"</CENTER></H2>");
x.document.write("<FORM><CENTER>");
x.document.write("</CENTER></FORM>");
</script>
</head>
<body>
</body>
</html>
A form is object and can be manipulated in tow aspects through JavaScript. First the
data that is entered onto your form can be checked at submission. Second you can build
form through JavaScript. The <form> has number of attributes.
Property Description
.name The name of the form, which will be used when referencing objects with in the form
The URL of the CGI(common gateway interface) to which the data entered by the user
.action
will be sent
It is optional function to all or inline script to execute before the form data is submitted
.onsubmit
to server
Method Description
It is applied to all form elements. The event is triggered When the user clicks on that
onclick
element. It is not triggered to force events through the click() method
This event can only be triggered by the form itself and occurs when a form is
onsubmit
submitted
onReset This is a form only event and is triggered when a form is reset by the user
The browser is a JavaScript object and can be queried from within your code. The browser
object is actually called the navigator object
Property Description
<html>
<body>
document.write("navigator.appName"+navigator.appName+"<br>");
document.write("navigator.appVersion"+navigator.appVersion+"<br>");
document.write("navigator.appCodeName"+navigator.appCodeName+"<br>");
document.write("navigator.userAgent"+navigator.userAgent+"<br>");
</script>
</body>
</html>
(OR)
JavaScript includes a well developed Date class which provides functions to perform
many different date manipulations. In JavaScript, date and time represent the number of
milliseconds since 1st January 1970 UTC. JavaScript like most programming systems, has
two separate notions of time UTC and local.
UTC is universal time, also know as Greenwich Mean Time, which is the standard
time throughout the world.
Local time is the time on the machine which is executing the script.
A JavaScript date object can represent dates from --100,000,000 to 100,000,000 days
Date (milliseconds) the new date object based upon the number of milliseconds which
have elapsed since 00:00:00 hours on 01/01/1970.
Date (string): The date object based upon the contents of a text string. The string must be
in the format which is created by the date. Parse() function
Method Description
date() Returns the current date and time
getDate() Returns the date, between the days of 1 and 31
getDay() Returns the day of the week, numbered 0 to 6
getMonth() Returns the month , numbered 0 to 11
getFullYear() Returns the year as a four digit number
getHours() Returns the current hour from 0 to 23
getMinutes() Returns the current minutes from 0 to 59
getSeconds() Returns the current seconds from 0 to 59
getMilliseconds() Returns the current milliseconds form 0 to 999
getTime() Returns the milliseconds since January 1, 1970
setDate() Specifies the day of the month 1-31
setMonth() Specifies the day of the month 0-11
setFullYear() Specifies the year in a Date object- four digits
<!DOCTYPE html>
<html>
<script>
document.write("Today:"+today);
document.write("<br>Year is:"+today.getYear());
document.write("<br>Hours is:"+today.getHours());
</script>
<body></body>
</html>
(OR)
(OR)
JavaScript is an event driven system. An event is any change that the user makes to the
state of the browser. For instance a word processor simply responds to you actions
JavaScript event handling can be quite a complex issue different manufactures have
implemented their own way of capturing and handling events. Internet explorer has a large
set of complicated, but useful, event routines which can be used t extend its functionality
beyond the web and onto the windows desktop the following are the event handler’s
properties.
Attributes Description
onkeypress Refers to when a keyboard key is pressed and /or held down
onunload Refers to when a page is unloaded either by being closed or a link is clicked
<html>
<head>
<script type="text/javascript">
<!--
function over() {
alert("Mouse Over");
function out() {
alert("Mouse Out");
//-->
</script>
</head>
<body>
</body>
</html>
(OR)
Validation is simply the process of ensuring that some data might be correct data for a
particular application. Data validation is the process of ensuring that users submit only the
set of characters which you require. It is not the process of ensuring that the data is any
way accurate.
If a program accepts data from a remote data looger and that input is always going
to be in a particular range, then the program knows that data outside the range is invalid
and should not be accepted..
<html>
<head>
<body>
if (result)
alert ("found"+result);
else
</script>
</body>
</html>
(OR)
(OR)
JavaScript provides three built-in window types that can be used from application
code. For instance you may need them to click a confirmation button before submitting
information to your database.
ALERT BOX: the alert box is useful for alerting the users to something important. When a
javascript alert box is triggered. A small box will pop up and display the text that is
specified in the javascript code. The alert box pops up with an Ok button which the user has
to press to continue
<html>
<head>
<script type="text/javascript">
<!--
function W() {
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
CONFIRM BOX: The confirm method shows a dialog box that contains a message and an
OK and Cancel button. If the user presses the OK button the confirm method returns true. It
the user presses cancel the method returns false
<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
return true;
}else{
return false;
//-->
</script>
</head>
<body>
<form>
</form>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
//-->
</script></head>
<body>
<form>
</form>
</body></html>
CHARACTERSTICS OF PHP
Five important characteristics make PHP's practical nature possible:
Simplicity
Efficiency
Security
Flexibility
Familiarity
Web Server - PHP will work with virtually all Web Server software, including Microsoft's Internet
Information Server (IIS) but then most often used is freely available Apache Server. Download Apache
for free here: http://httpd.apache.org/download.cgi
Database - PHP will work with virtually all database software, including Oracle and Sybase but most
commonly used is freely available MySQL database. Download MySQL for free here:
http://www.mysql.com/downloads/index.html
PHP Parser - In order to process PHP script instructions, a parser must be installed to generate HTML
output that can be sent to the Web Browser. This tutorial will guide you how to install PHP parser on
your computer
We will create a very simple PHP script that displays the text "Hello, world!" in the browser
window. Ok, click on the WampServer icon somewhere on your Windows task bar and select
the "www directory". Alternatively you can access the "www" directory through
C:\wamp\www. Create a subdirectory in "project".
Now open up your code editor and create a new PHP file. Start with an
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
local
global
EXPLAIN ABOUT DATA TYPES IN PHP?
PHP supports total eight primitive data types: Integer, Floating point number or Float, String,
Booleans, Array, Object, resource and NULL. These data types can be broken into three
categories
1. Scalar Data types 2. Compound Data types 3. Special Data types
Scalar data types: Scalar data types are capable of containing a single item of information.
Several data types fall under this category including Boolean, Integer, Float and String
Boolean: A Boolean variable represents truth, supporting only two values TRUE or FALSE.
Alternatively we can use zero to represent FALSE & nonzero to represent TRUE
Integer: An integer is quite simply a whole number or that doesn’t contain fractional parts.
Float: Float data type allows you to specify numbers that contain fractional parts
String: A string is a sequence of characters treated as a single unit; such units are typically
2. Compound data types: Compound data types allow us to aggregate multiple items of the
Array: An array is a variable that can hold more than one value at a time. It is useful to
Object: An object is a data type that not only allows storing data but also information on, how to
process that data. An object is a specific instance of a class which serves as templates for objects.
Objects are created based on this template via the new keyword. Every object has properties and
3. SPECIAL DATA TYPES: Special data types encompass those types serving some sort of specific
purpose, which makes it impossible to group them in any other type category.
Resource: PHP is often used to interact with external data sources such as databases,
files &network streams. Typically this interaction takes place through "handles? EX: such
Null: The special NULL value is used to represent empty variables in PHP. A variable of
Arithmetic Operators: The arithmetic operators perform various mathematical operations and
Assignment operators: - Used to assign a data value to a variable. The simplest form of assignment
operator justassigns some value
3. String Operators: PHP's string operators provide a convenient way in which to concatenate strings
together.
4. Increment & Decrement Operators: Providing shortened means by which you can add 1 to
or subtract 1 from the current value of a variable.
101
5. Logical Operators: Logical operators make it possible to direct the flow of a program, and are
used frequently with control structures, such as the if conditional and the while and for loops.
6. Equality Operators: Equality operators are used to compare two values, testing for
equivalence.
8. Bit-wise Operators: Bitwise operators examine and manipulate integer values on the level of
individual bits that make up the integer value.
102
IF STATEMENT:
The if statement executes some code if the specified condition is true.
Syntax
103
if (condition) {
code to be executed if condition is true;
}
LOOPS STATEMENTS
When we write code, we want the same block of code to run over and over again in a row.
Instead of adding several almost equal code-lines in a script, we can use loops to perform a task
like this.
104
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of time
While Loop
The while loop executes a block of code as long as the
specified condition is true.
Syntax
while (condition is true) {
code to be executed; }
Do...While Loop
The do...while loop will always execute the block of code once, it will then check the condition,
and repeat the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
For Loops
PHP for loops execute a block of code a specified number of times. The for loop is used when
we know in advance how many times the script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
105
BREAK STAEMENT
The keyword break ends execution of the current for, for each, while,
do while or switch structure. When the keyword break executed inside a loop
the control automatically passes to the first statement outside the loop.
DEFINE ARRAY? EXPLAIN HOW TO CREATE AN ARRAY AND TYPES OF ARRAY
IN PHP?
An array is a data structure that stores one or more similar data type of values in a
single value.
Advantage of PHP Array:
Less Code: We don't need to create multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can easily sort the elements of array.
CREATING ARRAYS
Arrays are complex variables that stores multiple or a group of values under a single variable
name.
<?php
$color1 = "Red";
$color2 = "Green";
$color3 = "Blue";
?>
Types of Arrays in PHP:
There are three types of arrays that you can create. These are:
• Indexed array - An array with a numeric key.
• Associative array - An array where each key has its own specific value.
• Multidimensional array - An array containing one or more arrays within itself.
Indexed Arrays:
A numeric array stores each element with a numeric ID key. That means the keys
have no real relation to the value other than the value?s position in the array. There are two
ways to create numerical arrays:
Syntax 1:
$colors=array("red", "green", "blue", "yellow", "black")
Syntax 2:
$colors[0]= "red"; $colors[1]= "green"; $colors[2]= "blue"; $colors[3]= "yellow"; $colors[4]=
"black";
Associative Arrays:
In an associative array, the keys assigned to values can be arbitrary and user defined strings. In
the following example the array uses keys instead of index numbers
Syntax:
$protocols = array ("TCP" => "Transmission Control Protocol", "IP" => "Internet
Protocol", "UDP" => "User Datagram Protocol", "FTP" => "File Transfer Protocol");
Multidimensional Arrays:
The multidimensional array is an array in which each element can also be an array and each
element in the sub-array can be an array or further contain array within itself and so on.
There are some functions in strings by using that commands we can manipulate the
strings according to that function.
1) Strlen() 2) strstr() 3) strpos() 4) substr() 5) strtok()
Strlen(): The strlen() is used to determine the length of a string. strlen() requires a string and returns an
integer representing the number of characters in the variable you have passed it.
if (strlen($membership) == 4) {
print "Thank you!";
} else {
print "Your 4 digits<P>";
}
strstr(): The strstr() is used to test whether a string exists embedded within another
string.strstr() requires two arguments: a source string and the substring you want to find within
it
$membership = "pAB7";
if (strstr($membership, "AB"))
{
print "Thank you. Don't forget soon!";
} else {
print "Thank you!";
}
substr(): The substr() function returns a portion of a string based on the start index and length
of the portion you are looking for. This function demands two arguments: a source string and
the starting index
$test = "mangofruit";
print substr($test,5); // prints "fruit"
print substr($test,5,2) // prints "fr"
110
strpos(): The strpos() function tells us both whether a string exists within a larger string and
where it is to be found. strpos() requires two arguments: the source string and the substring.
$membership = "message";
if (strpos($membership, "me") === 0) {
print "hello me";
}
strtok(): The strtok() function initially requires two arguments: the string to be tokenized and
the delimiters by which to split the string.
$test = "php.com"
$test .= "OP=dnquery.xp&ST=MS&DBS=2&QRY=developer+php";
$delims = "?&";
$word = strtok($test, $delims);
while (is_string($word)) {
if ($word) {
print "$word<br>";
}
$word = strtok($delims);
}
?>
PROGRAM
<!DOCTYPE html>
<html>
<head>
<title>PHP Date Basic Syntax</title>
</head>
<body>
<?php
echo "Today is : " . date("Y/m/d") . "<br />";
echo "Today is : " . date("Y.m.d") . "<br />";
echo "Today is : " . date("Y-m-d") . "<br />";
echo "Today is : " . date("l") . "<br />";
echo "Today is : " . date("D") . "<br />";
echo "Today date is : " . date("d") . "<br />";
echo "This Month is : " . date("M") . "<br />";
echo "This year is : " . date("Y");
?>
</body>
</html>
Output :
Today is : 2022/04/07 Today is : 2022.04.07
Today is : 2022-04-07 Today is : Thursday
Today is : Thu Today date is : 07
This Month is : Apr This year is : 2022
113
UNIT – III
ADVANCED PHP
Advanced PHP: Functions, Advantages of Using functions, Types of functions, creating and
invoking functions, returning values, recursive functions Object Oriented Concepts, File
handling and Data Storage: creating, open/close a file, file operations: read, write, append. File
truncate, file uploading, EOF in PHP.
1. Code Reusability: PHP functions are defined once and can be invoked many times, like in other
programming languages.
2. Less Code: With function, logic is written only once, and it will be reused. so it reduces the need
of writing the same logic many time in the script.
3. Easy to understand: PHP functions separate the programming logic from the actual code. So it is
easier to understand the flow of the application because every logic is divided in the form of
functions.
4. Easy to maintain code: Function created once can be used many times, so any changes
made inside a function is automatically implemented at all the places without touching the
several files
114
BUILT-IN FUNCTIONS: HP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions. To use those we just need to call
them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so on.
USER DEFINED FUNCTIONS: Apart from the built-in functions, PHP allows us to create our own
customized functions called the user-defined functions.
Using this we can create our own packages of code and use it wherever necessary by simply
calling it.
PHP allows us two ways in which an argument can be passed into a function
1) CALL BY VALUE (OR) PASS BY VALUE
2) CALL BY REFERENCE (OR) PASS BY REFERENCE
CALL BY VALUE: On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains unchanged. That
means a duplicate of the original value is passed as an argument.
116
<?php
function swap($arg1, $arg2){
echo "inside function before swapping: arg1=$arg1 arg2=$arg2\n";
$temp=$arg1;
$arg1=$arg2;
$arg2=$temp;
echo "inside function after swapping: arg1=$arg1 arg2=$arg2\n";
}
$arg1=10;
$arg2=20;
echo "before calling function : arg1=$arg1 arg2=$arg2\n";
swap($arg1, $arg2);
echo "after calling function : arg1=$arg1 arg2=$arg2\n";
?>
OUTPUT
before calling function : arg1=10 arg2=20
inside function before swapping: arg1=10 arg2=20
inside function after swapping: arg1=20 arg2=10
after calling function: arg1=10 arg2=20
EXAMPLE
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?> OUTPUT IS : 10
Class − This is a programmer-defined (OR) USER DEFINED data type, which includes local
functions as well as local data. You can think of a class as a template for making many instances
of the same kind (or class) of object.
Object − An individual instance of the data structure defined by a class. You define a class once
and then make many objects that belong to it. Objects are also known as instance.
Member Variable − These are the variables defined inside a class. This data will be invisible to
the outside of the class and can be accessed via member functions. These variables are called
attribute of the object once an object is created.
Member function − These are the function defined inside a class and are used to access object
data.
120
Inheritance − When a class is defined by inheriting existing function of a parent class then it is
called inheritance. Here child class will inherit all or few member functions and variables of a
parent class.
Parent class − A class that is inherited from by another class. This is also called a base class or
super class.
Child Class − A class that inherits from another class. This is also called a subclass or derived
class.
Polymorphism − This is an object oriented concept where same function can be used for
different purposes. For example function name will remain same but it take different number of
arguments and can do different task.
Data Abstraction − Any representation of data in which the implementation details are hidden
(abstracted).
Encapsulation − refers to a concept where we encapsulate all the data and member functions
together to form an object.
Constructor − refers to a special type of function which will be called automatically whenever
there is an object formation from a class.
Destructor − refers to a special type of function which will be called automatically whenever an
object is deleted or goes out of scope.
121
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
} function get_name() {
return $this->name;
}}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
</body> </html> output : apple banana
123
<?php <?php
class ClassName { class greeting {
public static function staticMethod() { public static function welcome() {
echo "Hello World!"; echo "Hello World!";
} }
} }
?> greeting::welcome(); ?>
FINAL KEY WORD: PHP 5 introduces the final keyword, which prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is being defined final then it cannot be
extended.
Syntax: EXAMPLE
final function name_of_the_function() <?php
{ final class MyClass {
} final class Class_Name public $name = "GSK";
{ } }
class AnotherClass extends MyClass{};
?>
SINGLE LEVEL INHERITANCE: In single-level inheritance, we inherit one class into another class.
In this process, One is parent class and the other is child class. This type of inheritance also
known as simple inheritance.
MULTILEVEL INHERITANCE:
In this type of inheritance, there will be more than 2 classes involved. In Multilevel inheritance
Parent class will be inherited by a child and then further child class will be inherited by another
child class.
HIERARCHICAL INHERITANCE:
When more than one class inherit to a single class. This type of inheritance known as
Hierarchical Inheritance.
126
An Interface allows the users to create programs, specifying the public methods that a class
must implement, without involving the complexities and details of how the particular methods are
implemented. It is generally referred to as the next level of abstraction. It resembles the abstract
methods, resembling the abstract classes. An Interface is defined just like a class is defined but with the
class keyword replaced by the interface keyword and just the function prototypes. The interface
contains no data variables. The interface is helpful in a way that it ensures to maintain a sort of
metadata for all the methods a programmer wishes to work on.
Encapsulation also allows a class to change its internal implementation without hurting
the overall functioning of the system.
Binding the data with the code that manipulates it.
It keeps the data and the code safe from external interference.
EXAMPLE
<?php
class Job
{
public $Job_name;
public $Job_id;
function __construct($job_names, $job_ids)
{
$this->Job_name = $job_names;
$this->Job_id = $job_ids;
}
public function Job_details()
{
echo "Job name is: $this->Job_name Job id is: $this->Job_id";
}
}
$obj = new Job("Web Developer", "096847");
echo $obj->Job_details();
?>
OUTPUT
Job name is: Web Developer
Job id is: 096847
130
3) fwrite() : New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to written to file. It can
contain optional third argument where length of text to written is specified
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
4) fclose() : file is closed using fclose() function. Its argument is file which needs to be closed
131
<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
MODES OF FILE (OR) FILE MODES
1) “w” – Opens a file for write only. If file not exist then new file is created and if file
already exists then contents of file is erased.
2) “r” – File is opened for read only.
3) “a” – File is opened for write only. File pointer points to end of file. Existing data in file is
preserved.
4) “w+” – Opens file for read and write. If file not exist then new file is created and if file
already exists then contents of file is erased.
5) “r+” – File is opened for read/write.
6) “a+” – File is opened for write/read. File pointer points to end of file. Existing data in file
is preserved. If file is not there then new file is created.
7) “x” – New file is created for write only.
132
UNIT – IV
WORKING WITH FORMS IN PHP
DEFINE FORM? EXPLAIN HOW TO CREATE A FORM IN PHP?
Form in PHP is similar to the forms that are built using HTML except the syntax used. In PHP,
forms use the GET and POST methods to print or retrieve the data entered by the user.
When the user enters all the details required in the form and submits the form using the
submit button the form is then further sent for processing and the action is performed on the
basis of whatever is mentioned in the action function. The form is then sent for further
processing using GET or POST methods whichever is mentioned while designing the form.
CREATION OF FORM
To create a form, you use the <form> element as follows:
<form action="form.php" method="post">
</form>
The <form> element has two important attributes:
action: specifies the URL that processes the form submission. In this example, the form.php
will process the form.
method: specifies the HTTP method for submitting the form. The most commonly used form
methods are POST and GET. In this example, the form method is post.
POST method
If a form uses the POST method, the web browser will include the form data in the HTTP
request’s body. After submitting the form, you can access the form data via the associative
array $_POST in PHP.
GET method
When you submit a form using the GET method, you can access the form data in PHP via the
associative array $_GET.
Unlike the POST method, the GET method appends the form data in the URL that
processes the form.
133
EXAMPLE
<!DOCTYPE HTML>
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form> </body> </html>
Forms provide an interface for collecting, displaying, and delivering information and are
used as a key component of HTML. Forms have different types of fields such as text input fields,
radio buttons, checkboxes, submit and reset button etc.
GET METHOD
Get appends the form data to the end of URL, in the form of name=value pairs.
Never use GET to send sensitive data, because the submitted form data is visible in the
URL.
The length of a URL is limited to 2048 characters. So, user cannot send large data.
Useful for form submissions where a user wants to bookmark the result.
GET is good for non-secure data, like query strings.
134
POST METHOD
POST appends the form data inside the body of the HTTP request. So, the submitted
form data is not visible to anyone.
POST has no size limitations and can be used to send large amounts of data.
Form submissions with POST cannot be bookmarked.
FORM ELEMENTS (OR) FROM INPUT TAGS
The primary element of forms which helps user to create various controls using its type
attributes. It is an independent tag which means it does not have closing tags. It supports 13
form controls with different structure.
Each input element with in the form is sent to the server as name/value pairs.
TEXT BOX: A rectangular shaped field in which a user can enter text is considered as text box. A
text box is the type of input tag with name, size max length and values.
PASSWORD: The password input type creates a single line empty text box where the user can
enter text into it. It is similar to text fields. It display the text in the fields like stars (*) and dot (.)
that means it creates masked fields in passwords
CHECKBOXES: A checkbox is represented by square icon. This is used for multiple selections.
The user can select or deselect by clicking on it. A selected check box is usually show in dark
grey, and unselected check box is shown in light grey. It often used in series.
RADIO BUTTONS: Radio buttons are a group of buttons from which only one can be selected at
a time.
135
ACTION BUTTONS: - They are two types actions buttons they are submit and reset. Where the
user clicks on the submit button, the values that have been entered into the form are sent the
program that process the form. whereas reset button is to allow to clear all of the input
entered in the form and starts from the first.
SELECT: The select tag allow to choose any subset of items from a group, the items given in
select tag are usually rendered in the style of a pop-up menu. The items are indicated by using
<option> tag. Here in <option>tag the end tag is optional
TEXT AREA: The <text area> tag defines a multi-line text input control. A text area can hold an
unlimited number of characters, and with fixed-width font (i.e. courier) the area can be
specified by the cols and rows attributes.
PROGRAM
<html>
<form action = "sample.php" method = "post">
<b>Please tell us about Our website:</b><p>
<b>Name:</b><br>
<input type="text" name="name" size="15" maxlength="25" value=""><br>
<b>Email:</b><br>
<input type="text" name="email" size="15" maxlength="45" value=""><br>
<b>How frequently do you visit our site?:</b><br>
<select name="frequency">
<option value="">Site frequency:
<option value="0">My first Visit
<option value="1">1 time a month
<option value="2">Once in a month
<option value="3">Several times a week
<option value="4">Every day
</select><br>
<b>I frequently purchase the following products:</b><br>
136
<html><body>
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
</body></html>
welcome.php
137
<?php
$name=$_GET["name"]; //receiving name field value into $name variable
echo "Welcome, $name";
?>
In the above program, user enters his name and clicks on Visit button, then the form data is
added to URL and a request is sent to welcome.php program which is there in the webserver.
Upon receiving the request, program retrieves the user data from the URL and displays it on the
output.
Simple example to receive data from post request in PHP.
form.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Email:</td><td> <input type="email" name="email"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
login.php
<?php
$name=$_POST["name"];//receiving name field value into $name variable
$email=$_POST["email"];//receiving email field value into $email variable
echo "Welcome $name, your email address is: $email";
?>
PHP and HTML can be placed on the same page interchangeably by embedding PHP code. In
order to embed PHP code with HTML, the PHP must be set apart using PHP start and end tags.
The PHP tags tell the web server where the PHP code starts and ends. The PHP parser
recognizes three styles of start and end tags.
<?php
$num_to_guess = 42;
$message = "";
if ( ! isset( $guess ) )
$message = "Welcome to the guessing machine!";
elseif ( $guess > $num_to_guess )
$message = "$guess is too big! Try a smaller number";
elseif ( $guess < $num_to_guess )
$message = "$guess is too small! Try a larger number";
else // must be equivalent
$message = "Well done!";
?>
<html>
<head>
<title>Listing 9.9 A PHP number guessing script</title>
</head>
<body>
<h1>
<?php print $message ?>
</h1>
<form method="POST">
Type your guess here: <input type="text" name="guess">
</form> </body> </html>
139
DEFINE RDBMS?
RDBMS stands for Relational Database Management System. It is a program used to maintain a
relational database. It uses SQL (Structured Query Language) queries to access the data in the
database.
A relational database defines database relationships in the form of tables. The tables are
related to each other - based on data common to each.
Database is a collection of tables. Each table is a collection of related data entries,and it
consists of columns and rows. Column holds specific information about every record in the
table. Record (or row) is each individual entry that exists in a table
140
1) SELECT statement is used to select data from a database. The data returned is stored in a
result table, called the result-set.
Syntax: SELECT column1, column2, ... FROM table_name;
Here, column1, column2, are the field names of the table you want to select data from. If you
want to select all the fields available in the table,
Syntax: SELECT * FROM table_name;
141
2) UPDATE The statement is used to modify the existing records in a table.While updating
records in a table, WHERE clause is used in the UPDATE statement. The WHERE clause specifies
which record(s) that are to be updated
Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
3) DELETE The DELETE statement is used to delete existing records in a table. While deleting
records in a table, observe that WHERE clause is used in the DELETE statement. The WHERE
clause specifies which record(s) is to be deleted. If you omit the WHERE clause, all records in
the table will be deleted. Table schema remains in the database.
Syntax: DELETE FROM table_name WHERE condition;
4) INSERT INTO This statement is used to insert new records in a table. It is possible to write
the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query.
INSERT INTO table_name VALUES (value1, value2, value3, ...);
5) CREATE DATABASE The CREATE DATABASE statement is used to create a new SQL database
Syntax: CREATE DATABASE database name;
8) ALTER TABLE statement is used to add, delete, or modify columns in an existing table. It is
also used to add and drop various constraints on an existing table.
ALTER TABLE - ADD Column
To add a new column in an existing table, use the following syntax:
ALTER TABLE table_name ADD column_name datatype;
ALTER TABLE - DROP COLUMN
ALTER TABLE table_name DROP COLUMN column_name;
10) CREATE INDEX statement is used to create indexes in tables. Indexes are used to retrieve
data from the database more quickly than otherwise. The users cannot see the indexes, they
are just used to speed up searches/queries.
Syntax: CREATE INDEX index_name ON table_name (column1, column2, ...);
MySQL is one of the most popular relational database management software that is widely
used in today's industry. It provides multi-user access support with various storage engines.
It allows us to implement database operations on tables, rows, columns, and indexes.
It defines the database relationship in the form of tables (collection of rows and
columns), also known as relations.
It provides the Referential Integrity between rows or columns of various tables.
It allows us to updates the table indexes automatically.
143
Step 9: Now, select the Authentication Method and click on Next. Here, I am going to select the
first option.
Step 10: The next screen will ask you to mention the MySQL Root Password. After filling the
password details, click on the Next button.
Step 11: The next screen will ask you to configure the Windows Service to start the server. Keep
the default setup and click on the Next button.
Step 12: In the next wizard, the system will ask you to apply the Server Configuration. If you
agree with this configuration, click on the Execute button.
Step 13: Once the configuration has completed, you will get the screen below. Now, click on the
Finish button to continue.
Step 14: In the next screen, you can see that the Product Configuration is completed. Keep the
default setting and click on the Next-> Finish button to complete the MySQL package
installation.
Step 15: In the next wizard, we can choose to configure the Router. So click on Next->Finish and
then click the Next button.
Step 16: In the next wizard, we will see the Connect to Server option. Here, we have to mention
the root password, which we had set in the previous steps. In this screen, it is also required to
check about the connection is successful or not by clicking on the Check button. If the
connection is successful, click on the Execute button. Now, the configuration is complete, click
on Next.
Step 17: In the next wizard, select the applied configurations and click on the Execute button.
Step 18: After completing the above step, we will get the following screen. Here, click on the
Finish button.
Step 19: Now, the MySQL installation is complete. Click on the Finish button.
MySQL implements a database as a directory that stores all files in the form of a table. It allows
us to create a database mainly in two ways:
1) MySQL Command Line Client
2) MySQL Workbench
MySQL Workbench
It is a visual database designing or GUI tool used to work with database architects,
developers, and Database Administrators. This visual tool supports SQL development, data
modeling, data migration, and comprehensive administration tools for server configuration,
user administration, backup, and many more. It allows us to create new physical data models,
E-R diagrams, and SQL development (run queries, etc.).
Server: It is the name of a host that runs the database server. By default, its value will be
lcalhost:3306.
User: It is the name of a user who accesses the database. If we will not specify this field, it
assumes the default value that will be the name of a user that owns the server process.
Password: It is the password of a user whose database you are going to access. If we will not
specify this field, it assumes the default value that will be an empty password.
New_link: If we make a second call with the same arguments in the mysql_connect() function,
MySQL does not establish a new connection. Instead, we will get the identifier of the already
opened database connection.
If we want to disconnect from the MySQL database server, we can use another PHP
function named mysql_close(). It accepts only a single parameter that will be a connection
returned by the mysql_connect() function.
</head> <body>
<?php
$servername = 'localhost:3306';
$username = 'javatpoint';
$dbpass = 'jtp123';
$conn = mysql_connect($servername, $username, $password);
if(! $conn ) {
die('Connection failed: ' . mysql_error());
}
echo 'Connection is successful';
mysql_close($conn);
?>
</body>
</html>
UNIT – V
WORKING WITH COOKIES AND USER SESSIONS
$_COOKIE is a PHP built in superglobal variable. It is an array type and stores the names and
values of all the set cookies. The number of values that the $_COOKIE array can contain
depends on the memory size set in php.ini. The default value is 1GB.
EXAMPLE
<?php
print_r($_COOKIE); //output the contents of the cookie array variable
?>
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie() function.
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date to the past time. i.e.,
negative number.
USE OF SESSIONS
You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
You want to pass values from one page to another.
You want the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to
passing them in the URL
You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.
The items you decide to store in the user's session should be those items you can imagine using
quite a bit and that would be inefficient to continually extract from the database. For example,
153
suppose that you have created a portal in which users are assigned a certain level, such as
administrator, registered user, anonymous guest, and so forth. Within your display modules,
you would always want to check to verify that the user accessing the module has the proper
permissions to do so. Thus, "user level" would be an example of a value stored in the user's
session, so that the authentication script used in the display of the requested module only has
to check a session variable there would be no need to connect to, select, and query the
database.
Each of those functional elements could be stored in a session. When the user logs in, the
application would load all relevant values into the user's session and would react accordingly
for each subsequently requested page. Should the user decide to change her preferences, she
could do so while logged in you could even pre populate a "preferences" form based on the
items stored in the session rather than going back to the database to retrieve them. If the user
changes any preferences while she is logged in, simply replace the value stored in the
$_SESSION super global with the new selection no need to force the user to log out and then
log back in again.