0% found this document useful (0 votes)
4 views

30_WEB_PROGRAMMING

The document provides a detailed explanation of key internet and web concepts, including the Internet, WWW, web browsers, HTTP, and HTTPS. It describes client-server architecture, the HTTP request-response model, and the structure of HTML, along with examples of basic HTML tags. Additionally, it outlines the functions and roles of web pages and web browsers in accessing online information.

Uploaded by

Aashish Kantiwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

30_WEB_PROGRAMMING

The document provides a detailed explanation of key internet and web concepts, including the Internet, WWW, web browsers, HTTP, and HTTPS. It describes client-server architecture, the HTTP request-response model, and the structure of HTML, along with examples of basic HTML tags. Additionally, it outlines the functions and roles of web pages and web browsers in accessing online information.

Uploaded by

Aashish Kantiwal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 196

QUESTIONS:

Question 1. Explain the Following Terms: WWW, HTTP, HTTPS, Web


browser, Web Server Explain the Internet & WWW in detail.
Answer:

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

5. HTTPS (Hypertext Transfer Protocol Secure):


HTTPS is the secure version of HTTP. It encrypts the transmitted data between the browser
and the server, providing security for sensitive information like passwords, credit card
numbers, and personal data.
HTTPS uses SSL (Secure Sockets Layer) or its newer version, TLS (Transport Layer
Security), to ensure that data cannot be intercepted or tampered with during transmission.
Modern browsers display a padlock icon in the address bar to indicate that the website uses
HTTPS.
6. Web Server:
A web server is a computer or software that stores, processes, and delivers web pages to
users upon request. When a user enters a website address (URL) in their browser, the browser
sends a request to the web server. The server processes this request and responds by returning
the appropriate web page or resource.
Web servers run server software such as Apache, Nginx, or Microsoft IIS, which manage the
hosting of websites and the communication with web browsers via HTTP/HTTPS.

Page | 1
WEB PRORAMMING

Question 2. Explain the Internet & WWW in detail


Answer:

What is the Internet?


The Internet is a vast, global network of interconnected computers and devices that
communicate with each other to share information and resources. It consists of millions of
private, public, academic, business, and government networks linked by a variety of
technologies like wired connections, wireless networks, satellites, and fiber optics.
The Internet allows devices to communicate through standardized protocols such as TCP/IP
(Transmission Control Protocol/Internet Protocol), ensuring that data can be transmitted,
routed, and received by devices worldwide.
Key Features of the Internet:
Global Network: The Internet connects computers and devices across the world.
Decentralized Structure: There is no single governing body or organization that controls the
entire Internet.
Packet Switching: Data is broken into small pieces (called packets) and sent over various
routes before being reassembled at its destination.
Protocols: Communication on the Internet relies on standardized protocols like TCP/IP,
which ensures that data can be transmitted reliably.
Services: The Internet provides various services like email, file sharing, remote access, and
the World Wide Web (WWW).

What is the World Wide Web (WWW)?


The World Wide Web (WWW), often referred to simply as "the web," is a service that
operates over the Internet. It is a vast collection of web pages that are interconnected via
hyperlinks and accessible through web browsers. The WWW is often mistakenly thought of
as the Internet itself, but it is actually just one of many services that run on the Internet.
The web was invented by Tim Berners-Lee in 1989, and it revolutionized how information
is shared and accessed online. While the Internet is the infrastructure that connects millions
of computers, the web is a system of information that users can browse and interact with.
Key Features of the WWW:
Web Pages: The web consists of millions of pages that are written in HTML (Hypertext
Markup Language).
Hyperlinks: Web pages are interconnected through hyperlinks, allowing users to navigate
from one page to another.

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

Question 3. Explain Client Server Architecture with a diagram.


Answer:

Client-server architecture is a fundamental concept in system design where a network


involves multiple clients and a server. Clients are devices or programs that request services or
resources, while the server is a powerful machine providing these resources or services. This
architecture allows efficient data management and resource sharing, making it popular in web
applications, databases, and other network-based systems. By separating roles and
distributing tasks, client-server architecture enhances performance, scalability, and security.

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

Client Server Communication Process


The client and the server are the first two evident participants in client server communication.
Requests: Requests are sent from the client to the server to inform it of events, such as a user
wishing to log in using his credentials or to ask the server for data, such as files.
Response: A server’s response to a client request is sent to the client as a message. This
might, for instance, be the outcome of an authentication.
Service: a particular task the server makes available to the client for use, such as
downloading an image.
Client: The client is a device or application that requests services or resources from the
server. It initiates communication with the server and processes the results returned by the
server.
Server: The server is a powerful machine or application that provides services or resources to
clients. It processes client requests, performs the necessary computations or data retrieval,
and sends back the appropriate responses.
Network: The network facilitates communication between clients and servers. It enables data
exchange using various protocols and ensures reliable connectivity.
Protocols: Protocols are standardized rules that govern data transmission and communication
between clients and servers. They ensure that data is transmitted in a secure, reliable, and
understood manner.

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

Question 4. Explain the HTTP Request-Response model.


Answer:

HTTP (Hypertext Transfer Protocol) is a fundamental protocol of the Internet, enabling


the transfer of data between a client and a server. It is the foundation of data communication
for the World Wide Web.
HTTP provides a standard between a web browser and a web server to establish
communication. It is a set of rules for transferring data from one computer to another. Data
such as text, images, and other multimedia files are shared on the World Wide Web.
Whenever a web user opens their web browser, the user indirectly uses HTTP. It is an
application protocol that is used for distributed, collaborative, hypermedia information
systems.
Methods of HTTP
GET: Used to retrieve data from a specified resource. It should have no side effects and is
commonly used for fetching web pages, images, etc.
POST: Used to submit data to be processed by a specified resource. It is suitable for form
submissions, file uploads, and creating new resources.
PUT: Used to update or create a resource on the server. It replaces the entire resource with
the data provided in the request body.
PATCH: Similar to PUT but used for partial modifications to a resource. It updates specific
fields of a resource rather than replacing the entire resource.
DELETE: Used to remove a specified resource from the server.
HEAD: Similar to GET but retrieves only the response headers, useful for checking resource
properties without transferring the full content.
OPTIONS: Used to retrieve the communication options available for a resource, including
supported methods and headers.
TRACE: Used for debugging purposes to echo the received request back to the client, though
it's rarely used due to security concerns.
CONNECT: Used to establish a tunnel to the server through an HTTP proxy, commonly
used for SSL/TLS connections.
What is an HTTP Request?
An HTTP request is a message sent by a client (usually a web browser) to a web server to
request a resource, typically a web page, image, or data. These requests follow a specific
structure and contain essential components:
HTTP Method: This defines the action to be performed, such as GET (retrieve data), POST
(send data), PUT (update data), DELETE (remove data), and more.

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

Question 6. Explain HTML Structure in detail with an example.


Answer:

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>

1. DOCTYPE Declaration: <!DOCTYPE html>


Purpose: Declares the document type as HTML5 (the current version of HTML).
Importance: Ensures that the browser renders the page in standards-compliant mode.

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.

3. <head> Tag (Metadata Section)


The <head> section contains metadata about the document that is not visible to users but is
crucial for browsers, search engines, and other tools.
Common Elements in the <head> Section:
<title>: Sets the title of the web page, which is displayed on the browser’s title bar
or tab.
<link>: Used to link external resources like CSS files.

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

Question 7. Explain any 7 basic tags of HTML with examples.


Answer:

1. Heading Tag (<h1> to <h6>)


The heading tags are used to define headings on a web page. HTML has six levels of
headings, from <h1> (most important) to <h6> (least important). These tags are
crucial for structuring content and improving SEO (Search Engine Optimization).
Example:
<h1>This is a Main Heading</h1>
<h2>This is a Subheading</h2>
<h3>This is a Smaller Subheading</h3>
Output:
<h1> creates the largest and most important heading.
<h6> creates the smallest and least important heading

2. Paragraph Tag (<p>)

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>

3. Anchor Tag (<a>)


The anchor tag (<a>) is used to create hyperlinks. The href attribute specifies the destination
URL. You can also link to a different section of the same page using anchor links.
Example:
<a href="https://www.example.com">Click here to visit Example.com</a>
<a href="#section2">Jump to Section 2 on this page</a>

4.Image Tag (<img>)


The image tag (<img>) is used to embed images in a web page. It requires the src attribute,
which specifies the image source (URL or file path), and alt, which provides alternative text
for the image.
Example:
<img src="https://via.placeholder.com/150" alt="Placeholder Image">

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”>

6. Audio Tag (<audio>)


The <audio> tag is used to embed an audio player. It supports attributes like controls (for
play/pause functionality) and can include multiple source formats for compatibility.
Example:
<audio controls>
<source src="audiofile.mp3" type="audio/mpeg">
</audio>

7. Table Tag (<table>, <tr>, <th>, <td>)


The <table> tag defines a table structure. Inside a table, you have:
<tr> (Table Row): Defines a row in the table.
<th> (Table Header): Defines a header cell, usually bold and centered.
<td> (Table Data): Defines a standard cell with regular content.

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:

Heading Tag (<h1> to <h6>)


The heading tags in HTML are used to define the headings of a webpage. There are six
levels of headings, ranging from <h1> (the most important, usually the main heading of a
page) to <h6> (the least important, usually used for subheadings or small text).
Syntax:
<h1>Heading Level 1</h1>
<h2>Heading Level 2</h2>
<h3>Heading Level 3</h3>
<h4>Heading Level 4</h4>
<h5>Heading Level 5</h5>
<h6>Heading Level 6</h6>

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

2. Paragraph Tag (<p>)


The paragraph tag (<p>) is used to define blocks of text. It creates a paragraph, which is
automatically separated from other text with margin or line breaks.
Syntax:
<p>This is a paragraph of text.</p>
Examples:
<html>
<head>
<title>HTML Paragraph Example</title>
</head>
<body>
<h1>Introduction to HTML</h1>

<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:

1. Setting Font Color in HTML


You can change the font color by using the style attribute within HTML tags, such as <p>,
<h1>, etc., and defining the color property.

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>

2. Setting Background Color of the Body in HTML


You can change the background color of the entire webpage (or any specific element) by
using the bgcolor attribute in the <body> tag (this is an old method) or by using the style
attribute to define the background-color property.
Using bgcolor (Deprecated Method):
<body bgcolor="lightblue">
<h1>Welcome to My Website</h1>
<p>This page has a light blue background using the "bgcolor" attribute.</p>
</body>
Using style Attribute:
<body style="background-color: light blue;">
<h1>Welcome to My Website</h1>
<p>This page has a light blue background using the "style" attribute.</p>
</body>

Page | 16
WEB PRORAMMING

Question 10. What is order list in HTML? Explain different types of order
list with example.
Answer:

Ordered List in HTML (<ol>)


An ordered list in HTML is a list where the items are numbered or have an ordered
sequence. The <ol> (ordered list) tag is used to create an ordered list, and the <li> (list item)
tag is used to define each list item.
Syntax:
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
Types of Ordered Lists:
By default, an ordered list uses numbers, but you can change the type of numbering using the
type attribute.
Numbered List (Default)
<ol>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>

Alphabetical Lowercase (type="a")


<ol type="a">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>

Page | 17
WEB PRORAMMING

Alphabetical Uppercase (type="A")


<ol type="A">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
Roman Numerals Lowercase (type="i")
<ol type="i">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>
Roman Numerals Uppercase (type="I")
<ol type="I">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ol>

Page | 18
WEB PRORAMMING

Question 11. What is unordered list in HTML? Explain different types of


unordered lists with examples.
Answer:

Unordered List in HTML (<ul>)


An unordered list is a list where the items are not numbered. Instead of numbers, a symbol
or bullet (such as a dot or square) is used. The <ul> (unordered list) tag is used to create an
unordered list, and the <li> (list item) tag is used for each list item.
Syntax:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
Types of Unordered Lists:
The default bullet is a solid circle, which can be changed using the type attribute.
Disc (Default)
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
Circle (type="circle")
<ul type="circle">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
Square (type="square")
<ul type="square">
<li>First item</li>

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>

<h2>Ordered List with Numbers</h2>


<ol>
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
</ol>

<h2>Ordered List with Uppercase Letters</h2>


<ol type="A">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
</ol>

<h2>Unordered List with Default Bullets</h2>


<ul>
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
</ul>

Page | 20
WEB PRORAMMING

<h2>Unordered List with Squares</h2>


<ul type="square">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
</ul>

</body>
</html>

Page | 21
WEB PRORAMMING

Question 12. Explain HTML Description List with an example


Answer:

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>

<h2>HTML Description List Example</h2>

<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

Question 13. Explain Anchor tag with its attributes.


Answer:

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>

Attributes of the Anchor Tag:


href (Hypertext Reference)
Defines the URL (or location) to which the link points.
Example:
<a href="https://www.google.com">Go to Google</a>
target
Specifies where to open the linked document. Common values include:
_self: Opens the link in the same tab (default).
_blank: Opens the link in a new tab or window.
_parent: Opens the link in the parent frame.
_top: Opens the link in the full body of the window (useful for frames).
Example:
<a href="https://www.wikipedia.org" target="_blank">Open Wikipedia in a new tab</a>
title
Provides additional information about the link. When the user hovers over the link, the title
text will appear as a tooltip.
Example:
<a href="https://www.github.com" title="Go to GitHub">GitHub</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>

<h2 id="section1">Section 1</h2>

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.

Syntax: <img src= “path to Image” />

The <img> tag has two required attributes:


src - specifies the path (URL) to the image.
alt - Specifies an alternate text for the image, if the user for some reason cannot view it. If a
browser cannot find an image, it will display the value of the alt attribute
width & height - The width and height attributes always define the width and height of the
image in pixels or percentage.
align – the align attribute(currently deprecated) will aligns the image with its surrounding
context (Use the float and/or vertical-align CSS properties instead of this attribute).
Example:
<html>
<head>
<title>Image</title>
</head>
<body>
<h3>Image Alignment = Right </h3>
<img src= "C:\Users\mohan_bjpjiz\OneDrive\Desktop\CSS\3.jpeg" align = "right" />
</body>
</html>

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>

<p>You can specify background images<br>


for any visible HTML element.<br>
In this example, the background image<br>
is specified for a div element.<br>
By default, the background-image<br>
will repeat itself in the direction(s)<br>
where it is smaller than the element<br>

Page | 27
WEB PRORAMMING

where it is specified. (Try resizing the<br>


browser window to see how the<br>
background image behaves.</p>

</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 HTML <video> element is used to show a video on a web page.

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>

<source src = "movie.mp4" type = "video/mp4" >

<source src = "movie.ogg" type = "video/ogg" >

Your browser does not support the video tag.

</video>

Example:

<html>

<head>

<title> Video </title>

</head>

<body>

<video controls>

<source src = "C:\Users\mohan_bjpjiz\Videos\Captures\video1.mp4" type = "video/mp4" >

<source src = "C:\Users\mohan_bjpjiz\Videos\Captures\video2.mp4" type = "video/mp4" >

Page | 29
WEB PRORAMMING

Your browser does not support the video tag.

</video>

</body>

</html>

Video Tag Attributes

Attribute Value Description

autoplay autoplay Specifies that the video will start playing as soon as it
is ready

controls controls Specifies that video controls should be displayed


(such as a play/pause button etc).

height pixels Sets the height of the video player

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

poster URL Specifies an image to be shown while the video is


downloading, or until the user hits the play button

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

The autoplay attribute is a boolean attribute.

When present, the video will automatically start playing.

Add muted after autoplay to let your video file start playing automatically (but muted).

Example:
<html>
<body>

<h1>The video autoplay attribute</h1>

<video width="320" height="240" controls autoplay>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

</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>

<h1>The video controls attribute</h1>

<video width="320" height="240" controls>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

</body>
</html>

height and width

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>

<h1>The video width and height attributes</h1>

<video width="320" height="240" controls>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

</body>
</html>

Muted

The muted attribute is a boolean attribute.

When present, it specifies that the audio output of the video should be muted.

Example:
<html>
<body>

<h1>The video muted attribute</h1>

<video width="320" height="240" controls muted>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

</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>

<h1>The video poster attribute</h1>

<video width="320" height="240" poster="/images/w3schools_green.jpg" controls>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

</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

<h1>The video src attribute</h1>

<video width="320" height="240" controls src="movie.ogg">


Your browser does not support the video tag.
</video>

<p><b>Note:</b> The .ogg fileformat is not supported in old IE and Safari.</p>

</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.

Audio tag Attributes:


Autoplay

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>

<h1>The audio autoplay attribute</h1>

<p>Click on the play button to play a sound:</p>

<audio controls autoplay>


<source src="alarm.ogg" type="audio/ogg">
<source src="alarm.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

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>

<h1>The audio autoplay attribute</h1>

<p>Click on the play button to play a sound:</p>

<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>

<h1>The audio autoplay attribute</h1>

<p>Click on the play button to play a sound:</p>

<audio controls loop>


<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>

Muted

The muted attribute is a boolean attribute. When present, it specifies that the audio output
should be muted.

Example:
<html>
<body>

<h1>The audio autoplay attribute</h1>

<p>Click on the play button to play a sound:</p>

Page | 38
WEB PRORAMMING

<audio controls muted>


<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>
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.

Note: The preload attribute is ignored if autoplay is present.

Example:
<html>
<body>

<h1>The audio preload attribute</h1>

<p>Click on the play button to play a sound:</p>

<audio controls preload="none">


<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 | 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>

<h1>The audio src attribute</h1>

<p>Click on the play button to play a sound:</p>

<audio src="alarm.ogg" controls>


Your browser does not support the audio element.
</audio>
</body>
</html>

Page | 40
WEB PRORAMMING

Question 18. Explain Table tag with its Attributes.

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>

<table border = "1">


<caption>Table Caption </caption>
<tr>
<th>Heading 1</th>
<th>Heading 2</th
</tr>
<tr>
<td>Row1 Col1 Data</td>
<td>Row1 Col2 Data</td>
</tr>
<tr>
<td>Row2 Col1 Data</td>
<td>Row2 Col2 Data</td>
</tr>

Page | 41
WEB PRORAMMING

</body>
</html>

Table Element Attributes


Border
border attribute with <table> tag is used to specify the thickness of the border lines around
the table. The value of the border attribure should be a non zero value in pixels. If its value is
zero, HTML displays the table without a border. The default value is zero in most browsers.
Border =number – width in pixels of border

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

Table row <tr> Attributes

Page | 42
WEB PRORAMMING

Align and valign


It is used to set the position of the element within the table.
Align=position –left, center, right
vlign=position –top, middle, bottom
Bgcolor: it is used to apply background colour to the table.

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>

<table border = "3" cellpadding = 10>


<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>

</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>

<table border = "3" cellspacing = 10>


<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>
</body>
</html>

Page | 45
WEB PRORAMMING

Question 20. Explain rowspan and colspan with examples.


Answer:

HTML Table with Rowspan


In HTML, the rowspan attribute specifies how many rows a table cell should span,
determining its vertical position.

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.

Note: Applied within a <td> or <th> element.

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

HTML Table with Colspan

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.

Note: The colspan is defined as the <th> element.

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:

<br> (Line Break)


It inserts a line break in the text, moving the content following it to a new line. Useful for
single line breaks in text content (similar to pressing "Enter" in a text editor).
Example:
<html>
<body>
This is the first line.<br>
This is the second line.
</html>
</body>

<hr> (Horizontal Rule)


It inserts a horizontal line (rule) across the page, often used to separate sections of content.
Provides a visual divider in the content and can be styled with CSS to change thickness,
color, or width.
Example:
<html>
<body>
<p>Content above the line.</p>
<hr>
<p>Content below the line.</p>
</html>
</body>

<b> (Bold Text)


It Renders text in bold font weight. Used to emphasize certain text visually but without
implying any importance or structural emphasis. For actual emphasis, use <strong> instead.
Example:
<html>
<body>

Page | 48
WEB PRORAMMING

This is <b>bold text</b>


</html>
</body>

<i> (Italic Text)


Renders text in italic style. Used to distinguish parts of text, such as foreign words, names, or
technical terms. For emphasized text, use <em> instead.
Example:
<html>
<body>
html
This is <i>italic text</i>
</html>
</body>

<u> (Underlined Text)


It underlines the enclosed text. Used for text decoration, though it’s less common today as
underlining can be confused with hyperlinks. CSS is often preferred for styling text.
Example:
<html>
<body>
This is <u>underlined text</u>
</html>
</body>
<pre> (Preformatted Text)
It preserves both whitespace and line breaks within the enclosed text, displaying it exactly as
written in the HTML source. Often used for displaying code, poetry, or other text where line
breaks and spaces are essential.
Example:
<html>
<body>
<pre>
This is preformatted text.

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

Question 22. Explain Marquee tag with its attributes.


Answer:

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>

Attributes Values Description

Define the background


bgcolor Color Name
color of the marquee.

Define the direction of


direction Top, Down, Left, Right
scrolling the content

Specifies how many times


loop Number content moves. The default
value is infinite.

Define the height of


height px or %
marquee

Define the width of


width px or %
marquee

Page | 51
WEB PRORAMMING

Attributes Values Description

Specify horizontal space


hspace px
around marquee

Specify vertical space


vspace px
around marquee

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>

HTML Forms in Client-Server Architecture

In a client-server architecture, HTML forms play a critical role in facilitating communication


between the client (browser) and the server. Here’s why they’re important:

1. Data Collection and User Interaction


Forms allow clients (users) to interact with web applications by submitting data, such as login
credentials, search queries, contact details, or any other form of input.
This data is collected by the client-side HTML form and then transmitted to the server for
further processing.
2. Request-Response Cycle Initiation
Submitting a form triggers an HTTP request from the client to the server, often using GET or
POST methods.
GET: Used for retrieving information. Parameters are included in the URL query string,
making it suitable for non-sensitive data.
POST: Used for sending data securely in the HTTP body, appropriate for sensitive or larger
data submissions.
The server receives this request, processes it, and sends back a response, often displaying the
result or updating the user interface on the client side.

Page | 54
WEB PRORAMMING

3. Enabling Server-Side Processing


When the form data is received, the server can perform various tasks such as storing data in a
database, processing calculations, validating entries, or sending emails.
The server’s response could be a confirmation message, a new page, or additional data to
display (e.g., in dynamic or AJAX-powered applications).
4. Security and Data Integrity
HTML forms support security measures like data validation and sanitization to ensure that
data submitted is accurate and free from harmful content.
Form attributes like method="POST" protect sensitive data (e.g., passwords) by sending it in
the request body instead of the URL.
Other security mechanisms, such as CSRF tokens (added by backend frameworks), are
integrated into forms to prevent unauthorized form submissions.
5. Enhancing Usability with Frontend Validation
HTML5 provides built-in form validation features (like required, min, max, pattern, etc.),
reducing the load on the server by ensuring basic validation happens on the client side.
This immediate feedback improves the user experience and minimizes unnecessary server
interactions.

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>

Select Gender </br>


Male <input type="radio" name = "gn" > <br/>
Female <input type="radio" name = "gn"/ >
</br>
</br>

Page | 58
WEB PRORAMMING

Subject: <br/>
<input type= "checkbox"/>Maths <br/>
<input type= "checkbox"/>Science<br/>
<input type= "checkbox"/>English
<br/>
<br/>

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


</form>

</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

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


</br>
</br>
Password:
<input type = "password"/ >
</br>
</br>

Select Gender </br>


Male <input type="radio" name = "gn" > <br/>
Female <input type="radio" name = "gn"/ >
</br>
</br>

Subject: <br/>
<input type= "checkbox"/>Maths <br/>
<input type= "checkbox"/>Science<br/>
<input type= "checkbox"/>English
<br/>
<br/>

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


</form>

</body>
</html>

File Upload Field


The HTML <input type=”file”> element is used to create a file input box in forms. It
allows users to browse and select files to upload from the devices. When the form is
submitted, the selected file(s) can be uploaded to the server.

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.

Name This attribute allows you to give a name to a frame. It is used to


indicate which frame a document should be loaded into. This is
especially important when you want to create links in one frame that
load pages into another frame, in which case the second frame needs a
name to identify itself as the target of the link.
Frameborder This attribute specifies whether or not the borders of that frame are
shown; it overrides the value given in frameborder the frameborder
attribute on the frameset> tag if one is given, and this can take values
either 1 (yes) or 0 (no)

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

Question 28. Explain the nested frame with an example.


Answer:

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>&copy; 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

Question 32. Explain simple/html element selector with example.


Answer:

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

Question 33. Explain the id selector with an example.


Answer:

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

Question 34. Explain the class selector with an example.


Answer:

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

Question 35. Explain the generic selector with an example.


Answer:

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

Question 36. Compare between id selector and class selector.


Answer:

ID Selector Class Selector


Unique to each element on a page. Can be used to select multiple elements.

Defined using the "id" attribute. Defined using the "class" attribute.

Preceded by a "#" in CSS selectors. Preceded by “.” in CSS selectors.

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

Question 37. Explain the grouping of selectors with an example.


Answer:

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.

Detailed Explanation of Inline CSS


Inline CSS is a way to add styles directly to HTML elements by using the style attribute
within the tag. Unlike other types, inline CSS only applies to the specific element its attached
to, so its useful for small, unique style changes on individual elements.
When to Use Inline CSS
When you need a quick style adjustment on one specific element.
When the styling needs to apply to a single item without affecting similar elements on the
page.
When you dont need the style to be reused or affect the overall document.

Example of Inline CSS

<P Style= “Background: Blue; Color: White;”> Inline CSS </P>

Page | 84
WEB PRORAMMING

Code for Inline CSS:

<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

Question 39. Explain Inline CSS with advantages and disadvantages


Answer:

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>

Advantages of Inline CSS


Easy and Quick:
Inline CSS is great for making simple, fast changes to just one part of the page. For example,
if you only want to change the color of one specific heading, you can do it directly without
needing an external file.
Highest Priority:
Inline CSS has the highest priority, so it will override any styles from external or internal
CSS files. This can be useful when you want specific elements to have a unique look.
Good for Testing:
Inline CSS is helpful for testing and experimenting. It lets you try out different styles quickly
without needing to save them in a CSS file. Once you find a style you like, you can then add
it to a CSS file if needed.
No External File Needed:
With inline CSS, you dont need to link or create a separate CSS file, making it convenient for
small changes. It keeps everything in one place within the HTML, which can be useful for
single-use or one-off styles.

Disadvantages of Inline CSS


Hard to Reuse:
Inline styles only apply to the specific element theyre written in. If you want the same style
on multiple elements, you would need to write the same inline CSS over and over for each
one, which can get repetitive.
Messy Code:

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

Question 40. Explain Internal CSS with advantages and disadvantages.


Answer:

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>

<STYLE TYPE= “TEXT/CSS”>

P {COLOR; RED;}

</STYLE>

</HEAD>

<BODY>

<P> HELLO </P>

</BODY>

</HTML>

Advantages of Internal CSS


Centralized for Single Page:
Internal CSS keeps all styling instructions within the HTML document. This can be helpful
for single-page designs where all the styles are kept in one place, making it easy to view and
edit.

Page | 88
WEB PRORAMMING

No External File Needed:


Since the CSS is within the HTML file itself, theres no need for additional files to load,
which can slightly improve the loading time for small projects.
Easier Specificity and Overrides:
Internal CSS can more easily override styles from external stylesheets or browser defaults for
that particular page. It has a higher priority in the CSS hierarchy, allowing for straightforward
customization on a specific page.

Disadvantages of Internal CSS


Less Efficient for Large Sites:
Internal CSS is limited to a single page, so it needs to be rewritten on each page. For larger
sites, this can become time-consuming and make the code harder to maintain.
Increased Page Size:
Including all CSS within each HTML document increases the overall file size, which can
slow down loading times, especially if there are complex styles on multiple pages.
Mixes HTML and CSS Code:
Internal CSS combines HTML and CSS in the same file, which can make the code harder to
read and less organized. For developers, separating CSS into its own file (using external CSS)
usually promotes cleaner and more manageable code.

Page | 89
WEB PRORAMMING

Question 41. Explain External CSS with advantages and disadvantages


Answer:

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

Advantages of External CSS


Consistency Across Multiple Pages:
External CSS provides a single stylesheet that can be applied to multiple pages, ensuring a
consistent design throughout the website. Updating the CSS file will reflect changes across
all pages that link to it, making site-wide updates fast and efficient.
Reduced Page Load Time (with Caching):
Once the CSS file is loaded by the browser, it is cached, so it doesnt need to be reloaded on
each page. This can improve load times for users as they navigate through the site.
Separation of Concerns:
Separating CSS from HTML keeps the code cleaner and more organized, making it easier to
read, maintain, and debug. HTML files focus on structure, while CSS files handle styling.
Smaller HTML File Size:
Linking to an external CSS file reduces the HTML file size, making it lighter and quicker to
load, especially when multiple pages rely on extensive styling.

Disadvantages of External CSS


Dependency on External File:
If the CSS file fails to load due to server issues or network problems, the webpage will load
without styles, which can impact user experience by displaying an unstyled, potentially
confusing layout.
Slightly Slower Initial Load:
The browser has to fetch the CSS file separately from the HTML, which can add a small
delay in loading time, especially for the first page load. However, this is typically mitigated
by caching on subsequent loads.
Not Ideal for Small, Single-Page Sites:
For very small or single-page websites, having a separate CSS file may add unnecessary
complexity, as an internal or inline CSS might be simpler for quick styling.

Page | 91
WEB PRORAMMING

Question 42. Compare inline CSS v/s internal CSS v/s external CSS
Answer:

❖ Location and Usage


Type Location Usage
Inline CSS Directly within HTML tags Used for applying styles to
using the `style` attribute specific elements only
Internal CSS Inside the `<style>` tag in Used for applying styles to
the `<head>` section of an a single HTML page
HTML document
External CSS In a separate `.css` file Used for applying styles
linked with the `<link>` tag across multiple pages of a
in HTML website

❖ 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

External CSS - Dependent on external file loading; if


CSS fails to load, page appears
unstyled<br>
- Initial load might be slightly slower due
to file retrieval<br>
- Adds complexity for very simple or
single-page projects

❖ Best Used For


Type Best Use Cases
Inline CSS - Quick, one-time style overrides for
specific elements<br>
- Small, simple web pages with minimal
styling needs
Internal CSS - Single-page websites where all styles are
self-contained<br>
- Prototypes or test pages where styles are
page-specific
External CSS - Medium to large websites requiring
consistent styling<br>
- Projects where scalability and
maintainability are prioritized<br>
- Sites that benefit from faster load times
through caching

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

Question 43. Explain various CSS font-related properties with example


Answer:

CSS font-related property with examples:


• COLOR: The `color` property in CSS sets the color of the text. It accepts
color names, hexadecimal values etc.
Example:
p {color: 333333;}
In the first example, the paragraph text color is set using a hexadecimal value.
h1 {color: Red;}
In the second example, color name is used for the heading.

• 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.

• FONT-SIZE: Sets the size of the font.


Example:
p {font-size: 16px;}
In the example, the font size is set to 16 pixels.

• FONT-STYLE: Defines the style of the font, such as `normal`, `italic`, or


`oblique`.
Example:
h 1{font-style: italic;}

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.

• FONT-WEIGHT: Specifies the weight (thickness) of the font, which ranges


from `100` (thin) to `900` (bold). Common keywords are `normal`, `bold`,
`bolder`, and `lighter`.
Example:
p {font-weight: bold;}
The `p` elements font is bold.
h 1 {font-weight: 300; / Light font;}
The `h 1` element has a light font weight with a numerical value.

• FONT-VARIANT: Primarily used for small-caps, `font-variant` can display


lowercase text as smaller uppercase letters. The main values are `normal` and
`small-caps`.

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

Question 44. Explain background image and background color property


using CSS
Answer:

The document outlines the background-image and background-color properties as follows:


• BACKGROUND-IMAGE:
− This property sets an image as the background for an element.
− It requires a URL to the image, which can be a relative or absolute path.
− Syntax: background-image: URL("path/to/image.jpg");
Additional options include:
Background image repeat(background-repeat): Specifies whether the background image
should repeat (repeat, no-repeat, repeat-x, repeat-y).

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;

Background-position: 20px 10px;

Background-position: 30% 30%;

Background-position: top center;

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

Question 45. Explain various CSS text-related properties with an example


Answer:

The document outlines various CSS text-related properties, including:


• TEXT-ALIGN: Sets the horizontal alignment of text within an element, with
values like left, right, center, and justify.
Example:
p {text-align: center;}
This centers the text within all <p> elements.
• TEXT-DECORATION: Controls decorative lines on text, such as underline,
overline, line-through, or none.
Example:
a {text-decoration: underline;}
This underlines all <a> (link) elements.
• TEXT-TRANSFORM: Adjusts text capitalization, with values like uppercase,
lowercase, and capitalize.
Example:
h1 {text-transform: uppercase;}
This converts all <h1> text to uppercase.
• TEXT-INDENT: Specifies the indentation of the first line of text.
Example:
p {text-indent: 20px;}
This indents the first line of each <p> by 20 pixels.
• LINE-HEIGHT: Sets the height of each line, improving readability by
adjusting spacing.
Example:
p {line-height: 1.6;}
This increases line spacing for all <p> elements, making text easier to read.

Page | 98
WEB PRORAMMING

• LETTER-SPACING: Adjusts the space between characters, useful for stylistic


effects.
Example:
h2 {letter-spacing: 2px;}
Adds 2 pixels of spacing between each character in <h2> elements.
• WORD-SPACING: Modifies the space between words, which can improve
text flow and readability.
Example:
p {word-spacing: 5px;}
Adds 5 pixels of space between words in <p> elements.
• WHITE SPACE: Allows you to prevent text from wrapping until you place a
break<br/> into your text.
Example:
p {white-space: nowrap;}

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

Question 47. Explain various positioning using CSS.


Answer:

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;}

Position Positioned Relative To Stays in Document Affects Surrounding


Type Flow? Elements?

Relative Original position Yes No (moves only itself)


Absolute Closest positioned No No
ancestor or body
Fixed Viewport No No
Sticky Scroll position relative to Yes (up to sticky Yes (up to sticky point)
viewport point)

Page | 102
WEB PRORAMMING

Question 48. Explain the purpose of JavaScript with its pros and cons
Answer:

JavaScript is a powerful programming language that enables dynamic interactions and


functionality in web applications. Its primarily used in web development to enhance user
interfaces, validate user inputs, create animations, and interact with back-end servers, making
web pages interactive and responsive.
• Pros of JavaScript
− Interactivity: JavaScript allows developers to add interactive features like sliders, pop-
ups, form validations, and animations.
− Client-Side Execution: Since JavaScript runs in the browser, it reduces server load
and can improve performance.
− Versatility: JavaScript can be used on both the client-side and server-side (with
frameworks like Node.js), making it a full-stack language.
− Rich Ecosystem: JavaScript has numerous frameworks and libraries, like React,
Angular, and Vue, which simplify complex development tasks.
− Community Support: With a large community, there are abundant resources, libraries,
and tools to help with development.
• Cons of JavaScript
− Security Risks: JavaScript is susceptible to security issues like cross-site scripting
(XSS) because it runs on the client side.
− Browser Compatibility: Different browsers may interpret JavaScript code differently,
requiring additional testing for cross-browser compatibility.
− Debugging Complexity: Due to its loosely-typed nature, JavaScript can be
challenging to debug, especially for larger applications.
− Performance Issues: JavaScript can slow down if not optimized, especially when
handling large computations on the client side.

Page | 103
WEB PRORAMMING

49. Compare between Client-side scripting language and Server side


scripting language
Answer:

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:

Client-side scripting Server-side scripting

Source code is not visible to the user because its


Source code is visible to the user. output of server-side side is an HTML page.

Its primary function is to manipulate and provide


Its main function is to provide the
access to the respective database as per the
requested output to the end user.
request.

In this any server-side technology can be used


It usually depends on the browser and and it does not
its version. depend on the client.

Page | 104
WEB PRORAMMING

Client-side scripting Server-side scripting

It runs on the user’s computer. It runs on the webserver.

There are many advantages linked


The primary advantage is its ability to highly
with this like faster.
customize, response
response times, a more interactive
requirements, access rights based on user.
application.

It does not provide security for data. It provides more security for data.

It is a technique used in web It is a technique that uses scripts on the


development in which scripts run on webserver to produce a response that is
the client’s browser. customized for each client’s request.

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.

It reduces load on processing unit of


It surges the processing load on the server.
the server.

Page | 105
WEB PRORAMMING

Question 50. Explain how to declare variables in JavaScript.


Answer:

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

Question 51. Compare let vs var vs const.


Answer:

Feature var let const


Function-scoped Block-scoped Block-scoped
Scope
Reassignment Allowed Allowed Not allowed

Hoisting Hoisted to the Hoisted but Hoisted but


top of scope not initialized
not initialized
Use Case Global or Local use within Values that
function-wide use a block
should not change

Page | 109
WEB PRORAMMING

Question 52. What is an identifier in JavaScript? explain various rules for


identifiers in JavaScript
Answer:

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:

Names can contain letters, digits, underscores, and dollar signs.


Names must begin with a letter.
Names can also begin with $ and _
Identifiers are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as names.
It cannot contain punctuation, space or start with a digit

Page | 110
WEB PRORAMMING

Question 53. Explain Parselnt and ParseFloat method with suitable


example.
Answer:

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);

• string: The string to be parsed as an integer.


• radix: An optional integer between 2 and 36 that represents the base of the
numeral system to be used.

Example:

let num1 = parseInt("10"); // Base 10 (decimal)


let num2 = parseInt("10.5"); // Result: 10 (decimal part is ignored)
let num3 = parseInt("101", 2); // Base 2 (binary) - Result: 5
let num5 = parseInt("Hello"); // Result: NaN (not a number)

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

The parseFloat function converts a string to a floating-point number (decimal). Unlike


parseInt, parseFloat will parse the string until it reaches a non-numeric character, allowing for
decimal points.
Syntax: parseFloat(string);
Example:
let float1 = parseFloat("10.5"); // Result: 10.5
let float3 = parseFloat("Hello"); // Result: NaN (not a number)
let float4 = parseFloat(" 15.75"); // Result: 15.75 (leading whitespace is ignored)
Important Points:
Like parseInt, if the string cannot be converted into a floating-point number,
parseFloat returns NaN.
Leading whitespace is ignored, and trailing non-numeric characters will stop parsing
at the first non-numeric character.
parseFloat is useful for extracting decimal values from strings, such as user input or
formatted numbers.

Page | 112
WEB PRORAMMING

Eg:

Page | 113
WEB PRORAMMING

Question 54. Explain Arithmetic Operators in JavaScript with suitable


example.
Answer:

Arithmetic operators in JavaScript are used to perform mathematical calculations on


numbers. The primary arithmetic operators include addition, subtraction, multiplication,
division, modulus, increment, and decrement.

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:

• Prefix (++x): Increments the value and then returns it.


• Postfix (x++): Returns the value and then increments it.

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

Question 55. Explain comparison Operators in JavaScript with suitable


example.
Answer:

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

2. Not Equal to (!=)


The inequality operator (!=) checks if two values are not equal, performing type coercion if
necessary.

Example:
Let a =10
Let b= 20
document.write("(a!= b) => ");
result = (a != b);
document.write(result); // Output : (a != b) => true

4. Greater Than (>)


The greater than operator checks if the value on the left is greater than the value on the right.
Example:

Page | 116
WEB PRORAMMING

Let a =10
Let b= 20
document.write("(a > b) => ");
result = (a > b);
document.write(result); // Output : (a > b) => false

6. Greater Than or Equal To (>=)

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

7. Less Than (<)


The less than operator checks if the value on the left is less than 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) => true

8. Less Than or Equal To (<=)


The less than or equal to operator checks if the value on the left is less than or equal to the
value on the right.
Example:

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

Question 56. Explain Logical Operators in JavaScript with suitable


example.
Answer:

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)

3. Logical NOT (!)


The logical NOT operator negates the Boolean value of its operand. If the operand is true, it
returns false, and vice versa.

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)

Combining Logical Operators


Logical operators can be combined to create complex conditional expressions.

Page | 120
WEB PRORAMMING

Question 57. Explain Assignment Operators in JavaScript with suitable


example.
Answer:

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.

1. Basic Assignment (=)


The basic assignment operator assigns the value on the right to the variable on the left.

Example:
let x = 10; // Assigns 10 to x
document.write(x); // Output: 10

2. Addition Assignment (+=)


The addition assignment operator adds the right operand to the left operand and assigns the
result to the left operand.
Example:
let y = 5;
y += 3; // Equivalent to y = y + 3
document.write(y); // Output: 8

3. Subtraction Assignment (-=)


The subtraction assignment operator subtracts the right operand from the left operand and
assigns the result to the left operand.

Example:

let z = 10;
z -= 4; // Equivalent to z = z - 4
document.write(z); // Output: 6

Page | 121
WEB PRORAMMING

4. Multiplication Assignment (*=)


The multiplication assignment operator multiplies the left operand by the right operand and
assigns the result to the left operand.
Example:
let a = 3;
a *= 4; // Equivalent to a = a * 4
document.write(a); // Output: 12

5. Division Assignment (/=)


The division assignment operator divides the left operand by the right operand and assigns
the result to the left operand.
Example:
let b = 20;
b /= 5; // Equivalent to b = b / 5
document.write(b); // Output: 4

6. Modulus Assignment (%=)


The modulus assignment operator calculates the remainder of dividing the left operand by the
right operand and assigns the result to the left operand.
Example:
let c = 10;
c %= 3; // Equivalent to c = c % 3
document.write(c); // Output: 1

Page | 122
WEB PRORAMMING

Question 58. Explain conditional (ternary) operator in JavaScript?


Answer:

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 />";

document.write("((a > b) ? 100 : 200) => ");


let result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);

//-->
Page | 123
WEB PRORAMMING

</script>
</body>
</html>

Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100

Page | 124
WEB PRORAMMING

Question 59. Explain Conditional statements in JavaScript with suitable


example.
Answer:

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

This structure allows for multiple conditions to be evaluated in sequence.


Syntax
if (expression 1){
Statement(s) to be executed if expression 1 is true
}else if (expression 2){
Statement(s) to be executed if expression 2 is true
}else if (expression 3){
Statement(s) to be executed if expression 3 is true
}else{
Statement(s) to be executed if no expression is true
}
Example:
let score = 85;
if (score >= 90) {
document.write("Grade: A");
} else if (score >= 80) {
document.write("Grade: B"); // This will execute
} else if (score >= 70) {
document.write("Grade: C");
} else {
document.write("Grade: D");
}

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

Question 60. Explain while loop in JavaScript.


Answer:

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

Question 61. Explain do while loop with suitable example in javascript.


Answer:

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

Question 62. Explain for loop with a suitable example in JavaScript.


Answer:

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.

The `for` loop structure consists of three main parts:


1. Initialization: Sets a starting point for the loop.
2. Condition: Evaluates whether the loop should continue. If `true`, the loop executes; if
`false`, it stops.
3. Iteration: Updates the loop control variable after each iteration.

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

Question 63. Explain for...in loop with a suitable example in JavaScript.


Answer:

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

65. Explain the working of user-defined functions in JavaScript.


Answer:

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

Question 66. Explain built-in string functions in JavaScript.


Answer:

JavaScript provides several built-in string functions:

1. length: Returns the length of a string.


javascript
let str = "Hello";
console.log(str.length); // 5

2. toUpperCase(): Converts a string to uppercase.


javascript
console.log(str.toUpperCase()); // "HELLO"

3. toLowerCase(): Converts a string to lowercase.


javascript
console.log(str.toLowerCase()); // "hello"

4. charAt(index): Returns the character at the specified index.


javascript
console.log(str.charAt(0)); // "H"

5. substring(start, end): Returns a part of the string.


javascript
console.log(str.substring(1, 4)); // "ell"

Page | 136
WEB PRORAMMING

Question 67. Explain built-in math functions in JavaScript.


Answer:

JavaScript provides a Math object with several built-in math functions:

1. Math.abs(x): Returns the absolute value of x.


javascript
console.log(Math.abs(-5)); // 5

2. Math.sqrt(x): Returns the square root of x.


javascript
console.log(Math.sqrt(16)); // 4

3. Math.pow(base, exponent): Returns the base raised to the exponent.


javascript
console.log(Math.pow(2, 3)); // 8

4. Math.random(): Returns a random number between 0 and 1.


javascript
console.log(Math.random());

5. Math.round(x): Rounds x to the nearest integer.


javascript
console.log(Math.round(4.6)); // 5

Page | 137
WEB PRORAMMING

Question 68. Explain built-in date functions in JavaScript.


Answer-

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);

2. getFullYear(): Returns the year (4 digits).


javascript
console.log(now.getFullYear()); // e.g., 2024

3. getMonth(): Returns the month (0-11).


javascript
console.log(now.getMonth()); // e.g., 10 for November

4. getDate(): Returns the day of the month (1-31).


javascript
console.log(now.getDate()); // e.g., 1

5. getHours(): Returns the hour (0-23).


javascript
console.log(now.getHours()); // e.g., 14 for 2 PM

Page | 138
WEB PRORAMMING

Question 69. Explain built-in array functions in JavaScript.


Answer:

JavaScript provides several built-in array functions:

1. push(element): Adds one or more elements to the end of an array.


javascript
let arr = [1, 2, 3];
arr.push(4); // arr becomes [1, 2, 3, 4]

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]

4. unshift(element): Adds one or more elements to the beginning of an array.


javascript
arr.unshift(0); // arr becomes [0, 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

Question 70. What is an Event? Explain various types of events like


onclick, onkeyup, onblur, etc.
Answer:

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!");
};

2. onkeyup: Triggered when a key is released.


javascript
input.onkeyup = function() {
console.log("Key released: " + this.value);
};

3. onblur: Triggered when an element loses focus.


javascript
input.onblur = function() {
console.log("Input lost focus");
};

4. onchange: Triggered when the value of an input changes.


javascript

Page | 140
WEB PRORAMMING

input.onchange = function() {
console.log("Value changed to: " + this.value);
};

5. onsubmit: Triggered when a form is submitted.


javascript
form.onsubmit = function() {
alert("Form submitted!");
return false; // Prevents form submission for demonstration
};

Page | 141
WEB PRORAMMING

Question 71. Explain the working of user-defined functions in PHP.


Answer:

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

Question 72. Explain the built-in string functions in PHP.


Answer-

PHP provides several built-in string functions:

1. strlen($string): Returns the length of a string.


php
echo strlen("Hello"); // 5

2. strtoupper($string): Converts a string to uppercase.


php
echo strtoupper("hello"); // "HELLO"

3. strtolower($string): Converts a string to lowercase.


php
echo strtolower("HELLO"); // "hello"

4. substr($string, $start, $length): Returns a substring.


php
echo substr("Hello", 1, 3); // "ell"

5. strpos($haystack, $needle): Finds the position of the first occurrence of a substring.


php
echo strpos("Hello", "e"); // 1

Page | 143
WEB PRORAMMING

Question 73. Explain the built-in math functions in PHP.


Answer:

PHP provides several built-in math functions:

1. abs($value): Returns the absolute value.


php
echo abs(-5); // 5

2. sqrt($value): Returns the square root.


php
echo sqrt(16); // 4

3. pow($base, $exponent): Returns the base raised to the exponent.


php
echo pow(2, 3); // 8

4. rand($min, $max): Generates a random number.


php
echo rand(1, 10); // Random number between 1 and 10

5. round($value): Rounds a float to the nearest integer.


php
echo round(4.6); // 5

Page | 144
WEB PRORAMMING

Question 74. Explain The Built-In Date Function In PHP.


Answer:

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:

date(string $format, int $timestamp = time())

$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

Format Description Example

A am' or 'pm' lowercase pm

A 'AM' or 'PM' uppercase PM

D Day of month, a number with leading zeroes 20

D Day of week (three letters) Thu

F Month name January

H Hour (12-hour format - leading zeroes) 12

H Hour (24-hour format - leading zeroes) 22

G Hour (12-hour format - no leading zeroes) 12

G Hour (24-hour format - no leading zeroes) 22

I Minutes ( 0 - 59 ) 23

J Day of the month (no leading zeroes 20

l (Lower 'L') Day of the week Thursday

L Leap year ('1' for yes, '0' for no) 1

M Month of year (number - leading zeroes) 1

M Month of year (three letters) Jan

Page | 145
WEB PRORAMMING

R The RFC 2822 formatted date Thu, 21 Dec 2000


16:01:07 +0200

N Month of year (number - no leading zeroes) 2

S Seconds of hour 20

U Time stamp 948372444

Y Year (two digits) 06

Y Year (four digits) 2006

Z Day of year (0 - 365) 206

Z Offset in seconds from GMT +5

Example

Try out the following example.

<?php

print date("m/d/y G.i:s<br>", time());

print "Today is ";

print date("j of F Y, \a\\t g.i a", time());

It will produce following result:

07/19:16 11:15:06 Today is 19 2016f July 2016 at 11:15 am

Page | 146
WEB PRORAMMING

Question 75. Explain The Built-In Array Function In PHP.


Answer:

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

/* First method to create array. */

$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value )

echo "Value is $value <br />";

/* Second method to create array. */

$numbers[0] = "one";

$numbers[1] = "two";

$numbers[2] = "three";

Page | 147
WEB PRORAMMING

$numbers[3] = "four";

$numbers[4] = "five";

foreach( $numbers as $value )

echo "Value is $value <br />";

?>

</body>

</html>

This will produce the following result:

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

/* First method to associate create array. */

$salaries = array(

"mohammad" => 2000,

"qadir" => 1000,

"zara" => 500

);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";

echo "Salary of qadir is ". $salaries['qadir']. "<br />";

echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */

$salaries['mohammad'] = "high";

$salaries['qadir'] = "medium";

$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";

echo "Salary of qadir is ". $salaries['qadir']. "<br />";

echo "Salary of zara is ". $salaries['zara']. "<br />";

?>

</body>

</html>

This will produce the following result:

Salary of mohammad is 2000

Salary of qadir is 1000

Salary of zara is 500

Page | 149
WEB PRORAMMING

Salary of mohammad is high

Salary of qadir is medium

Salary of zara is low

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(

"mohammad" => array

"physics" => 35,

"maths" => 30,

"chemistry" => 39

),

"qadir" => array

"physics" => 30,

"maths" => 32,

"chemistry" => 29

),

"zara" => array

Page | 150
WEB PRORAMMING

"physics" => 31,

"maths" => 22,

"chemistry" => 39

);

/* Accessing multi-dimensional array values */

echo "Marks for mohammad in physics : " ;

echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";

echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;

echo $marks['zara']['chemistry'] . "<br />";

?>

</body>

</html>

This will produce the following result:

Marks for mohammad in physics : 35

Marks for qadir in maths : 32

Marks for zara in chemistry : 39

Page | 151
WEB PRORAMMING

Question 76. Explain Various Looping Structures In Php With Example.


Answer:

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.

• for - loops through a block of code a specified number of times.

• 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.

• foreach - loops through a block of code for each element in an array.

The for loop statement


The for statement is used when you know how many times you want to execute a statement or a
block of statements.

Syntax

for (initialization; condition; increment)

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;

for( $i=0; $i<5; $i++ )

$a += 10;

$b += 5;

echo ("At the end of the loop a=$a and b=$b" );

?>

</body>

</html>

This will produce the following result:

At the end of the loop a=50 and b=25

The while loop statement


The while statement will execute a block of code if and as long as a test expression is true. If the test
expression is true, then the code block will be executed. After the code has executed the test
expression will again be evaluated and the loop will continue until the test expression is found to be
false.

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;

while( $i < 10)

$num--;

$i++;

echo ("Loop stopped at i = $i and num = $num" );

?>

</body>

</html>

This will produce the following result:

Loop stopped at i = 10 and num = 40

The do...while loop statement


The do...while statement will execute a block of code at least once - it will then repeat the loop as
long as a condition is true.

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 );

echo ("Loop stopped at i = $i" );

?>

</body>

</html>

This will produce the following result:

Loop stopped at i = 10

The foreach loop statement


The foreach statement is used to loop through arrays. For each pass the value of the current array
element is assigned to $value and the array pointer is moved by one and in the next pass next
element will be processed.

Syntax

foreach (array as value)

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

$array = array( 1, 2, 3, 4, 5);

foreach( $array as $value )

echo "Value is $value <br />";

?>

</body>

</html>

This will produce the following result:

Value is 1

Value is 2

Value is 3

Value is 4

Value is 5

The break statement


The PHP break keyword is used to terminate the execution of a loop prematurely.

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;

while( $i < 10)

$i++;

if( $i == 3 )break;

Page | 157
WEB PRORAMMING

echo ("Loop stopped at i = $i" );

?>

</body>

</html>

This will produce the following result:

Loop stopped at i = 3

The continue statement


The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate
the loop.

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

$array = array( 1, 2, 3, 4, 5);

Page | 158
WEB PRORAMMING

foreach( $array as $value )

if( $value == 3 )continue;

echo "Value is $value <br />";

?>

</body>

</html>

This will produce the following result:

Value is 1

Value is 2

Value is 4

Value is 5

Page | 159
WEB PRORAMMING

Question 77. Explain Various Conditional Structures In Php With


Example.
Answer:

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.

PHP supports the following three decision making statements:

• 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.

The If...Else Statement


If you want to execute some code if a condition is true and another code if a condition is false, use
the if....else statement.

Syntax

if (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it
will output "Have a nice day!":

<html>

<body>

<?php

$d=date("D");

if ($d=="Fri")

Page | 160
WEB PRORAMMING

echo "Have a nice weekend!";

else

echo "Have a nice day!";

?>

</body>

</html>

It will produce the following result:

Have a nice weekend!

The ElseIf Statement


If you want to execute some code if one of the several conditions is true, then use the elseif
statement.

Syntax

if (condition)

code to be executed if condition is true;

elseif (condition)

code to be executed if condition is true;

else

code to be executed if condition is false;

Example

The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a
nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!":

<html>

<body>

<?php

$d=date("D");

if ($d=="Fri")

echo "Have a nice weekend!";

elseif ($d=="Sun")

Page | 161
WEB PRORAMMING

echo "Have a nice Sunday!";

else

echo "Have a nice day!";

?>

</body>

</html>

It will produce the following result:

Have a nice weekend!

The Switch Statement


If you want to select one of many blocks of code to be executed, use the Switch statement. The
switch statement is used to avoid long blocks of if..elseif..else code.

Syntax

switch (expression)

case label1:

code to be executed if expression = label1;

break;

case label2:

code to be executed if expression = label2;

break;

default:

code to be executed

if expression is different

from both label1 and label2;

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":

echo "Today is Monday";

break;

case "Tue":

echo "Today is Tuesday";

break;

case "Wed":

echo "Today is Wednesday";

break;

case "Thu":

echo "Today is Thursday";

break;

case "Fri":

echo "Today is Friday";

break;

case "Sat":

echo "Today is Saturday";

break;

case "Sun":

echo "Today is Sunday";

break;

default:

echo "Wonder which day is this ?";

Page | 163
WEB PRORAMMING

?>

</body>

</html>

It will produce the following result:

Today is Friday

Page | 164
WEB PRORAMMING

Question 78. Explain various php operators with example?


Answer:

PHP operators are used to perform operations on variables and values.

PHP language supports following type of operators.

• Arithmetic Operators

• Comparison Operators

• Logical (or Relational) Operators

• Assignment Operators

• Conditional (or ternary) Operators

Arithmetic Operators
The following arithmetic operators are supported by PHP language:

Assume variable A holds 10 and variable B holds 20 then:

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;

echo "Addition Operation Result: $c <br/>";

$c = $a - $b;

echo "Subtraction Operation Result: $c <br/>";

$c = $a * $b;

echo "Multiplication Operation Result: $c <br/>";

$c = $a / $b;

echo "Division Operation Result: $c <br/>";

$c = $a % $b;

echo "Modulus Operation Result: $c <br/>";

$c = $a++;

echo "Increment Operation Result: $c <br/>";

$c = $a--;

echo "Decrement Operation Result: $c <br/>";

?>

</body>

</html>

This will produce the following result:

Addition Operation Result: 62

Subtraction Operation Result: 22

Multiplication Operation Result: 840

Division Operation Result: 2.1

Modulus Operation Result: 2

Increment Operation Result: 42

Decrement Operation Result: 43

Page | 166
WEB PRORAMMING

Comparison Operators
There are following comparison operators supported by PHP language.

Assume variable A holds 10 and variable B holds 20 then:

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 ){

echo "TEST1 : a is equal to b<br/>";

}else{

echo "TEST1 : a is not equal to b<br/>";

Page | 167
WEB PRORAMMING

if( $a > $b ){

echo "TEST2 : a is greater than b<br/>";

}else{

echo "TEST2 : a is not greater than b<br/>";

if( $a < $b ){

echo "TEST3 : a is less than b<br/>";

}else{

echo "TEST3 : a is not less than b<br/>";

if( $a != $b ){

echo "TEST4 : a is not equal to b<br/>";

}else{

echo "TEST4 : a is equal to b<br/>";

if( $a >= $b ){

echo "TEST5 : a is either greater than or equal to b<br/>";

}else{

echo "TEST5 : a is neither greater than nor equal to b<br/>";

if( $a <= $b ){

echo "TEST6 : a is either less than or equal to b<br/>";

}else{

echo "TEST6 : a is neither less than nor equal to b<br/>";

?>

</body>

</html>

Page | 168
WEB PRORAMMING

This will produce the following result:

TEST1 : a is not equal to b

TEST2 : a is greater than b

TEST3 : a is not less than b

TEST4 : a is not equal to b

TEST5 : a is either greater than or equal to b

TEST6 : a is neither less than nor equal to b

Logical Operators
The following logical operators are supported by PHP language.

Assume variable A holds 10 and variable B holds 20 then:

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 ){

echo "TEST1 : Both a and b are true<br/>";

}else{

echo "TEST1 : Either a or b is false<br/>";

if( $a and $b ){

echo "TEST2 : Both a and b are true<br/>";

}else{

echo "TEST2 : Either a or b is false<br/>";

if( $a || $b ){

echo "TEST3 : Either a or b is true<br/>";

}else{

echo "TEST3 : Both a and b are false<br/>";

if( $a or $b ){

echo "TEST4 : Either a or b is true<br/>";

}else{

echo "TEST4 : Both a and b are false<br/>";

$a = 10;

Page | 170
WEB PRORAMMING

$b = 20;

if( $a ){

echo "TEST5 : a is true <br/>";

}else{

echo "TEST5 : a is false<br/>";

if( $b ){

echo "TEST6 : b is true <br/>";

}else{

echo "TEST6 : b is false<br/>";

if( !$a ){

echo "TEST7 : a is true <br/>";

}else{

echo "TEST7 : a is false<br/>";

if( !$b ){

echo "TEST8 : b is true <br/>";

}else{

echo "TEST8 : b is false<br/>";

?>

</body>

</html>

This will produce the following result:

TEST1 : Either a or b is false

TEST2 : Either a or b is false

TEST3 : Either a or b is true

TEST4 : Either a or b is true

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:

Operator Description Example

= Simple assignment operator, Assigns values C = A + B will assign the value


from right side operands to left side operand of A + B into C

Add AND assignment operator, It adds right C += A is equivalent to C = C +


operand to the left operand and assign the A
+=
result to left operand

-= Subtract AND assignment operator, It C -= A is equivalent to C = C -


subtracts right operand from the left A
operand and assign the result to left operand

*= Multiply AND assignment operator, It C *= A is equivalent to C = C *


multiplies right operand with the left A
operand and assign the result to left operand

/= Divide AND assignment operator, It divides C /= A is equivalent to C = C /


left operand with the right operand and A
assign the result to left operand

%= Modulus AND assignment operator, It takes C %= A is equivalent to C = C


modulus using two operands and assign the %A
result to left operand

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;

$c = $a + $b; /* Assignment operator */

echo "Addition Operation Result: $c <br/>";

$c += $a; /* c value was 42 + 20 = 62 */

echo "Add AND Assignment Operation Result: $c <br/>";

$c -= $a; /* c value was 42 + 20 + 42 = 104 */

echo "Subtract AND Assignment Operation Result: $c <br/>";

$c = $a; / c value was 104 - 42 = 62 */

echo "Multiply AND Assignment Operation Result: $c <br/>";

$c /= $a; /* c value was 62 * 42 = 2604 */

echo "Division AND Assignment Operation Result: $c <br/>";

$c %= $a; /* c value was 2604/42 = 62*/

echo "Modulus AND Assignment Operation Result: $c <br/>";

?>

</body>

</html>

This will produce the following result:

Addition Operation Result: 62

Add AND Assignment Operation Result: 104

Subtract AND Assignment Operation Result: 62

Multiply AND Assignment Operation Result: 2604

Division AND Assignment Operation Result: 62

Modulus AND Assignment Operation Result: 20

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

Operator Description Example

?: Conditional Expression If Condition is true ? Then


value X : Otherwise value Y

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;

/* If condition is true then assign a to result otherwise b */

$result = ($a > $b ) ? $a :$b;

echo "TEST1 : Value of result is $result<br/>";

/* If condition is true then assign a to result otherwise b */

$result = ($a < $b ) ? $a :$b;

echo "TEST2 : Value of result is $result<br/>";

?>

</body>

</html>

This will produce the following result:

TEST1 : Value of result is 20

TEST2 : Value of result is 10

Page | 174
WEB PRORAMMING

Question 79. Explain The Array In Php With Suitable Example


Answer:

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

/* First method to create array. */

$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value )

echo "Value is $value <br />";

/* Second method to create array. */

$numbers[0] = "one";

$numbers[1] = "two";

Page | 175
WEB PRORAMMING

$numbers[2] = "three";

$numbers[3] = "four";

$numbers[4] = "five";

foreach( $numbers as $value )

echo "Value is $value <br />";

?>

</body>

</html>

This will produce the following result:

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

/* First method to associate create array. */

$salaries = array(

"mohammad" => 2000,

"qadir" => 1000,

"zara" => 500

);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";

echo "Salary of qadir is ". $salaries['qadir']. "<br />";

echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */

$salaries['mohammad'] = "high";

$salaries['qadir'] = "medium";

$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";

echo "Salary of qadir is ". $salaries['qadir']. "<br />";

echo "Salary of zara is ". $salaries['zara']. "<br />";

?>

</body>

</html>

This will produce the following result

Salary of mohammad is 2000

Salary of qadir is 1000

Salary of zara is 500

Salary of mohammad is high

Salary of qadir is medium

Salary of zara is low

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(

"mohammad" => array

"physics" => 35,

"maths" => 30,

"chemistry" => 39

),

"qadir" => array

"physics" => 30,

"maths" => 32,

"chemistry" => 29

),

"zara" => array

"physics" => 31,

"maths" => 22,

"chemistry" => 39

);

/* Accessing multi-dimensional array values */

Page | 178
WEB PRORAMMING

echo "Marks for mohammad in physics : " ;

echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";

echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ;

echo $marks['zara']['chemistry'] . "<br />";

?>

</body>

</html>

This will produce the following result

Marks for mohammad in physics : 35

Marks for qadir in maths : 32

Marks for zara in chemistry : 39

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.

Differences Between GET and POST Methods

Feature GET Method POST 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

Example of GET Method in a Form

The GET method is typically used when sending data that is not sensitive, such as search queries or
filters.

HTML Form Using GET:

<!DOCTYPE html>

<html>

<body>

<h2>Search Form (GET)</h2>

<form action="search.php" method="GET">

<label for="query">Search:</label>

Page | 180
WEB PRORAMMING

<input type="text" id="query" name="query" placeholder="Enter search term">

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

</form>

</body>

</html>

PHP Script to Handle GET Request (search.php):

<?php

if (isset($_GET['query'])) {

$searchQuery = htmlspecialchars($_GET['query']); // Sanitize input

echo "You searched for: " . $searchQuery;

?>

Example of POST Method in a Form

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.

HTML Form Using POST:

<!DOCTYPE html>

<html>

<body>

<h2>Registration Form (POST)</h2>

<form action="register.php" method="POST">

<label for="username">Username:</label>

<input type="text" id="username" name="username" required>

<label for="password">Password:</label>

<input type="password" id="password" name="password" required>

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

Page | 181
WEB PRORAMMING

</form>

</body>

</html>

PHP Script to Handle POST Request (register.php):

<?php

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

$username = htmlspecialchars($_POST['username']); // Sanitize input

$password = htmlspecialchars($_POST['password']); // Sanitize input

echo "Registration successful! Welcome, " . $username;

?>

Page | 182
WEB PRORAMMING

Question 81. Write a PHP function to check if a given string is a palindrome.


Please provide an example of its usage.
Answer:

Here's a PHP function to check if a given string is a palindrome. A palindrome is a word,


phrase, number, or other sequence of characters that reads the same forward and backward
(ignoring spaces, punctuation, and capitalization).

<?php
function isPalindrome($string) {
// Remove whitespace and convert to lowercase
$cleanedString = strtolower(preg_replace("/[^A-Za-z0-9]/", "", $string));

// Reverse the cleaned string


$reversedString = strrev($cleanedString);

// Check if the original cleaned string is equal to the reversed string


return $cleanedString === $reversedString;
}

Explanation

The function isPalindrome takes a string as input.

It removes all non-alphanumeric characters (like spaces, punctuation) and converts the string to
lowercase to ignore case sensitivity.

It then reverses the cleaned string.

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

$testString1 = "A man, a plan, a canal, Panama";

$testString2 = "Hello, World!";

Page | 183
WEB PRORAMMING

if (isPalindrome($testString1)) {

echo "\"$testString1\" is a palindrome.\n";

} else {

echo "\"$testString1\" is not a palindrome.\n";

if (isPalindrome($testString2)) {

echo "\"$testString2\" is a palindrome.\n";

} else {

echo "\"$testString2\" is not a palindrome.\n";

Output

"A man, a plan, a canal, Panama" is a palindrome.

"Hello, World!" is not a palindrome.

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.

Steps to Connect to a MySQL Database Using PHP MySQLi

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

$host = "localhost"; // Server host (usually "localhost")

$username = "root"; // Database username

$password = ""; // Database password

$dbname = "test_db"; // Database name

// Establish connection

$conn = mysqli_connect($host, $username, $password, $dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

} else {

echo "Connected successfully to the database.";

Page | 185
WEB PRORAMMING

// Close the connection

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".

$username is the MySQL username.

$password is the MySQL password for the specified user.

$dbname is the name of the database you want to connect to.

Establishing the Connection:

The mysqli_connect() function takes four parameters: the host, username, password, and database
name.

It attempts to establish a connection to the database. If successful, it returns a connection object;


otherwise, it returns false.

Checking the Connection:

The if (!$conn) condition checks if the connection failed.

If the connection fails, mysqli_connect_error() will return an error message detailing why it failed.

If successful, a "Connected successfully to the database." message is displayed.

Closing the Connection:

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.

Here's a step-by-step guide and code example:

Steps to Create and Select a Database in PHP (MySQLi)

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

// Database connection credentials

$host = "localhost";

$username = "root";

$password = "";

$dbname = "my_new_database";

// Step 1: Establish a connection to the MySQL server

$conn = mysqli_connect($host, $username, $password);

// Check if the connection was successful

if (!$conn) {

Page | 187
WEB PRORAMMING

die("Connection failed: " . mysqli_connect_error());

echo "Connected to MySQL server successfully.<br>";

// Step 2: Create the database if it doesn't already exist

$sql = "CREATE DATABASE IF NOT EXISTS $dbname";

if (mysqli_query($conn, $sql)) {

echo "Database '$dbname' created or already exists.<br>";

} else {

die("Error creating database: " . mysqli_error($conn));

// Step 3: Select the database

if (mysqli_select_db($conn, $dbname)) {

echo "Database '$dbname' selected successfully.";

} else {

die("Error selecting database: " . mysqli_error($conn));

// Close the connection

mysqli_close($conn);

?>

Explanation

Connecting to MySQL Server:

mysqli_connect($host, $username, $password); is used to connect to the MySQL server without


specifying a database.

The if (!$conn) check verifies if the connection is successful. If not, an error message is displayed
using mysqli_connect_error().

Creating the Database:

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_query($conn, $sql) executes this SQL command. If successful, a confirmation message is


displayed. Otherwise, an error message is shown.

Selecting the Database:

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).

Closing the Connection:

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.

Steps to Create a Table and Insert a Record in PHP (MySQLi)


Connect to the Database: Use mysqli_connect() to establish a connection to the MySQL server and
select the database.

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

// Database connection credentials

$host = "localhost";

$username = "root";

$password = "";

$dbname = "my_database";

// Step 1: Establish a connection to the MySQL server

$conn = mysqli_connect($host, $username, $password, $dbname);

// Check if the connection was successful

Page | 190
WEB PRORAMMING

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected to the database successfully.<br>";

// Step 2: Create a table if it doesn't already exist

$tableName = "users";

$sqlCreateTable = "CREATE TABLE IF NOT EXISTS $tableName (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(50) NOT NULL,

email VARCHAR(50) NOT NULL,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

)";

if (mysqli_query($conn, $sqlCreateTable)) {

echo "Table '$tableName' created successfully or already exists.<br>";

} else {

die("Error creating table: " . mysqli_error($conn));

// Step 3: Insert a record into the table

$sqlInsert = "INSERT INTO $tableName (username, email) VALUES ('john_doe',


'[email protected]')";

if (mysqli_query($conn, $sqlInsert)) {

echo "New record inserted successfully.<br>";

} else {

die("Error inserting record: " . mysqli_error($conn));

// Close the connection

Page | 191
WEB PRORAMMING

mysqli_close($conn);

?>

Explanation

Connecting to the Database:

mysqli_connect($host, $username, $password, $dbname); establishes a connection to the database.

The connection is checked with if (!$conn). If it fails, an error message is displayed using
mysqli_connect_error().

Creating the Table:

The CREATE TABLE IF NOT EXISTS SQL statement defines the structure of the table.

In this example, we create a table named users with columns:

id: an auto-incrementing integer as the primary key.

username: a VARCHAR field for the username.

email: a VARCHAR field for the email address.

created_at: a TIMESTAMP field that automatically stores the creation timestamp.

mysqli_query($conn, $sqlCreateTable) executes this SQL statement. If successful, a confirmation


message is displayed; otherwise, an error message is shown.

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.

Closing the Connection:

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.

Steps to Show a Record Using PHP (MySQLi)

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.

Close the Connection: Once done, close the database connection.

Code Snippet
The following code connects to a MySQL database, retrieves a record from a table, and displays it.

<?php

// Database connection credentials

$host = "localhost";

$username = "root";

$password = "";

$dbname = "my_database";

$tableName = "users"; // Name of the table to retrieve data from

// Step 1: Establish a connection to the MySQL server

$conn = mysqli_connect($host, $username, $password, $dbname);

Page | 193
WEB PRORAMMING

// Check if the connection was successful

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected to the database successfully.<br>";

// Step 2: Run a SELECT query to get records from the table

$sql = "SELECT id, username, email, created_at FROM $tableName LIMIT 1"; // Fetches the first
record

$result = mysqli_query($conn, $sql);

// Step 3: Fetch the row

if ($result) {

// Check if any rows were returned

if (mysqli_num_rows($result) > 0) {

$row = mysqli_fetch_row($result); // Fetches the first row as a numeric array

echo "Record fetched successfully:<br>";

echo "ID: " . $row[0] . "<br>";

echo "Username: " . $row[1] . "<br>";

echo "Email: " . $row[2] . "<br>";

echo "Created At: " . $row[3] . "<br>";

} else {

echo "No records found in the table.";

} else {

echo "Error in query: " . mysqli_error($conn);

// Close the connection

mysqli_close($conn);

?>

Page | 194
WEB PRORAMMING

Explanation

Connecting to the Database:

mysqli_connect($host, $username, $password, $dbname); connects to the database.

The connection is verified with if (!$conn). If the connection fails, it displays an error using
mysqli_connect_error().

Running a SELECT Query:

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.

mysqli_query($conn, $sql) runs the query and stores the result.

Fetching the Row:

mysqli_fetch_row($result); fetches the first row of the result as a numeric array.

$row[0], $row[1], $row[2], and $row[3] correspond to the id, username, email, and created_at fields,
respectively.

Checking and Displaying the Data:

If the query returns at least one row, it displays the record’s data.

If no rows are returned, it outputs a message saying "No records found.

Closing the Connection:

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

You might also like