30_WEB_PROGRAMMING
30_WEB_PROGRAMMING
1. Internet:
The Internet is the foundation of modern communication, acting as a global network of
interconnected devices like computers, smartphones, servers, and data centres. It uses a
standardised set of communication protocols (TCP/IP) to allow these devices to communicate
with one another, sharing data and resources.
The internet is hardware-based, consisting of routers, switches, transmission lines (fibre
optics and satellite links), and servers. It supports various services like email, file transfers,
streaming, and the World Wide Web (WWW).
2. WWW (World Wide Web):
Built on top of the internet, the World Wide Web is a system that allows users to access and
navigate interlinked web pages. It is a software-based service using the internet’s
infrastructure. When you visit websites, view web pages, or interact with online content, you
engage with the WWW.
The WWW functions by using hypertext, allowing users to click links and navigate between
documents. It is based on languages like HTML (Hypertext Markup Language), which
structures the content of web pages.
3. Web Browser:
A web browser is a software application that allows users to interact with the World Wide
Web. It retrieves and displays web pages from a web server.
Some common web browsers include Google Chrome, Mozilla Firefox, Safari, and Microsoft
Edge. The browser acts as the client in the client-server relationship: it sends requests for web
pages (via HTTP or HTTPS) to the server and then displays the results on the user’s screen.
4. HTTP (Hypertext Transfer Protocol):
HTTP is the protocol or rules defining how web browsers communicate with web servers. It
is responsible for transmitting the data (text, images, video, etc.) that makes up a web page
from the web server to the web browser.
When you type a URL into a browser, it sends an HTTP request to the web server. The server
then responds by returning the requested web page to the browser. HTTP is a "stateless"
protocol, meaning that each request is treated independently and does not remember past
interactions.
WEB PRORAMMING
Page | 1
WEB PRORAMMING
Page | 2
WEB PRORAMMING
Web Browsers: Users access the web through browsers like Google Chrome, Mozilla
Firefox, Safari, or Edge, which render HTML pages and allow users to view and interact
with web content.
Web Protocols: The web relies on the HTTP (Hypertext Transfer Protocol) and HTTPS
(Hypertext Transfer Protocol Secure) protocols to transmit data between clients (users) and
servers (websites).
Multimedia Content: The web allows for a wide variety of content, including text, images,
videos, audio, and interactive applications.
Page | 3
WEB PRORAMMING
This architecture allows for efficient data management and resource allocation by centralizing
critical functions on the server, which can handle complex processing and large-scale data
storage.
Clients manage user interactions and send specific requests to the server, which processes
these requests and sends back appropriate responses.
The client-server architecture is highly scalable, as it can accommodate more clients by
scaling the server's capabilities or adding additional servers.
This design is prevalent in various applications, including web services, database
management, and email systems, providing a robust framework for developing and managing
complex, distributed systems efficiently.
Page | 4
WEB PRORAMMING
Database: A database is a structured collection of data stored on the server. It stores and
manages data that clients request, ensuring data consistency, integrity, and security.
Page | 5
WEB PRORAMMING
Page | 6
WEB PRORAMMING
URI (Uniform Resource Identifier): It specifies the resource’s location or path on the
server.
HTTP Version: It indicates the version of the HTTP protocol being used (e.g., HTTP/1.1).
Headers: Headers provide additional information about the request, such as the user-agent,
content type, and authentication tokens.
Body: For some HTTP methods like POST and PUT, a request may include a message body
containing data to be sent to the server.
What is an HTTP Response?
An HTTP response is the server’s reply to an HTTP request. It contains information about the
request’s status and often includes the requested resource or data. HTTP responses also have
a specific structure:
Status Line: This line includes the HTTP version, a three-digit status code, and a brief
textual description of the status.
Headers: Similar to request headers, response headers provide metadata about the response,
such as content type, server type, and caching directives.
Body: The response body contains the requested data or resource. For HTML pages, this is
the actual web page content. For images or files, it’s the binary data.
Page | 7
WEB PRORAMMING
Question 5. What is web page and web browser? Explain how to create a
simple web page?
Answer:
When we need any kind of information most of the time we get help from the Internet, and
we get information. The Internet provides us with useful information easily. We use mobile
phones, computers, and tablets. We search for a lot of things in our daily lives, so we get
information about all over the world, but we can not get information by just only getting
connected to the Internet. We need a platform where we can search for our questions. The
platform that provides such kinds of services is called a web browser, without a web browser
internet will not be able to provide information.
What is a Web Browser?
The web browser is an application software to explore www (World Wide Web). It provides
an interface between the server and the client and it requests to the server for web documents
and services. It works as a compiler to render HTML which is used to design a webpage.
Whenever we search for anything on the internet, the browser loads a web page written in
HTML, including text, links, images, and other items such as style sheets and JavaScript
functions. Google Chrome, Microsoft Edge, Mozilla Firefox, and Safari are examples of web
browsers.
What is a Web Page?
A web page is a digital document that is accessible on the World Wide Web (WWW) through
a web browser. It is written in HTML (HyperText Markup Language) and can contain text,
images, links, videos, and interactive elements.
Web pages are typically part of a larger collection of pages that together form a website.
A web page is identified by its URL (Uniform Resource Locator) and is served by a web
server to the client (the user’s device) when requested.
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
Page | 8
WEB PRORAMMING
HTML (Hypertext Markup Language) is the foundation of every web page. It structures and
defines the content on the web using tags. These tags tell the browser how to display the
content, whether it’s text, images, links, or other elements.
<!DOCTYPE html>
<html>
<head>
<title>Title of the Web Page</title>
</head>
<body>
<h1>Main Heading</h1>
<p>This is a paragraph .</p>
</body>
2. <html> Tag:
Purpose: The <html> element wraps all the content of the web page. It is the root element
that contains everything else in the document.
Page | 9
WEB PRORAMMING
<script>: Can be used to include JavaScript files for adding dynamic behavior to the
page.
4. <body> Tag (Visible Content Section)
The <body> tag contains all the visible content of the web page, such as text, images,
links, and media.
Everything inside the <body> section is displayed to users when they visit the web
page.
Page | 10
WEB PRORAMMING
The paragraph tag (<p>) is used to define blocks of text. It automatically adds some space
before and after the text to make the content readable.
Example:
<p>This is a paragraph of text. </p>
Page | 11
WEB PRORAMMING
5. colours
We can use color values for mainly two attributes named bgcolor and color
Possible values for the color are
Many are predefined (red, blue, green,….)
All colors can be specified as a six character hexadecimal value : RRGGBB
#FF000 – red
#888888 – gray
#00FF00 – green
#000000 – black
For example, <body bgcolor=”red”> or <body bgcolor= “888888”>
Example:
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
Page | 12
WEB PRORAMMING
<td>ram</td>
<td>21</td>
<td>gwalior</td>
</tr>
<tr>
<td>sita</td>
<td>20</td>
<td>jabalpur</td>
</tr>
</table>
Page | 13
WEB PRORAMMING
Question 8. Explain the Heading tag and Paragraph tag in HTML with
examples.
Answer:
Examples:
<html>
<head>
<title>HTML Headings </title>
</head>
<body>
<h1>Main Heading (H1)</h1>
<p>This is a paragraph under the main heading.</p>
<h2>Subheading (H2)</h2>
<p>This is a paragraph under a subheading.</p>
</body>
</html>
Page | 14
WEB PRORAMMING
<p>HTML stands for HyperText Markup Language. It is the standard language used to
create web pages and web applications.</p>
<p>This is another paragraph, which will automatically appear below the first one because
paragraphs are block elements.</p>
</body>
</html>
Page | 15
WEB PRORAMMING
Question 9. Explain How to set font color and body background color in
html.
Answer:
Syntax:
<element style="color: color_name_or_hex_value;">Content</element>
Example:
<p style="color: red;">This is a red paragraph.</p>
<h1 style="color: blue;">This is a blue heading.</h1>
<p style="color: #00FF00;">This is a green paragraph using a hex color.</p>
Page | 16
WEB PRORAMMING
Question 10. What is order list in HTML? Explain different types of order
list with example.
Answer:
Page | 17
WEB PRORAMMING
Page | 18
WEB PRORAMMING
Page | 19
WEB PRORAMMING
<li>Second item</li>
<li>Third item</li>
</ul>
Complete Example of Ordered and Unordered Lists:
<html>
<head>
<title>Ordered and Unordered Lists</title>
</head>
<body>
Page | 20
WEB PRORAMMING
</body>
</html>
Page | 21
WEB PRORAMMING
An HTML Description List is used to display a list of items where each item consists of a
term and its description. Unlike ordered or unordered lists, where items are represented in a
sequence or bulleted form, a description list pairs terms and descriptions together.
The HTML tags used for creating a description list are:
<dl>: Defines the description list (stands for "Description List").
<dt>: Defines the term (or name) within the list (stands for "Description Term").
<dd>: Defines the description or definition of the term (stands for "Description Data").
Syntax:
<dl>
<dt>Term 1</dt>
<dd>Description of Term 1.</dd>
<dt>Term 2</dt>
<dd>Description of Term 2.</dd>
</dl>
Example:
<html>
<head>
<title>Description List Example</title>
</head>
<body>
<dl>
Page | 22
WEB PRORAMMING
<dt>HTML</dt>
<dd>HTML stands for HyperText Markup Language. It is the standard language used to
create webpages.</dd>
<dt>CSS</dt>
<dd>CSS stands for Cascading Style Sheets. It is used to style and layout web pages.</dd>
<dt>JavaScript</dt>
<dd>JavaScript is a programming language used to create interactive effects and dynamic
content on web pages.</dd>
</dl>
</body>
</html>
Page | 23
WEB PRORAMMING
The anchor tag (<a>) in HTML is used to create hyperlinks, which link one webpage to
another or to different sections of the same webpage. The <a> tag can be used to link to
external websites, internal pages, email addresses, files, or even specific parts of the same
document (using bookmarks or fragment identifiers).
Syntax:
<a href="URL">Link Text</a>
href: The href (hypertext reference) attribute specifies the destination of the link.
Link Text: This is the clickable text that will be displayed to the user.
Example:
<a href="https://www.example.com">Visit Example.com</a>
Page | 24
WEB PRORAMMING
rel (Relationship)
Specifies the relationship between the current document and the linked document. It is
commonly used for SEO and security purposes.
Example:
<a href="https://www.example.com" target="_blank" rel="noopener">Visit
Example.com</a>
download
Specifies that the link should be used to download a file rather than navigate to it. You can
also specify a custom filename.
Example:
<a href="file.pdf" download="myfile.pdf">Download PDF</a>
name and id (for linking to sections within the same page)
The name attribute is used for older versions of HTML, and id is more modern. They create a
bookmark inside the page that other links can refer to.
Example (for creating a bookmark):
<a href="#section1">Go to Section 1</a>
Page | 25
WEB PRORAMMING
Question 14. Explain how to attach an image in html page. Also explain
various attributes of its.
Answer:
The HTML <img> tag is used to insert an image in a HTML. This tag uses the src attribute
to define the URL of the image file. The <img> tag is empty, it contains attributes only, and
does not have a closing tag.
Page | 26
WEB PRORAMMING
To insert background image on HTML page, use the HTML style attribute and the
CSS background-image property
Example:
<html>
<head>
<style>
p{
background-image: url('3.jpeg');
background-repeat: no-repeat;
}
</style>
</head>
<body>
<h2>Background Image</h2>
Page | 27
WEB PRORAMMING
</body>
</html>
Page | 28
WEB PRORAMMING
Question 15. Explain how to attach a video in html page. Also explain
various attributes of its.
Answer:
The <video> tag is used to embed video content in a document, such as a movie clip or other
video streams.
The <video> tag contains one or more <source> tags with different video sources. The
browser will choose the first source it supports.
The text written between the <video> and </video> tags will only be displayed in browsers
that do not support the <video> element.
There are three supported video formats in HTML: MP4, WebM, and OGG.
Syntax:
<video controls>
</video>
Example:
<html>
<head>
</head>
<body>
<video controls>
Page | 29
WEB PRORAMMING
</video>
</body>
</html>
autoplay autoplay Specifies that the video will start playing as soon as it
is ready
loop loop Specifies that the video will start over again, every
time it is finished
muted muted Specifies that the audio output of the video should be
muted
preload auto Specifies if and how the author thinks the video
metadata should be loaded when the page loads
none
src URL Specifies the URL of the video file
width pixels Sets the width of the video player
Page | 30
WEB PRORAMMING
Question 16. Explain Autoplay, controls, height, width, muted, poster, src
attribute of video tag.
Answer:
Autoplay
Add muted after autoplay to let your video file start playing automatically (but muted).
Example:
<html>
<body>
</body>
</html>
Controls
The controls attribute is a boolean attribute.
When present, it specifies that video controls should be displayed.
Video controls should include:
Play
Pause
Page | 31
WEB PRORAMMING
Seeking
Volume
Fullscreen toggle
Captions/Subtitles (when available)
Track (when available)
Example:
<html>
<body>
</body>
</html>
The height and width attribute specifies the height and width of a video player, in pixels.
Always specify both the height and width attributes for videos. If these attributes are set, the
required space for the video is reserved when the page is loaded. However, without these
attributes, the browser does not know the size of the video, and cannot reserve the appropriate
space to it. The effect will be that the page layout will change during loading (while the video
loads).
Example:
<html>
Page | 32
WEB PRORAMMING
<body>
</body>
</html>
Muted
When present, it specifies that the audio output of the video should be muted.
Example:
<html>
<body>
</body>
Page | 33
WEB PRORAMMING
</html>
Poster
The poster attribute specifies an image to be shown while the video is downloading, or until
the user hits the play button. If this is not included, the first frame of the video will be used
instead.
Example:
<html>
<body>
</body>
</html>
Src
The src attribute specifies the location (URL) of the video file.
The example above uses an Ogg file, and will work in Chrome, Edge, Firefox and Opera.
To play the video in old Internet Explorer and Safari, we must use an MPEG4 file.
To make it work in all browsers - add several <source> elements inside the <video> element.
Each <source> elements can link to different video files. The browser will use the first
recognized format
Example:
<html>
<body>
Page | 34
WEB PRORAMMING
</body>
</html>
Page | 35
WEB PRORAMMING
Question 17. Explain how to attach an audio in html page. Also explain
various attribute of its.
Answer:
The HTML <audio> element is used to play an audio file on a web page.
The <audio> tag is used to embed sound content in a document, such as music or other audio
streams.
The <audio> tag contains one or more <source> tags with different audio sources. The
browser will choose the first source it supports.
The text between the <audio> and </audio> tags will only be displayed in browsers that do
not support the <audio> element.
There are three supported audio formats in HTML: MP3, WAV, and OGG.
The autoplay attribute is a boolean attribute. When present, the audio will automatically start
playing as soon as it can do so without stopping.
Add muted after autoplay to let your audio file start playing automatically (but muted).
Example:
<html>
<body>
Page | 36
WEB PRORAMMING
</body>
</html>
Controls
The controls attribute is a boolean attribute. When present, it specifies that audio controls
should be displayed.
Audio controls should include:
Play
Pause
Seeking
Volume
Example:
<html>
<body>
<audio controls>
<source src="alarm.ogg" type="audio/ogg">
<source src="alarm.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
Page | 37
WEB PRORAMMING
Loop
The loop attribute is a boolean attribute. When present, it specifies that the audio will start
over again, every time it is finished.
Example:
<html>
<body>
</body>
</html>
Muted
The muted attribute is a boolean attribute. When present, it specifies that the audio output
should be muted.
Example:
<html>
<body>
Page | 38
WEB PRORAMMING
</body>
</html>
Preload
The preload attribute specifies if and how the author thinks that the audio file should be
loaded when the page loads.
The preload attribute allows the author to provide a hint to the browser about what he/she
thinks will lead to the best user experience. This attribute may be ignored in some instances.
Example:
<html>
<body>
Page | 39
WEB PRORAMMING
Src
The src attribute specifies the location (URL) of the audio file.
The example above uses an Ogg file, and will work in Firefox, Opera, Chrome, and Edge.
However, to play the audio file in IE or Safari, we must use an MP3 file.
To make it work in all browsers - use <source> elements inside the <audio> element.
Each <source> element can link to different audio files. The browser will use the first
recognized format
Example:
<html>
<body>
Page | 40
WEB PRORAMMING
Answer:
The <table> tag defines an HTML table. An HTML table consists of one <table> element and
one or more <tr>, <th>, and <td> elements.
The <tr> element defines a table row, the <th> element defines a table header, and the <td>
element defines a table cell. An HTML table may also
include <caption>, <colgroup>, <thead>, <tfoot>, and <tbody> elements.
Example:
<html>
<head>
<title> Table</title>
</head>
<body>
<h2 align = "center">TABLE</h2>
Page | 41
WEB PRORAMMING
</body>
</html>
Align
It is used to set the position of the table within the browser window. Left is the default
position.
align=position – left, center, right
Height & width
These two attributes are used to specify the height and width of a table in terms of pixels or
percentage.
Height=number[%]
Width=number[%]
Cellspacing
It is used to set the space between cells in a table. The value should be in pixels.
Cellspacing =number
Cellpadding
It is used to set the space between the contents of a cell and its border. The value should be in
pixels.
Cellpadding =number
Page | 42
WEB PRORAMMING
Page | 43
WEB PRORAMMING
Question 19. Explain cell padding and cell spacing with examples
Answer:
In HTML, cell padding and cell spacing are used to control the spacing within and around
table cells, respectively. These properties are especially useful for improving the readability
and layout of tables.
Cell Padding
Cell padding is the space between the cell content and the cell border. It creates "padding"
within each cell, making the content less cramped. By default the padding is set to 0.
Example
<html>
<head>
<title> Table </title>
</head>
<body>
<h3>Table cell padding</h3>
</body>
</html>
Page | 44
WEB PRORAMMING
Cell Spacing
Cell spacing is the space between the cells themselves. It creates "gaps" between the borders
of adjacent cells. By default the space is set to 2 pixels.
Example
<html>
<head>
<title> Table </title>
</head>
<body>
<h3>Table cell spacing</h3>
Page | 45
WEB PRORAMMING
The HTML attribute rowspan determines how many rows a specific cell in a table should
cover. When a cell spans multiple rows, it occupies the space of those rows within the
table.
Example
<html>
<head>
<title> Rowspan </title>
</head>
<body>
<table border = "2" width ="300" height = "200">
<tr align = "center" valign = "middle">
<td rowspan = "2"> 1 </td>
<td> 2 </td>
</tr>
<tr align = "center" valign = "middle" >
<td> 3 </td>
</tr>
</table>
</body>
</html>
Page | 46
WEB PRORAMMING
In HTML, the colspan attribute specifies the number of columns a cell should span,
determining its horizontal position.
HTML Table with Colspan allows you to merge or combine adjacent table cells
horizontally, creating a single, wider cell that spans across multiple columns.
Example
<html>
<head>
<title> Irregular Table </title>
</head>
<body>
<table border = "2" width ="300" height = "200">
<tr align = "center" valign = "middle">
<td colspan = "3"> 1 </td>
</tr>
<tr>
<td> 2</td>
<td> 3 </td>
<td> 4 </td>
</tr>
</table>
</body>
</html>
Page | 47
WEB PRORAMMING
Question 21. Explain following tags: br, hr, b, I, u, pre, sub, sup
Answer:
Page | 48
WEB PRORAMMING
Page | 49
WEB PRORAMMING
Whitespace and
line breaks are preserved.
</pre>
</html>
</body>
<sub> (Subscript Text)
It displays text as a subscript, lowered slightly below the normal text line. Useful for
mathematical or scientific notations, such as chemical formulas.
Example:
<html>
<body>
H<sub>2</sub>O (Water)
</html>
</body>
<sup> (Superscript Text)
It displays text as a superscript, raised slightly above the normal text line. Commonly used
for exponents, footnotes, or ordinal indicators.
Example:
<html>
<body>
x<sup>2</sup> (x squared)
</body>
</html>
Page | 50
WEB PRORAMMING
The <marquee> tag in HTML creates a scrolling text or image effect within a webpage. It
allows content to move horizontally or vertically across the screen, providing a simple way
to add dynamic movement to elements. Although this tag is deprecated in HTML5, it is
still useful to understand its functionality for legacy projects.
Syntax
<marquee>
<!-- contents -->
</marquee>
Attributes of <marquee>
Page | 51
WEB PRORAMMING
Example
<html>
<head>
<title> Marquee</title>
</head>
<body>
<h3> Marquee tag</h3>
<marquee bgcolor ="yellow" hspace= "40px" > Hello World! </marquee>
</body>
</html>
Page | 52
WEB PRORAMMING
Question 23. What is HTML form tag? Explain its important in client
server architecture.
Answer:
The <form> tag in HTML is used to create an HTML form for user input, allowing users to
submit data to a server. It is essential for gathering user information, as it allows users to
enter data in input fields, checkboxes, radio buttons, dropdowns, and other interactive
elements. Once submitted, the form data is sent to a server for processing.
Syntax:
<form parameters> form elements </form>
The form elements are the individual input fields and controls within an HTML <form> that
allow users to enter data and interact with a web form. Each form element collects specific
types of user information, such as text, numbers, selections, dates, and file uploads. The form
elements include button, checkboxes, text fields, radio button, drop-down menus, text,
password etc.
The form paraments tell browser how to send the information to the server. The parameters
to form tell what to do with the user input.
Action=”url”
Specifies where to send the data when the Submit button is clicked.
Method=”get”
Form data is sent as a URL with ?form_data info appended to the end. It can be used only if
data is all ASCII and not more than 100 characters.
Method=”post”
Form data is sent in the body of the URL request. It cannot be bookmarked by most browsers.
Target=”target”
It tells where to open the page sent as a result of the request
Example
<html>
<head>
<title>HTML Form</title>
</head>
Page | 53
WEB PRORAMMING
<body>
<h2>HTML form</h2>
<form>
First name:
<input type = "text" >
</form>
</body>
</html>
Page | 54
WEB PRORAMMING
Page | 55
WEB PRORAMMING
Question 24. Explain Text fields, password field, submit button, reset
button, file upload and custom button with its attributes and example.
Answer:
Text Field
The HTML <input type=”text”> element creates a single-line text input field for users to
enter textual data. Commonly used in web forms for collecting names, emails, or messages,
it supports various attributes for validation, styling, and functionality, making it versatile
and essential.
Common Attributes:
name: Specifies the name of the input, used when submitting data.
placeholder: Text displayed inside the field as a hint.
maxlength: Limits the number of characters that can be entered.
required: Ensures the field must be filled before submission.
value: Sets a default value for the text field.
Example:
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<h2>HTML form</h2>
<form>
First name:
<input type = "text" name = "F name" value = "Enter your name">
</form>
</body>
</html>
Password Field
Page | 56
WEB PRORAMMING
HTML <input type=”password”> is used to specify the password field of the input tag.
Password should be served over the HTTPS pages because it includes the sensitive
information of the user.
Common Attributes:
name: Name of the input for form submission.
maxlength: Limits the maximum number of characters.
placeholder: Text hint for the field.
required: Makes the field mandatory.
Example:
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<h2>HTML form</h2>
<form>
User name:
<input type = "text" name = "user">
</br>
</br>
Password:
<input type = "password">
</form>
</body>
</html>
Submit Button
Page | 57
WEB PRORAMMING
The <input type="submit"> defines a submit button which submits all form values to a form-
handler. The form-handler is typically a server page with a script for processing the input
data. The form-handler is specified in the form's action attribute.
Common Attributes:
value: Sets the text displayed on the button if using <input>.
formaction: Specifies a URL for form submission (overrides form’s action attribute).
formenctype: Specifies how form data should be encoded before submission, commonly
used with file uploads.
Example:
<!DOCTYPE HTML>
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<h2>HTML form</h2>
<form action = "C:/Users/mohan_bjpjiz/OneDrive/Desktop/Priya/submitted%20form.html">
Name:
<input type = "text" name ="name"/>
</br>
</br>
Password:
<input type = "password"/ >
</br>
</br>
Page | 58
WEB PRORAMMING
Subject: <br/>
<input type= "checkbox"/>Maths <br/>
<input type= "checkbox"/>Science<br/>
<input type= "checkbox"/>English
<br/>
<br/>
</body>
</html>
Reset Button
The <input type="reset"> defines a reset button which resets all form values to its initial
values.
Tip: Avoid reset buttons in your forms! It is frustrating for users if they click them by
mistake.
Common Attributes:
value: Sets the text displayed on the button.
Example:
<html>
<head>
<title>HTML Form</title>
</head>
<body>
<h2>HTML form</h2>
<form action ="C:\Users\mohan_bjpjiz\OneDrive\Desktop\Priya\button tag 1.html">
Name:
Page | 59
WEB PRORAMMING
Subject: <br/>
<input type= "checkbox"/>Maths <br/>
<input type= "checkbox"/>Science<br/>
<input type= "checkbox"/>English
<br/>
<br/>
</body>
</html>
Page | 60
WEB PRORAMMING
Common Attributes:
name: Name of the file input for form submission.
accept: Specifies the types of files allowed (e.g., .jpg, .png, .pdf).
multiple: Allows selecting multiple files.
required: Makes the file input mandatory.
Example:
<html>
<body>
<form>
<label for="fileUpload">Upload your profile picture:</label>
<input type="file" id="fileUpload" value="ok button" >
</form>
</body>
</html>
Custom Button
The HTML <input type=”button”> element creates a clickable button that can be
customized with text or an image. It does not have any default behavior but can be used to
perform actions using JavaScript. It makes versatile for various interactive purposes in web
forms and applications.
Common Attributes:
type: Specifies the button type (button, submit, or reset).
onclick: Executes JavaScript code when the button is clicked.
name: Can be used to identify the button in form submissions.
Example:
html
<button type="button" onclick="alert('Button clicked!')">Click Me</button>
Page | 61
WEB PRORAMMING
Question 25. Explain radio button and check box with its attributes and
example
Answer:
Radio button
A radio button (<input type="radio">) allows users to select only one option from a group of
options. Radio buttons are commonly used for questions where only one is possible, like
selecting a gender or a payment method.
Common Attributes:
name: Identifies the group of radio buttons. Radio buttons with the same name are
considered part of the same group, allowing only one selection within that group.
value: Sets the value that will be sent to the server if this option is selected.
checked: Pre-selects the radio button if set (only one option in a group should have this
attribute).
required: Ensures that at least one option in the group is selected before form submission.
Example
<html>
<head>
<title>Radio button</title>
</head>
<body>
<form>
Do you agree this statement?
<br>
<input type="radio"
name="agree"
value="yes">Yes
<br>
<input type="radio"
name="agree"
value="no">No
Page | 62
WEB PRORAMMING
<br>
<input type="Submit">
</form>
</body>
</html>
Checkbox
A checkbox (<input type="checkbox">) allows users to select one or more options
independently. Checkboxes are often used for multi-choice selections, such as selecting
newsletter subscriptions or agreeing to terms.
Common Attributes:
name: Identifies the checkbox when submitted to the server. For multiple checkboxes in a
group, give each checkbox the same name (usually paired with square brackets [] to treat
them as an array).
value: Sets the value that will be sent to the server if the checkbox is selected.
checked: Pre-selects the checkbox if set (can be applied to multiple checkboxes).
required: Ensures that at least one checkbox in a group is selected before form submission.
Example
<html>
<head>
<title> Checkboxes</title>
</head>
<body>
<form>
Choose languages you know:
<br>
<input type="checkbox"
name="C"
Page | 63
WEB PRORAMMING
value="yes">C
<br>
<input type="checkbox"
name="C++"
value="yes">C++
<br>
<input type="checkbox"
name="Java"
value="yes">Java
<br>
<input type="checkbox"
name="Python"
value="yes">Python
<br>
<input type="Submit">
</form>
</body>
</html>
Page | 64
WEB PRORAMMING
Question 26. Explain the drop-down list and text area with its attributes
and example.
Answer:
DROP-DOWN LIST
A drop-down list allows users to select an option from a list of predefined choices. It's useful
for limiting input to specific values while saving space in the user interface.
Attributes:
Name: Identifies the form element for submission.
id: Unique identifier for the element, useful for styling and scripting.
size: Specifies the number of visible options (default is usually one).
disabled: Disables the list, preventing user interaction.
required: Ensures the user selects an option before form submission.
Example:
<!DOCTYPE HTML>
<html>
<head>
<title>Forms</title>
</head>
<body>
<form>
<h1>student admission form</h1>
<form name="f1">
Select your City:
<select multiple="multiple">
<option Value="0"selected>Select City</option>
<option Value="1">Rajkot</option>
<option value="2">Ahmedabad</option>
<option value="3">Surat</option>
<br/>
</select>
</body>
Page | 65
WEB PRORAMMING
</html>
Output:
TEXT AREA
A text area allows users to input multi-line text. It's ideal for longer text entries like
comments or descriptions.
Attributes:
name: Identifies the text area for form submission.
id: Unique identifier for the element.
rows: Defines the visible number of text lines.
cols: Specifies the visible width in characters.
placeholder: Provides a hint to the user about what to enter.
required: Ensures the text area is filled before submission.
Example:
<!DOCTYPE HTML>
<html>
<head>
<title>Forms</title>
</head>
<body>
<form>
<h1>student admission form</h1>
<form name="f1">
Address:<textarea rows="8" cols="30"/>
</textarea>
</br>
</body>
</html>
Page | 66
WEB PRORAMMING
Output:
Page | 67
WEB PRORAMMING
Question 27. Explain frame and frameset with its attributes and example.
Answer:
Frames and framesets were used in HTML to divide a browser window into multiple sections,
each capable of displaying a separate HTML document. However, they are now considered
outdated due to usability and accessibility issues, and modern web design practices favour
CSS and responsive design.
HTML frames are used to divide your browser window into multiple sections where each
section can load and separate HTML document independently.
A collection of frames in the browser window is known as a frameset.
ATTRIBUTES
Src This attribute is used to give the file name that should be loaded in the
frame. Its value can be any URL. For example,
src="/html/top_frame.htm" will load an HTML file available in html
directory.
Marginwidth This attribute allows you to specify the width of the space between the
left and right of the frame's borders and the frame's content. The value
is given in pixels. For example, marginwidth="10".
marginheight This attribute allows you to specify the height of the space between the
top and bottom of the frame's borders and its contents. The value is
given in pixels. For example, marginheight="10".
Noresize By default you can resize any frame by clicking and dragging on the
borders of a frame. The noresize attribute prevents a user from being
able to resize the frame. For example, noresize="noresize".
Page | 68
WEB PRORAMMING
Scrolling This attribute controls the appearance of the scrollbars that appear on
the frame. This takes values either "yes", "no" or "auto". For example
scrolling="no" means it should not have scroll bars.
Example:
<!DOCTYPE HTML>
<html>
<head>
<title>Frame tag</title>
<frameset cols="20%,*">
<frame name="top" src="file:///C:/Users/joons/OneDrive/Desktop/rhea/1.html"/>
<frameset rows="40%,*">
<frame name="bottom" src="file:///C:/Users/joons/OneDrive/Desktop/rhea/2.html"/>
<frame name="bottom" src="file:///C:/Users/joons/OneDrive/Desktop/rhea /3.html"/>
</frameset>
</head>
<body>
</body>
</html>
Page | 69
WEB PRORAMMING
Nested frames refer to frames that are placed within other frames. This allows for a more
complex layout where a frame itself can contain a frameset, enabling multiple layers of
frames.
Advantages:
Accessibility: Nested frames can complicate navigation and accessibility for users,
making it harder for screen readers and other assistive technologies.
Usability: Users may find it confusing if frames are nested too deeply.
Deprecation: As mentioned earlier, frames and framesets are deprecated in HTML5,
and modern web design prefers CSS for layout due to better flexibility and
accessibility.
Example:
html
<!DOCTYPE html>
<html>
<head>
<title>Nested Frames Example</title>
</head>
<frameset rows="50%,50%">
<frameset cols="50%,50%">
<frame src="frame1.html" name="nestedFrame1">
<frame src="frame2.html" name="nestedFrame2">
</frameset>
<frame src="frame3.html" name="outerFrame3">
</frameset>
</html>
Page | 70
WEB PRORAMMING
Question 29. Explain section, article, aside, header, footer, nav, dialog,
figure, date, time, week tags of html5.
Answer:
1. <section>
The <section> element represents a thematic grouping of content, typically with a heading. It
is used to organize content into distinct areas, making the document structure clearer.
Example:
<html>
<section>
<h2>Our Services</h2>
<p>We offer a variety of services including...</p>
</section>
2. <article>
The <article> element is used for self-contained content that can stand alone, such as a blog
post, news article, or forum post. It can be distributed independently.
Example:
html
<article>
<h2>New Features in HTML5</h2>
<p>HTML5 introduces many new features...</p>
</article>
3. <aside>
The <aside> element is for content that is related to the surrounding content but is not
essential to it. This is often used for sidebars, related links, or additional information.
Example:
html
<aside>
<h3>Related Articles</h3>
<p>Check out these other articles...</p>
</aside>
Page | 71
WEB PRORAMMING
4. <header>
The <header> element contains introductory content or navigational links. It typically
includes headings, logos, and navigation menus.
Example:
html
<header>
<h1>Website Title</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
</nav>
</header>
5. <footer>
The <footer> element is used for footer content at the bottom of a page or section. It may
include copyright information, links, and authorship details.
Example:
html
<footer>
<p>© 2024 Company Name. All rights reserved.</p>
</footer>
6. <nav>
The <nav> element is specifically for navigation links. It helps search engines and assistive
technologies identify navigation areas.
Example:
<html>
<nav>
<ul>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
Page | 72
WEB PRORAMMING
</ul>
</nav>
7. <dialog>
The <dialog> element creates a dialog box or modal that can be opened and closed
programmatically. It’s used for prompts, alerts, or other interactive content.
Example:
<dialog id="myDialog">
<p>This is a dialog message.</p>
<button onclick="document.getElementById('myDialog').close()">Close</button>
</dialog>
8. <figure>
The <figure> element is for encapsulating media content such as images, diagrams, or
illustrations, along with an optional <figcaption> for a caption.
Example:
<figure>
<img src="image.jpg" alt="A beautiful scene">
<figcaption>A caption describing the image.</figcaption>
</figure>
9. <time>
The <time> element is used to represent a specific period or date. It can include attributes to
provide machine-readable date and time.
Example:
<time datetime="2024-11-04">November 4, 2024</time>
10. <week>
The <week> element does not exist in HTML5. However, you might be thinking of <time> in
relation to specific dates or durations. If you're looking for something specific about weeks,
you could represent weeks using custom attributes or other relevant structures.
Example:
<time datetime= “2024 – W45“>Week 45 of 2024 <time>
Page | 73
WEB PRORAMMING
Question 30. Explain email, range, number tags with its attributes and
example.
Answer:
Email Tag:
The <input type="email"> defines a field for an e-mail address. The input value is
automatically validated to ensure it is a properly formatted e-mail address. To define an e-
mail field that allows multiple e-mail addresses, add the "multiple" attribute.
Tip: Always add the labels tag for best accessibility practices.
Example:
<form action="/action_page.php"> <label for="email">Enter your email:</label>
<input type="email" id="email" name="email">
<input type="submit">
</form>
Output:
Number Tag:
The <input type="number"> defines a field for entering a number
ATTRIBUTES:
max specifies the maximum value allowed
min specifies the minimum value allowed
step-specifies the legal number intervals
value-Specifies the default value
Example:
<form action="/action_page.php">
<label for-"quantity">Quantity (between 1 and 5):</label>
<input type="number" id="quantity" name="quantity" min="1" max="5">
<input type="submit">
</form>
Page | 74
WEB PRORAMMING
Output:
Page | 75
WEB PRORAMMING
Question 31. What is CSS? Explain its importance with advantages and
disadvantages.
Answer:
CSS or Cascading Style Sheets is a stylesheet language used for describing the presentation
of a document written in HTML or XML. CSS controls the layout, colours, fonts, and overall
visual appearance of web pages, allowing for separation of content and design.
IMPORTANCE OF CSS
1. Separation of Concerns: CSS separates content (HTML) from presentation, making both
easier to manage and maintain.
2. Consistency: CSS enables consistent styling across multiple web pages, enhancing user
experience.
3. Responsive Design: CSS allows for the creation of responsive layouts that adapt to
different screen sizes and devices.
4. Accessibility: By controlling layout and styling, CSS helps improve the accessibility of
web content for users with disabilities.
5. Performance: Well-structured CSS can lead to faster load times as styles can be cached
and reused.
ADVANTAGES OF CSS
CSS saves time You can write CSS once and then reuse same sheet in multiple
HTML pages. You can define a style for each HTML element and apply it to as many
Web pages as you want.
Pages load faster If you are using CSS, you do not need to write HTML tag attributes
every time. Just write one CSS rule of a tag and apply it to all the occurrences of that
tag. So less code means faster download times.
Easy maintenance to make a global change, simply change the style, and all elements
in all the web pages will be updated automatically.
Superior styles to HTML-CSS has a much wider array of attributes than HTML, so
you can give a far better look to your HTML page in comparison to HTML attributes.
Multiple Device Compatibility Style sheets allow content to be optimized for more
than one type of device. By using the same HTML document, different versions of a
website can be presented for handheld devices such as PDAs and cell phones or for
printing.
Global web standards Now HTML attributes are being deprecated and it is being
recommended to use CSS. So, it is a good idea to start using CSS in all the HTML
pages to make them compatible to future browsers.
Offline Browsing - CSS can store web applications locally with the help of an offline
catches. Using of this, we can view offline websites. The cache also ensures faster
loading and better overall performance of the website.
Page | 76
WEB PRORAMMING
Platform Independence -The Script offer consistent platform independence and can
support latest browsers as well.
DISADVANTAGES OF CSS
Learning Curve: For beginners, mastering CSS can be challenging due to its
complexities and various techniquestion
Browser Compatibility Issues: Different browsers may render CSS differently, leading
to inconsistencies that require workarounds.
Specificity Conflicts: Managing specificity can be tricky, leading to unintended style
applications if not handled carefully.
Performance Overheads: Excessive use of complex CSS rules can impact rendering
performance on older devices.
Page | 77
WEB PRORAMMING
A simple HTML element selector in CSS allows you to apply styles to all instances of
a specific HTML element on a webpage. It targets elements based solely on their tag name.
Example:
<html>
<head>
<style type=”text/CSS”>
h1{color:blue}
</style>
<body>
<h1>Hello Friends</h1>
<h1>How are You</h1>
</body>
</html>
Output:
Page | 78
WEB PRORAMMING
The id selector is used to specify a style for a single, unique element. The id selector uses the
id attribute of the html element and is defines with a “#” in CSS. Each element can only have
one ID and each page can only have one element with that specific ID.
Example:
<html>
<head>
<style type=”text/CSS”>
#para1{color:blue}
</style>
<body>
<h1 id=”para1”>Hello Friends</h1>
<h1>How are You</h1>
</body>
</html>
Output:
Page | 79
WEB PRORAMMING
The class selector in CSS is used to apply styles to multiple elements that share the same
class name. Unlike ID selectors, which are unique to a single element, class selectors can
target multiple elements, making them ideal for styling groups of elements consistently. The
class selector uses html attribute and is defined with a “.” In CSS.
Example:
<html>
<head>
<style type=”text/CSS”>
.c1{color:blue}
</style>
<body>
<h1 class=”c1”>Hello Friends</h1>
<h1>How are You</h1>
<h1 class=”c1”>How are You</h1>
</body>
</html>
Output:
Page | 80
WEB PRORAMMING
The term generic selector in CSS generally refers to selectors that are not specific to any
particular element type, class, or ID. Instead, they apply styles broadly to elements based on
their type or context. The most common examples of generic selectors are the universal
selector and the type selector. The universal selector is defined with a “*” in CSS.
Example:
<html>
<head>
<style type=”text/CSS”>
*{color:blue}
</style>
<body>
<h1>Hello Friends</h1>
<h1>How are You</h1>
<h2>Hello Friends</h2>
</body>
</html>
Output:
Page | 81
WEB PRORAMMING
Defined using the "id" attribute. Defined using the "class" attribute.
There can only be one element on a page a Multiple elements on a page can have the
Specific ID. same class.
Used to select a specific, unique element on Used to select multiple elements and
a page. apply styles to them.
Has higher specificity. Has lower specificity.
Slightly better in performance in querying May have a slight overhead when querying
single elements since id’s are unique. multiple elements, but still efficient for
common use.
Ideal for styling unique elements. Ideal for styling group of elements.
Page | 82
WEB PRORAMMING
Grouping selectors in CSS allows you to apply the same styles to multiple selectors without
repeating the CSS rules. This feature helps to keep your stylesheets concise and organized.
Example:
<html>
<head>
<style type=”text/CSS”>
h1, h2, p{color:blue}
</style>
<body>
<h1>Hello Friends</h1>
<p>How are You, I am fine</p>
<h2>Hello Friends</h2>
</body>
</html>
Output:
Page | 83
WEB PRORAMMING
Question 38. List out types of CSS and explain anyone with an example.
Answer:
CSS (Cascading Style Sheets) is a language used to style HTML documents, which are the
backbone of most web pages. While HTML provides the structure and content, CSS is
responsible for the look and feel—things like colors, fonts, layout, and spacing. By adding
CSS to an HTML document, you can make web pages visually appealing and user-friendly.
Types of CSS
There are three main ways to use CSS, each with its unique purpose and advantages:
Inline CSS: Adds styling directly to individual HTML elements. This is helpful when you
want to style a single element without affecting other parts of the page.
Internal CSS: Uses a <style> tag within the <head> section of an HTML document. Internal
CSS applies styles to the entire page but is limited to that specific HTML file.
External CSS: Saves CSS in a separate .css file, which is then linked to the HTML document.
This method is efficient when you want the same styles across multiple pages, as changes in
the external CSS file will update all linked pages.
Page | 84
WEB PRORAMMING
<Html>
<Head>
</Head>
<Body>
<P Style= “Background: Blue; Color: White;”> Good </P>
<P> Morning </P>
<H1 Style= “Background: Blue; Color: White;”> Everyone</P>
</Body>
</Html>
Page | 85
WEB PRORAMMING
Inline CSS is a way to style individual elements directly in the HTML by using the style
attribute. This method allows you to add specific styles to each element separately, affecting
only that one item without impacting others on the page. Inline CSS is quick to use and
doesn’t require a separate CSS file or <style> section in the HTML.
Example:
<P Style= “Background: Blue; Color: White;”> Inline CSS </P>
Page | 86
WEB PRORAMMING
Too many inline styles can make the HTML code look cluttered and harder to read, especially
when working on large or complex pages. When the code is messy, its harder to find and edit
specific elements.
Slower Loading for Large Pages:
If you use a lot of inline CSS across a page, it can increase the file size of the HTML, making
the page slower to load. This can become an issue for larger websites or pages with lots of
content.
Hard to Change Across the Site:
If you need to update a style across multiple elements, inline CSS requires you to go to each
element and change the style manually. In contrast, with an external CSS file, you can update
one line in the file, and the change will automatically apply to all linked elements.
Page | 87
WEB PRORAMMING
Internal CSS refers to CSS code that is embedded directly within the HTML file, specifically
within a <style> tag located in the <head> section. This approach allows styling to be applied
to elements on a single page.
When to Use Internal CSS
Internal CSS is typically best suited for smaller websites or single-page designs where:
The styles are specific to a single page.
Theres no need to reuse the styles on other pages.
Faster development and testing are prioritized over scalability.
This method of styling is less ideal for complex sites that require consistency and scalability
across multiple pages, where external CSS would be more efficient.
Example:
<HTML>
<HEAD>
P {COLOR; RED;}
</STYLE>
</HEAD>
<BODY>
</BODY>
</HTML>
Page | 88
WEB PRORAMMING
Page | 89
WEB PRORAMMING
External CSS is a styling approach where CSS rules are written in a separate file (with a .css
extension) and linked to the HTML file using a <link> tag within the <head> section. This
allows for centralized styling across multiple web pages by referencing the same stylesheet
file.
When to Use External CSS
External CSS is ideal for:
Medium to large websites where styles need to be reused across multiple pages.
Projects requiring easy and consistent updates, as changes to the CSS file will automatically
apply to all linked pages.
Better-organized code where separation of HTML and CSS makes the project more
maintainable and scalable.
External CSS is the preferred approach for most web development projects, particularly when
consistent styling and maintainability are key priorities.
EXAMPLE:
DEMO.HTML TEST.CSS
<HTML> PARA 1{TEXT-ALIGN: CENTER;}
<HEAD> P {COLOR: BLUE;}
<LINK REL= “STYLESHEET” TYPE= “TEXT/CSS”
HREF= “TEST.CSS”>
</HEAD>
OUTPUT
<BODY>
HELLO FRIENDS
<P> HELLO FRIENDS </P>
HOW ARE YOU?
<P ID= “PARA 1”> HOW ARE YOU? </P>
</BODY>
</HTML>
Page | 90
WEB PRORAMMING
Page | 91
WEB PRORAMMING
Question 42. Compare inline CSS v/s internal CSS v/s external CSS
Answer:
❖ Advantages
Type Advantages
Inline CSS -Allows quick, specific styling
changes<br> -No external file needed, so
styles load immediately
Internal CSS -All styles for a single page are in one
place<br>
- Higher specificity than external CSS<br>
- No dependency on external files for
styles
External CSS | - Maintains consistency across multiple
pages<br>
- Reduces HTML file size<br> - Enables
caching for faster load times<br>
- Separates structure (HTML) from design
(CSS)
❖ Disadvantages
Type Disadvantages
Inline CSS - Results in cluttered HTML code<br>
- Difficult to maintain and update<br>
- Hard to enforce consistency across pages
Internal CSS - Increases file size for each HTML
document<br>
- Not reusable across multiple pages<br> -
Mixing CSS and HTML reduces
separation of concerns
Page | 92
WEB PRORAMMING
CONCLUSION:
Inline CSS is best for quick changes and minor adjustments on individual elements
but is generally not recommended for large or complex projects.
Internal CSS works well for single-page sites and quick prototypes but lacks
reusability for multi-page projects.
External CSS is ideal for most professional websites, offering consistency, scalability,
and efficient management across multiple pages. Its considered the best practice for
larger projects due to its separation of concerns and centralized management.
Page | 93
WEB PRORAMMING
• FONT-FAMILY: This property defines the typeface of the text. Multiple font
names can be specified in a comma-separated list as a "fallback" system,
where the browser will choose the next available font if the first one isnt
available.
Example:
p {font-family: "Times New Roman", Times, serif;}
The `p` element will use "Times New Roman" if available, otherwise `Times`, and as a final
fallback, any serif font.
h2 {font-family: Arial, Helvetica, sans-serif;}
For `h2`, Arial is preferred, falling back to Helvetica, and finally, a generic sans-serif font.
Page | 94
WEB PRORAMMING
p {font-style: oblique;}
Italic and oblique styles make the text slanted. `italic` is typically a custom, designed style,
whereas `oblique` is a slanted version of the normal font.
Example:
p {font-variant: small-caps;}
In this example, all lowercase letters in the paragraph text appear in uppercase format but at a
smaller size than usual capital letters.
CSS also offers the shorthand `font` property, which combines these properties into a
single line:
p {font: italic small-caps bold 16px/1.5 "Arial", sans-serif;}
This shorthand sets the font style to italic, the variant to small-caps, the weight to
bold, the size to 16px, the line-height to 1.5, and the font family to Arial with a
fallback to sans-serif.
Page | 95
WEB PRORAMMING
Body {
Background-image: URL(‘pathtoimage.jpg’);
Background-repeat: repeat;
Background-repeat: repeat-x;
Background-repeat: repeat-y;
Background-repeat: no-repeat;
Background image positioning (background-position): Sets the starting position for the
background image.
Body {
Background-image: URL(‘pathtoimage.jpg’);
Background-repeat: no-repeat;
Page | 96
WEB PRORAMMING
Fixed background image (background-size): Defines the size of the background image, like
cover or specific dimensions.
Body {
Background-image: URL(‘pathtoimage.jpg’);
Background-repeat: no-repeat;
Background-attachment: fixed;
• BACKGROUND-COLOR:
Sets a solid color as the background for an element.
The color can be specified using color names and HEX codes.
Syntax: background-color: color;
Often used as a fallback color when an image is also set with background-image.
Body {
Background-color: red;
Background-color: #FF0000;
Page | 97
WEB PRORAMMING
Page | 98
WEB PRORAMMING
Page | 99
WEB PRORAMMING
Question 46. Explain the Box model in CSS with a suitable example
Answer:
The CSS Box Model is fundamental to controlling the layout and spacing of HTML elements
on a webpage. It helps you understand and control the size, padding, borders, and margins of
elements, ensuring that they appear as expected on the screen.
Breakdown of the CSS Box Model
Every element in HTML can be thought of as a rectangular "box," and this box consists of
four key parts:
Content: This is the innermost part where your actual content (text, images, etc.) lives. Its the
width and height of this area that you control with the width and height properties in CSS.
Padding: The padding is the space between the content and the border. It pushes the border
away from the content, creating inner spacing. You can set padding on each side individually
(e.g., padding-top, padding-right, padding-bottom, padding-left) or use padding to set the
same value on all sides.
Border: The border wraps around the padding and the content. Its like a frame for your
content area, which can be customized in terms of thickness, style (solid, dashed, etc.), and
color. You can set individual borders for each side as well.
Margin: The outermost layer of the box model, the margin creates space between the
elements border and the next element. Like padding, you can set individual margins for each
side, or use margin to apply the same value to all sides. Margins don’t have any color and are
fully transparent.
Example:
H1{width: 200px; padding: 20px; border: 5px solid black; margin: 10px;}
In this example, the total width of the element is the content width (200px) plus padding
(20px 2), border (5px 2), and margin (10px 2).
Page | 100
WEB PRORAMMING
In CSS, the position property determines how an element is placed in the document and
interacts with other elements. Here’s a breakdown of the main positioning types in CSS:
relative, absolute, fixed, and sticky.
RELATIVE POSITIONING:
Keyword: position: relative;
Behavior: Elements are positioned relative to their original position in the document flow.
Adding top, right, bottom, or left properties will move the element without affecting
surrounding elements positions.
Use case: Commonly used to make small adjustments or as a reference for absolute
positioned child elements.
Example:
H1 {position: relative;
top: 10px;
left: 20px;}
ABSOLUTE POSITIONING
Keyword: position: absolute;
Behavior: The element is removed from the document flow and positioned relative to its
closest positioned (non-static) ancestor. If no such ancestor is found, it positions itself relative
to the document body.
Use case: Useful for dropdowns, tooltips, or any element that should be positioned
independently of other elements.
Example:
H1{position: absolute;
top: 50px;
left: 100px;}
FIXED POSITIONING
Keyword: position: fixed;
Behavior: The element is removed from the document flow and positioned relative to the
viewport (the browser window). It remains fixed even when scrolling.
Use case: Useful for headers, footers, or side navigation bars that should stay visible while
scrolling.
Page | 101
WEB PRORAMMING
Example:
H1{position: fixed;
top: 0;
right: 0;
width: 100px;}
A fixed header or footer that stays visible at the top or bottom of the page, regardless of scroll
position.
STICKY POSITIONING
Keyword: position: sticky;
Behavior: A hybrid between relative and fixed positioning. An element with position: sticky
behaves like a relative element until it scrolls to a certain position, at which point it “sticks”
in place as if fixed. You need to specify at least one of top, right, bottom, or left for it to work.
Use case: Useful for headers or sections that should stick in place only when scrolled to a
certain point.
H1 {position: sticky;
top: 20px;}
Page | 102
WEB PRORAMMING
Question 48. Explain the purpose of JavaScript with its pros and cons
Answer:
Page | 103
WEB PRORAMMING
CLIENT-SIDE SCRIPTING:
Web browsers execute client-side scripting. It is used when browsers have all code. Source
code is used to transfer from webserver to user’s computer over the internet and run directly
on browsers. It is also used for validations and functionality for user events.
It allows for more interactivity. It usually performs several actions without going to the user.
It cannot be basically used to connect to databases on a web server. These scripts cannot
access the file system that resides in the web browser. Pages are altered on basis of the user’s
choice. It can also be used to create “cookies” that store data on the user’s computer.
SERVER-SIDE SCRIPTING:
Web servers are used to execute server-side scripting. They are basically used to create
dynamic pages. It can also access the file system residing at the webserver. A server-side
environment that runs on a scripting language is a web server.
Scripts can be written in any of a number of server-side scripting languages available. It is
used to retrieve and generate content for dynamic pages. It is used to require to download
plugins. In this load times are generally faster than client-side scripting. When you need to
store and retrieve information a database will be used to contain data. It can use huge
resources of the server. It reduces client-side computation overhead. The server sends pages
to the request of the user/client.
Difference between client-side scripting and server-side scripting:
Page | 104
WEB PRORAMMING
It does not provide security for data. It provides more security for data.
HTML, CSS, and JavaScript are used. PHP, Python, Java, Ruby are used.
No need of interaction with the server. It is all about interacting with the servers.
Page | 105
WEB PRORAMMING
Like many other programming languages, JavaScript has variables. Variables, considered as
named containers, can be declared in 4 different ways.
Automatically
Using var
Using const
Using let
1. Automatically
JavaScript allows the automatic or implicit declaration of variables by assigning a value to a
name without using var, let, or const. However, this is considered a bad practice since it
creates global variables and can lead to unpredictable code behaviour.
2. Using var
The var keyword was the standard way to declare variables. It was used in all JavaScript code
from 1995 to 2015.Variables declared using the var keyword have their scope limited to the
function within which they are defined, or they are scoped globally if they are declared
outside any function. Now the var keyword is only used in code written for or to support
older browsers
Page | 106
WEB PRORAMMING
3. using let
Introduced in ES6 (ECMAScript 2015), let allows you to declare block-scoped variables,
significantly improving code readability and reducing errors related to variable scope. Let is
used when you need a variable that can change over time or when working in an environment
that supports ES6 features.
4 using const
const is utilized for defining variables with values intended to remain constant and
unchangeable. Similar to let, const also adheres to block-scoping rules. It is used when you
have a variable whose value should not change once assigned. This helps to prevent bugs and
clarifies your intent to anyone reading your code. Use const by default for variables that do
not need to be reassigned.
Page | 107
WEB PRORAMMING
Page | 108
WEB PRORAMMING
Page | 109
WEB PRORAMMING
All JavaScript variables must be identified with unique names These unique names are called
identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum,
total Volume). An identifier in JavaScript is a name used to identify variables, functions,
objects, classes, and other entities.
The general rules for constructing names for variables (unique identifiers) are:
Page | 110
WEB PRORAMMING
In JavaScript, parseInt and parseFloat are built-in functions used to convert strings into
numbers. They are particularly useful when dealing with user input or when extracting
numerical values from strings.
1. parseInt
The parseInt function converts a string to an integer. It takes two arguments: the string to be
converted and an optional radix (base) that specifies the number system to use.
Syntax:
parseInt(string, radix);
Example:
Important Points:
If the string cannot be converted into an integer, parseInt returns NaN (Not-a-
Number).
Leading whitespace is ignored, but trailing characters (non-numeric) will cause
parsing to stop.
If the radix is not provided, JavaScript assumes base 10 unless the string starts with
“0x” (hexadecimal) or “0” (octal, in non-strict mode).
Eg:
Page | 111
WEB PRORAMMING
2. parseFloat
Page | 112
WEB PRORAMMING
Eg:
Page | 113
WEB PRORAMMING
1. Addition (+)
The addition operator is used to add two numbers. If one of the operands is a string, it will
perform string concatenation instead.
Example:
let sum = 5 + 3; // Result: 8
let concat = "Hello, " + "World!"; // Result: "Hello, World!"
2. Subtraction (-)
The subtraction operator is used to subtract one number from another.
Example:
let a = 10 - 4; // Result: 6
3. Multiplication (*)
The multiplication operator is used to multiply two numbers.
Example:
let product = 7 * 6; // Result: 42
4. Division (/)
The division operator is used to divide one number by another. If the denominator is zero, it
returns Infinity or -Infinity, depending on the sign of the numerator.
Example:
let a = 20 / 5; // Result: 4
let a = 5 / 0; // Result: Infinity
Page | 114
WEB PRORAMMING
5. Modulus (%)
The modulus operator returns the remainder of a division operation.
Example:
let remainder = 10 % 3; // Result: 1 (10 divided by 3 is 3 remainder 1)
6. Increment (++)
The increment operator increases the value of a variable by 1. It can be used in two ways:
Example:
let a = 5;
let b = ++a; // Prefix increment: a is incremented first, then assigned to b
// Now, a = 6 and b = 6
let c = 5;
let d = c++; // Postfix increment: d is assigned the original value of c, then c is incremented
// Now, c = 6 and d = 5
7. Decrement (--)
The decrement operator decreases the value of a variable by 1. It can also be used in prefix
and postfix forms.
Eg:
let e = 5;
let f = --e; // Prefix decrement: e becomes 4, f is also 4
let g = 5;
let h = g--; // Postfix decrement: h is assigned 5 (original value of g), then g becomes 4
Now, the values are:
e = 4, f = 4, g = 4, h = 5
Page | 115
WEB PRORAMMING
Comparison operators in JavaScript are used to compare two values or expressions and return
a Boolean value (true or false). These operators are fundamental in making decisions and
controlling the flow of a program using conditional statements.
1. Equal to (==)
The equality operator (==) checks if two values are equal, performing type coercion if
necessary. This means that if the values are of different types, JavaScript will attempt to
convert them to the same type before making the comparison.
Example:
Let a =10
Let b= 20
document.write("(a == b) => ");
result = (a == b);
document.write(result); // Output : (a == b) => false
Example:
Let a =10
Let b= 20
document.write("(a!= b) => ");
result = (a != b);
document.write(result); // Output : (a != b) => true
Page | 116
WEB PRORAMMING
Let a =10
Let b= 20
document.write("(a > b) => ");
result = (a > b);
document.write(result); // Output : (a > b) => false
The greater than or equal to operator checks if the value on the left is greater than or equal to
the value on the right.
Example:
Let a =10
Let b= 20
document.write("(a >= b) => ");
result = (a >= b);
document.write(result); // Output : (a >= b) => false
Page | 117
WEB PRORAMMING
Let a =10
Let b= 20
document.write("(a <= b) => ");
result = (a <= b);
document.write(result); // Output : (a <= b) => true
Page | 118
WEB PRORAMMING
Logical operators in JavaScript are used to combine multiple conditions and return a Boolean
result (true or false). They are essential for controlling the flow of execution in conditional
statements.
1. Logical AND (&&)
The logical AND operator returns true if both operands are true. If either operand is false, it
returns false.
Example:
let a = 5;
let b = 10;
document.write(a > 0 && b > 5); // Output: true (both conditions are true)
document.write(a > 0 && b < 5); // Output: false (second condition is false)
2. Logical OR (||)
The logical OR operator returns true if at least one of the operands is true. It returns false
only if both operands are false.
Example:
let x = 5;
let y = 10;
document.write(x > 0 || y > 15); // Output: true (first condition is true)
document.write(x < 0 || y < 5); // Output: false (both conditions are false)
Page | 119
WEB PRORAMMING
Example:
let isTrue = true;
document.write(!isTrue); // Output: false (negates the value)
document.write(!(x > 10)); // Output: true (x is not greater than 10)
Page | 120
WEB PRORAMMING
Assignment operators in JavaScript are used to assign values to variables. The most basic
assignment operator is the equal sign (=), but there are also several compound assignment
operators that perform an operation and assign the result in one step.
Example:
let x = 10; // Assigns 10 to x
document.write(x); // Output: 10
Example:
let z = 10;
z -= 4; // Equivalent to z = z - 4
document.write(z); // Output: 6
Page | 121
WEB PRORAMMING
Page | 122
WEB PRORAMMING
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
Syntax:
If Condition is true? Then value X : Otherwise value Y
Example
Try the following code to understand how the Conditional Operator works in
JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
let a = 10;
let b = 20;
const linebreak = "<br />";
//-->
Page | 123
WEB PRORAMMING
</script>
</body>
</html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Page | 124
WEB PRORAMMING
Conditional statements in JavaScript are used to control the flow of a program based on
certain conditions. These statements allow the execution of different code blocks depending
on whether a specified condition evaluates to true or false, providing a fundamental
mechanism for decision-making in algorithms.The most common conditional statements are
if, if...else,if….else..if, and switch.
1. if Statement
The if statement evaluates a condition and executes a block of code if the condition is true.
The syntax for a basic if statement is as follows:
if (expression){
Statement(s) to be executed if expression is true
}
Example:
let mark = 50;
if (mark > 25) {
document.write("student has passed."); // This will execute
}
2. if...else Statement
The if...else statement allows you to execute one block of code if the condition is true and
another block if the condition is false.
Syntax;
if (expression){
Statement(s) to be executed if expression is true
}else{
Statement(s) to be executed if expression is false
}
Page | 125
WEB PRORAMMING
Example:
let age = 18;
if (age < 18) {
document.write("You are a minor.");
} else {
document.write("You are an adult."); }
3. if...else if...else Statement
Page | 126
WEB PRORAMMING
4. switch Statement
The switch statement is a control structure that executes one block of code based on the value
of a variable or expression. It is often used as an alternative to multiple if...else statements
when comparing the same variable against different values.The objective of a 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)
}
Example:
let fruit = "apple";
switch (fruit) {
case "banana":
document.write("It's a banana.");
break;
case "apple":
document.write("It's an apple."); // This will execute
break;
Page | 127
WEB PRORAMMING
case "orange":
document.write("It's an orange.");
break;
default:
document.write("Unknown fruit.");
}
Page | 128
WEB PRORAMMING
Looping statements in JavaScript allow you to execute a block of code repeatedly based on a
specified condition. The most common looping statements
While loop
For loop
do...while loop
while Loop
The while loop continues executing as long as the specified condition is true. It is suitable for
situations where the number of iterations is not known in advance.
Syntax:
while (condition) {
// Code to be executed
}
Example:
let n = 1;
let i = 1;
while (n <= 5) {
document.write("sno " + i + "<br>");
i++;
n++;
}
;
Output:
sno 1
sno 2
sno 3
sno 4
sno 5
Page | 129
WEB PRORAMMING
do...while Loop
The do...while loop is similar to the while loop but guarantees that the block of code is
executed at least once, even if the condition is false initially.
Syntax:
do {
// Code to be executed
} while (condition);
Example:
let k = 0;
do {
document.write("Iteration " + k);
k++; // Increment k
} while (k < 5);
A `do...while` loop is particularly helpful in input validation scenarios, where user input is
requested until it meets a specific condition. Since the code is guaranteed to run once, we can
prompt the user at least once before re-checking the condition.
Page | 130
WEB PRORAMMING
The `for` loop is a control structure used in JavaScript to execute a block of code multiple
times, typically when the number of iterations is known. It is compact and allows
initialization, condition-checking, and increment/decrement in a single line, making it ideal
for executing a block of code for a set number of times.
Example:
javascript
for (let i = 0; i < 5; i++) {
console.log(i); // Prints 0 to 4
}
In this example, `i` is initialized to 0. The condition checks if `i` is less than 5, and if so, the
code block inside the loop executes. After each execution, `i` is incremented by 1 (`i++`).
The loop stops once `i` is equal to 5, as the condition `i < 5` is no longer satisfied.
The `for` loop is often used for tasks like iterating over arrays, generating sequences, or
running tasks a specific number of times. It’s structured and concise, making it a versatile
loop option for situations requiring exact control over the number of iterations.
Page | 131
WEB PRORAMMING
The `for...in` loop in JavaScript is specifically designed to iterate over the properties of an
object. This loop goes through each enumerable property of an object, allowing access to
both the property names (keys) and their values.
This type of loop is beneficial when you need to traverse all properties of an object without
knowing its structure in advance. It’s most often used with objects, but it can also be used
with arrays, though the `for...of` loop or traditional `for` loop is usually more appropriate for
arrays.
Example:
javascript
let person = {name: "John", age: 30};
for (let key in person) {
console.log(key + ": " + person[key]); // Outputs "name: John" and "age: 30"
}
```
In this example, the `for...in` loop iterates over the properties of the `person` object. On each
iteration, the variable `key` holds the current property name, which is then used to access the
corresponding value (`person[key]`). The loop outputs both the key and the value.
While `for...in` is powerful for objects, it should be used carefully with arrays since it iterates
over all enumerable properties, which might include unexpected inherited properties. For
arrays, a regular `for` loop or the `for...of` loop (introduced in ES6) is generally preferable.
Page | 132
WEB PRORAMMING
64. What is a dialog box? Explain various types of dialog boxes with
examples in JavaScript.
Answer:
In JavaScript, a dialog box is a pop-up window that interacts with the user. Dialog boxes are
used to either display information, request confirmation, or obtain input from the user. The
most common types of dialog boxes are `alert`, `confirm`, and `prompt`.
1. Alert Box:
An alert box displays a message and an "OK" button. This type of dialog is used to provide
information to the user.
Example:
javascript
alert("This is an alert box!");
In this example, a message box displays "This is an alert box!" with an OK button. The user
must click OK to proceed.
2. Confirm Box:
A confirm box prompts the user to confirm or cancel an action, typically with "OK" and
"Cancel" buttons. It returns `true` if the user clicks OK, and `false` if Cancel.
Example:
```javascript
let result = confirm("Are you sure?");
Here, a message asks "Are you sure?". The `confirm` dialog stores the user's response
(`true` for OK, `false` for Cancel) in the variable `result`.
3. Prompt Box:
Page | 133
WEB PRORAMMING
A prompt box requests input from the user. It shows a text field for user input, along with
OK and Cancel buttons. The prompt returns the user input as a string if OK is clicked or
`null` if Cancel is clicked.
Example:
javascript
let name = prompt("Please enter your name:");
In this example, a prompt asks the user to enter their name. The entered value is stored in
the `name` variable.
Page | 134
WEB PRORAMMING
User-defined functions in JavaScript are blocks of reusable code created by the developer to
perform specific tasks. They help break down complex tasks into smaller, manageable parts
and allow code reuse, making the codebase more modular and maintainable.
A function is defined using the `function` keyword, followed by a unique name, a list of
parameters (optional), and a code block. Parameters allow input values to be passed to the
function, and the `return` statement can be used to return a value after execution.
Example:
```javascript
function add(a, b) {
return a + b;
}
let sum = add(5, 3); // sum is 8
In this example, the function `add` takes two parameters, `a` and `b`, and returns their sum.
The function is invoked with arguments `5` and `3`, and the result (`8`) is stored in the
variable `sum`.
Functions enable developers to avoid code duplication and make updates in a single place if
the functionality needs to change. JavaScript also supports function expressions and arrow
functions (introduced in ES6) as additional ways to define functions.
Page | 135
WEB PRORAMMING
Page | 136
WEB PRORAMMING
Page | 137
WEB PRORAMMING
JavaScript provides several built-in date functions through the Date object:
1. new Date(): Creates a new date object with the current date and time.
javascript
let now = new Date();
console.log(now);
Page | 138
WEB PRORAMMING
2. pop(): Removes the last element from an array and returns it.
javascript
let last = arr.pop(); // last is 4, arr becomes [1, 2, 3]
3. shift(): Removes the first element from an array and returns it.
javascript
let first = arr.shift(); // first is 1, arr becomes [2, 3]
5. map(callback): Creates a new array with the results of calling a function on every element.
javascript
let doubled = arr.map(x => x 2); // [0, 4, 6]
Page | 139
WEB PRORAMMING
An event is an action or occurrence that can be detected by the browser, such as user
interactions with the page.
Types of Events:
1. onclick: Triggered when an element is clicked.
javascript
button.onclick = function() {
alert("Button clicked!");
};
Page | 140
WEB PRORAMMING
input.onchange = function() {
console.log("Value changed to: " + this.value);
};
Page | 141
WEB PRORAMMING
User-defined functions in PHP allow you to encapsulate code for reuse. Functions can accept
parameters and return values.
Example:
php
function add($a, $b) {
return $a + $b;
}
$sum = add(5, 3
); // $sum is 8
Page | 142
WEB PRORAMMING
Page | 143
WEB PRORAMMING
Page | 144
WEB PRORAMMING
The date() function in PHP is used to format a local date and time. It takes a format string as an
argument and returns a string formatted according to the specified format. This function is
particularly useful for displaying dates in different formats, such as day, month, year, and time.
The date() function returns a formatted string representing a date. You can exercise an enormous
amount of control over the format that date() returns with a string argument that you must pass to
it.
Syntax:
$format (required): Specifies the format of the outputted date string. It is a string that
includes predefined format characters, each representing parts of the date or time.
$timestamp (optional): An integer Unix timestamp. If omitted, the current time is used.
The following table lists the codes that a format string can contain
I Minutes ( 0 - 59 ) 23
Page | 145
WEB PRORAMMING
S Seconds of hour 20
Example
<?php
Page | 146
WEB PRORAMMING
An array is a data structure that stores one or more similar type of values in a single value. For
example, if you want to store 100 numbers, then instead of defining 100 variables, it is easy to define
an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c which is called
array index.
• Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion
• Associative array - An array with strings as index. This stores element values in association with key
values rather than in a strict linear index order.
• Multidimensional array - An array containing one or more arrays and values are accessed using
multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default, the array index starts from zero.
Example
The following example demonstrates how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function reference.
<html>
<body>
<?php
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
Page | 147
WEB PRORAMMING
$numbers[3] = "four";
$numbers[4] = "five";
?>
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you can
establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best
choice. Instead, we could use the employees names as the keys in our associative array, and the
value would be their respective salary.
Page | 148
WEB PRORAMMING
NOTE: Don't keep associative array inside double quote while printing, otherwise it would not return
any value.
Example
<html>
<body>
<?php
$salaries = array(
);
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
?>
</body>
</html>
Page | 149
WEB PRORAMMING
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each element in
the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using
multiple index.
Example
In this example, we create a two dimensional array to store marks of three students in three
subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"chemistry" => 39
),
"chemistry" => 29
),
Page | 150
WEB PRORAMMING
"chemistry" => 39
);
?>
</body>
</html>
Page | 151
WEB PRORAMMING
PHP offers several looping structures to execute a block of code repeatedly as long as a specified
condition is true. These structures are commonly used to iterate over arrays, perform repetitive
tasks, and control the flow of the code.
Loops in PHP are used to execute the same block of code a specified number of times. PHP supports
following four loop types.
• while - loops through a block of code if and as long as a specified condition is true.
• do...while - loops through a block of code once, and then repeats the loop as long as a special
condition is true.
Syntax
code to be executed;
The initializer is used to set the start value for the counter of the number of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i
Page | 152
WEB PRORAMMING
Example
The following example makes five iterations and changes the assigned value of two variables on each
pass of the loop:
<html>
<body>
<?php
$a = 0;
$b = 0;
$a += 10;
$b += 5;
?>
</body>
</html>
Syntax
while (condition)
code to be executed;
Page | 153
WEB PRORAMMING
Example
This example decrements a variable value on each iteration of the loop and the counter increments
until it reaches 10 when the evaluation becomes false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;
$num--;
$i++;
?>
</body>
</html>
Syntax
do
Page | 154
WEB PRORAMMING
code to be executed;
}while (condition);
Example
The following example will increment the value of i at least once, and it will continue incrementing
the variable i as long as it has a value of less than 10:
<html>
<body>
<?php
$i = 0;
$num = 0;
do
$i++;
}while( $i < 10 );
?>
</body>
</html>
Loop stopped at i = 10
Syntax
code to be executed;
Page | 155
WEB PRORAMMING
Example
Try out the following example to list out the values of an array.
<html>
<body>
<?php
?>
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
The break statement is situated inside the statement block. If gives you full control and whenever
you want to exit from the loop you can come out. After coming out of a loop immediate statement to
the loop will be executed.
Page | 156
WEB PRORAMMING
Example
In the following example, the condition test becomes true when the counter value reaches 3 and
loop terminates.
<html>
<body>
<?php
$i = 0;
$i++;
if( $i == 3 )break;
Page | 157
WEB PRORAMMING
?>
</body>
</html>
Loop stopped at i = 3
Just like the break statement the continue statement is situated inside the statement block
containing the code that the loop executes, preceded by a conditional test. For the pass
encountering continue statement, rest of the loop code is skipped and next pass starts.
Example
In the following example, the loop prints the value of array, but when the condition becomes true, it
just skips the code and next value is printed.
<html>
<body>
<?php
Page | 158
WEB PRORAMMING
?>
</body>
</html>
Value is 1
Value is 2
Value is 4
Value is 5
Page | 159
WEB PRORAMMING
The if, elseif ...else and switch statements are used to take decision based on the different condition.
You can use conditional statements in your code to make your decisions.
• if...else statement - use this statement if you want to execute a set of code when a condition is true
and another if the condition is not true
• elseif statement - is used with the if...else statement to execute a set of code if one of several
condition are true
• switch statement - is used if you want to select one of many blocks of code to be executed, use the
Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
if (condition)
else
Example
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it
will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
Page | 160
WEB PRORAMMING
else
?>
</body>
</html>
Syntax
if (condition)
elseif (condition)
else
Example
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a
nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
elseif ($d=="Sun")
Page | 161
WEB PRORAMMING
else
?>
</body>
</html>
Syntax
switch (expression)
case label1:
break;
case label2:
break;
default:
code to be executed
if expression is different
Example
PHP 43 The switch statement works in an unusual way. First it evaluates the given expression, then
seeks a label to match the resulting value. If a matching value is found, then the code associated with
the matching label will be executed. If none of the labels match, then the statement will execute any
specified default code.
Page | 162
WEB PRORAMMING
<html>
<body>
<?php
$d=date("D");
switch ($d)
case "Mon":
break;
case "Tue":
break;
case "Wed":
break;
case "Thu":
break;
case "Fri":
break;
case "Sat":
break;
case "Sun":
break;
default:
Page | 163
WEB PRORAMMING
?>
</body>
</html>
Today is Friday
Page | 164
WEB PRORAMMING
• Arithmetic Operators
• Comparison Operators
• Assignment Operators
Arithmetic Operators
The following arithmetic operators are supported by PHP language:
Example
Try the following example to understand all the arithmetic operators. Copy and paste following PHP
program in test.php file and keep it in your PHP Server's document root and browse it using any
browser.
<html>
<head><title>Arithmetical Operators</title><head>
Page | 165
WEB PRORAMMING
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b;
$c = $a - $b;
$c = $a * $b;
$c = $a / $b;
$c = $a % $b;
$c = $a++;
$c = $a--;
?>
</body>
</html>
Page | 166
WEB PRORAMMING
Comparison Operators
There are following comparison operators supported by PHP language.
Example
Try the following example to understand all the comparison operators. Copy and paste the following
PHP program in test.php file and keep it in your PHP Server's document root and browse it using any
browser
<html>
<head><title>Comparison Operators</title><head>
<body>
<?php
$a = 42;
$b = 20;
if( $a == $b ){
}else{
Page | 167
WEB PRORAMMING
if( $a > $b ){
}else{
if( $a < $b ){
}else{
if( $a != $b ){
}else{
if( $a >= $b ){
}else{
if( $a <= $b ){
}else{
?>
</body>
</html>
Page | 168
WEB PRORAMMING
Logical Operators
The following logical operators are supported by PHP language.
Page | 169
WEB PRORAMMING
Example
Try the following example to understand all the logical operators. Copy and paste the following PHP
program in test.php file and keep it in your PHP Server's document root and browse it using any
browser.
<html>
<head><title>Logical Operators</title><head>
<body>
<?php
$a = 42;
$b = 0;
if( $a && $b ){
}else{
if( $a and $b ){
}else{
if( $a || $b ){
}else{
if( $a or $b ){
}else{
$a = 10;
Page | 170
WEB PRORAMMING
$b = 20;
if( $a ){
}else{
if( $b ){
}else{
if( !$a ){
}else{
if( !$b ){
}else{
?>
</body>
</html>
TEST5 : a is true
Page | 171
WEB PRORAMMING
TEST6 : b is true
TEST7 : a is false
TEST8 : b is false
Assignment Operators
PHP supports the following assignment operators:
Example
Try the following example to understand all the assignment operators. Copy and paste the following
PHP program in test.php file and keep it in your PHP Server's document root and browse it using any
browser.
<html>
<head><title>Assignment Operators</title><head>
<body>
<?php
$a = 42;
Page | 172
WEB PRORAMMING
$b = 20;
?>
</body>
</html>
Conditional Operator
There is one more operator called the conditional operator. It first evaluates an expression for a true
or false value and then executes one of the two given statements depending upon the result of the
evaluation.
Page | 173
WEB PRORAMMING
Try the following example to understand the conditional operator. Copy and paste the following PHP
program in test.php file and keep it in your PHP Server's document root and browse it using any
browser.
<html>
<head><title>Arithmetical Operators</title><head>
<body>
<?php
$a = 10;
$b = 20;
?>
</body>
</html>
Page | 174
WEB PRORAMMING
An array is a data structure that stores one or more similar type of values in a single value. For
example, if you want to store 100 numbers, then instead of defining 100 variables, it is easy to define
an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c which is called
array index.
• Numeric array - An array with a numeric index. Values are stored and accessed in linear fashion
• Associative array - An array with strings as index. This stores element values in association with key
values rather than in a strict linear index order.
• Multidimensional array - An array containing one or more arrays and values are accessed using
multiple indices
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default, the array index starts from zero.
Example
The following example demonstrates how to create and access numeric arrays. Here we have used
array() function to create array. This function is explained in function reference.
<html>
<body>
<?php
$numbers[0] = "one";
$numbers[1] = "two";
Page | 175
WEB PRORAMMING
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
?>
</body>
</html>
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you can
establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best
choice. Instead, we could use the employees names as the keys in our associative array, and the
value would be their respective salary.
Example
<html>
Page | 176
WEB PRORAMMING
<body>
<?php
$salaries = array(
);
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
?>
</body>
</html>
Page | 177
WEB PRORAMMING
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each element in
the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using
multiple index.
Example
In this example, we create a two dimensional array to store marks of three students in three
subjects:
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"chemistry" => 39
),
"chemistry" => 29
),
"chemistry" => 39
);
Page | 178
WEB PRORAMMING
?>
</body>
</html>
Page | 179
WEB PRORAMMING
Question 80. Explain the differences between GET and LOST methods in PHP.
Provide an example of how to use each method in a form.
Answer:
In PHP, GET and POST are two primary methods used to send data from an HTML form to the server.
Here are the differences between them, along with examples for each method.
Data Data is visible in the URL (query string). Data is hidden from the URL.
Visibility
Data Length Limited by URL length (around 2000 characters). No size limit (theoretically
large, but server-dependent).
Security Less secure, as data is exposed in the URL. More secure, suitable for
sensitive information.
Usage Ideal for retrieving data or making search Ideal for sending data (e.g.,
queries. form submissions).
Bookmarking Can be bookmarked and shared (data remains in Cannot be bookmarked (no
the URL). data in the URL).
Request Can result in cached results due to URL content. Data is not cached by default.
Type
The GET method is typically used when sending data that is not sensitive, such as search queries or
filters.
<!DOCTYPE html>
<html>
<body>
<label for="query">Search:</label>
Page | 180
WEB PRORAMMING
</form>
</body>
</html>
<?php
if (isset($_GET['query'])) {
?>
The POST method is typically used for sending sensitive or large amounts of data, such as passwords
or form data that should not be exposed in the URL.
<!DOCTYPE html>
<html>
<body>
<label for="username">Username:</label>
<label for="password">Password:</label>
Page | 181
WEB PRORAMMING
</form>
</body>
</html>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
?>
Page | 182
WEB PRORAMMING
<?php
function isPalindrome($string) {
// Remove whitespace and convert to lowercase
$cleanedString = strtolower(preg_replace("/[^A-Za-z0-9]/", "", $string));
Explanation
It removes all non-alphanumeric characters (like spaces, punctuation) and converts the string to
lowercase to ignore case sensitivity.
Finally, it checks if the original cleaned string is equal to the reversed string. If they match, it returns
true (indicating the string is a palindrome); otherwise, it returns false.
Example Usage
Page | 183
WEB PRORAMMING
if (isPalindrome($testString1)) {
} else {
if (isPalindrome($testString2)) {
} else {
Output
Page | 184
WEB PRORAMMING
Question 82. Describe how to connect to a MySQL database using PHP (PHP-
MySQLi connectivity). Write a simple code snippet that connects to a
database and checks for a successful connection.
Answer:
To connect to a MySQL database in PHP, you can use the MySQLi (MySQL Improved) extension, which
provides a secure way to interact with MySQL databases. MySQLi can be used in both procedural and
object-oriented styles. Here, I’ll explain the procedural method.
Define Database Credentials: Specify the database host, username, password, and database name.
Establish a Connection: Use the mysqli_connect() function with the database credentials.
Check the Connection: Verify if the connection is successful. If not, output an error message.
Code Snippet
Here’s a simple code snippet to connect to a MySQL database using PHP MySQLi:
<?php
// Database credentials
// Establish connection
// Check connection
if (!$conn) {
} else {
Page | 185
WEB PRORAMMING
mysqli_close($conn);
?>
Explanation
Database Credentials:
$host is the hostname of the database server. If your database is on the same server, you typically
use "localhost".
The mysqli_connect() function takes four parameters: the host, username, password, and database
name.
If the connection fails, mysqli_connect_error() will return an error message detailing why it failed.
Finally, the mysqli_close($conn); function is used to close the connection. This is optional because
PHP automatically closes the connection at the end of the script, but it's good practice to close it
manually when you're done.
Page | 186
WEB PRORAMMING
Question 83. Describe how to create and select a database using PHP
(mysqli_select_db). Write a simple code snippet that connects to a database
and checks for a successful connection.
Answer:
To create and select a database in PHP using the MySQLi extension, you first establish a connection
to the MySQL server, then create the database if it doesn't already exist, and finally select the
database to perform further operations.
Connect to the MySQL Server: Use mysqli_connect() to connect to the MySQL server (without
specifying a database initially).
Create the Database (if it doesn’t exist): Use a SQL CREATE DATABASE query to create the database.
Select the Database: Use mysqli_select_db() to choose the newly created or existing database for
further operations.
Check for Errors: Check each step for successful execution and handle any errors.
Code Snippet
The following code demonstrates connecting to the MySQL server, creating a database if it doesn't
exist, and selecting it.
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "my_new_database";
if (!$conn) {
Page | 187
WEB PRORAMMING
if (mysqli_query($conn, $sql)) {
} else {
if (mysqli_select_db($conn, $dbname)) {
} else {
mysqli_close($conn);
?>
Explanation
The if (!$conn) check verifies if the connection is successful. If not, an error message is displayed
using mysqli_connect_error().
The CREATE DATABASE IF NOT EXISTS $dbname SQL statement is used to create the database only if
it doesn’t already exist.
Page | 188
WEB PRORAMMING
mysqli_select_db($conn, $dbname); selects the specified database for use in subsequent queries.
If the database selection is successful, a message is displayed. If it fails, an error message is shown
using mysqli_error($conn).
mysqli_close($conn); closes the connection to the MySQL server. Although PHP closes the
connection automatically at the end of the script, it’s good practice to do this manually once all
database operations are complete.
Page | 189
WEB PRORAMMING
Question 84. Describe how to create a table and insert a record using PHP.
Write a simple code snippet that connects to a database and checks for a
successful connection
Answer:
To create a table and insert a record into it in PHP, you need to connect to the MySQL database,
create the table if it doesn’t already exist, and then insert a record. Here’s a step-by-step explanation
and code example.
Create the Table: Use a SQL CREATE TABLE statement to define the structure of the table (columns
and data types).
Insert a Record: Use an INSERT INTO statement to add a new row of data to the table.
Check for Errors: Verify if each operation (connection, table creation, record insertion) is successful
and handle any errors.
Code Snippet
The following code demonstrates connecting to a MySQL database, creating a table, and inserting a
record.
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
Page | 190
WEB PRORAMMING
if (!$conn) {
$tableName = "users";
)";
if (mysqli_query($conn, $sqlCreateTable)) {
} else {
if (mysqli_query($conn, $sqlInsert)) {
} else {
Page | 191
WEB PRORAMMING
mysqli_close($conn);
?>
Explanation
The connection is checked with if (!$conn). If it fails, an error message is displayed using
mysqli_connect_error().
The CREATE TABLE IF NOT EXISTS SQL statement defines the structure of the table.
Inserting a Record:
The INSERT INTO SQL statement adds a new row to the users table.
In this example, we insert a record with username set to 'john_doe' and email set to
'[email protected]'.
mysqli_query($conn, $sqlInsert) executes the SQL statement to insert the record. If successful, a
message is displayed; otherwise, an error message is shown.
mysqli_close($conn); closes the connection to the database. This is optional since PHP automatically
closes the connection at the end of the script, but it’s good practice to close it explicitly.
Page | 192
WEB PRORAMMING
Question 85. Describe how to show a record of the table using PHP
(mysqli_fetch_row). Write a simple code snippet that connects to a database
and checks for a successful connection.
Answer:
To show a record from a MySQL table in PHP, you can use the mysqli_fetch_row() function, which
retrieves a single row from the result set as a numerical array. Here’s how to connect to the
database, retrieve a record, and display it.
Connect to the Database: Use mysqli_connect() to establish a connection to the MySQL server and
select the database.
Run a Query: Use a SELECT SQL statement to retrieve records from the table.
Fetch the Row: Use mysqli_fetch_row() to get a single row of data from the result set.
Display the Record: Access the row’s elements using numeric indices to display the data.
Code Snippet
The following code connects to a MySQL database, retrieves a record from a table, and displays it.
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";
Page | 193
WEB PRORAMMING
if (!$conn) {
$sql = "SELECT id, username, email, created_at FROM $tableName LIMIT 1"; // Fetches the first
record
if ($result) {
if (mysqli_num_rows($result) > 0) {
} else {
} else {
mysqli_close($conn);
?>
Page | 194
WEB PRORAMMING
Explanation
The connection is verified with if (!$conn). If the connection fails, it displays an error using
mysqli_connect_error().
The SELECT SQL statement retrieves data from the specified table (users in this example).
Here, we select columns id, username, email, and created_at from the table and use LIMIT 1 to fetch
only the first record.
$row[0], $row[1], $row[2], and $row[3] correspond to the id, username, email, and created_at fields,
respectively.
If the query returns at least one row, it displays the record’s data.
mysqli_close($conn); closes the connection to the database. This is good practice, even though PHP
automatically closes the connection at the end of the script.
Page | 195