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

Web Programming Chapter 4

Web programming or WP

Uploaded by

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

Web Programming Chapter 4

Web programming or WP

Uploaded by

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

Web Programming

Model Paper- 4
Section-A
I. Answer any four question. Each question carries two marks: (4 X 2 = 8)

1. What is the difference between WWW and Internet.


• The Internet is the large container, and the Web is a part within the container. The Internet is like
restaurant, and the Web is the most popular dish on the menu .
• WWW depends on Internet. But internet is an independent of WWW.
• The Internet can be thought of as the hardware infrastructure that enables communication and
information exchange between devices. On the other hand, the World Wide Web (WWW) is a
software application that runs on top of the Internet infrastructure and provides a user- friendly
interface for accessing and sharing information. Without the hardware infrastructure of the Internet,
the software application of the WWW would not be able to function.
• The Web is just one of the ways that information can be transmitted over the Internet. It's a powerful
platform for accessing and sharing information using web pages and hyperlinks, but it's not the only
way we use the Internet.

2.What is Navigator Object ?


The navigator object is a built-in object in JavaScript that provides information about the web
browser and the system on which it is running. It contains properties such as appCodeName, appName,
appVersion, mimeTypes, platform, and userAgent, which can be used to determine the browser's name,
version, supported MIME types, operating system, and other details.

3.What is XSLT style sheet ?


XSLT is an xml based language for transforming XML documents into other XML or HTML
documents. XSLT stands for extensible Styles Language Transformations. It is the most important part of
XSL (Extensible Stylesheet Language).

4. What is window.alert() ?
Window.alert() is a method used to display an alert box with the specified message.
Example : window.alert("Hello, World!");

5. Explain the types of comments in PHP.


Comments in PHP are used to add notes or explanations to the code that are not executed by the
PHP engine. They are used to make the code more readable and understandable for other developers
who may work on the code in the future. Comments can be added in two ways in PHP:
• 1. Single-line Comments: Single-line comments start with '//' and continue until the end of the line.
They are used to add comments to a single line of code.
Example : Single Line Comments
<?php
// This is a single-line comment
$x = 5; // This is another single-line comment
?>

• 2. Multi-line Comments: Multi-line comments start with '/' and end with */'. They are used to add
comments to multiple lines of code.
Example : Multiline Comments
<?php
/*This is a multi-line comment
that spans multiple lines of code
$x = 5;
/* This is another multi-line comment */
?>

6.How to merge two arrays in php? Give an example.


By using array_merge(): Merges two or more arrays. Ideal for combining arrays into a single array.
Example :
$arr1 = [1, 2];
$arr2 = ["a", "b"];
$merged = array_merge($arr1, $arr2);
print_r($merged);
Output: Array ( [0] => 1 [1] => 2 [2] => a [3] => b )

Section-B
II. Answer any four question. Each question carries five marks: (4 X 5 = 20)

7. How to add Dynamic Content to the HTML? Explain with an example.


Dynamic Content in web development refers to the ability to change the content of HTML on a web page
dynamically using JavaScript. This can involve updating text, images, or other content in response to user
interactions, data changes, or other events without requiring reload.
The concept of dynamic content is important as it allows web developers to create more user and
Responsive user interfaces. By updating content dynamically, web pages can provide real feedback,
display live data, and adapt to user input, resulting in a more engaging and personalize user experience.
Examples of Dynamic Content Include:
1. Real-time Updates: Displaying live data such as stock prices, weather information, or social media feeds
without requiring the user to manually refresh the page.
2. Interactive Forms: Validating user input, providing instant feedback, and dynamically updating form
elements based on user actions.
3. Content Loading: Loading additional content, such as comments or product listings, as the user scrolls
down a page to create a seamless browsing experience.
4. Dynamic Visualizations: Updating charts, graphs, or maps in response to user interactions or data
changes.
Example :
<IDOCTYPE html>
<html>
<head>
<title>Dynamic Content</title>
<script type="text/javascript">
var messages = [
"The first name should be followed by second name.",
"Address should end with a PIN code.",
"Enter valid EMAIL ID."
];

function helpMessage(msgNo) {
document.getElementById('helperText').value = messages[msgNo];
}
</script>
</head>
<body>
<form>
<label>Enter Your Name: </label>
<input type="text" size="40" onfocus="helpMessage(0)"><br><br>
<label>Enter Address : </label>
<input type="text" size="40" onfocus="helpMessage(1)"><br><br>
<label>Enter Email : </label>
<input type="text" size="40" onfocus="helpMessage(2)"><br><br>
<label>Help Box : </label>
<input type="text" id="helperText" size="40"><br><br>
</form>
</body>
</html>

8.Explain Handling Events from Button Elements with an example .


Buttons in a Web document provide an effective way to collect simple input from the browser user. The
most commonly used event created by button actions is click.
The event handler is registered by assigning its call to the onclick attribute of the radio buttons
Example :
An example to demonstrate handling events from radio button elements for selecting a particular age
group from 4 different options.
<!DOCTYPE html>
<!-radioclick1.html
A document for radioclick1.js
---- >
<html>
<head>
<title> HANDLING EVENTS FROM BUTTON ELEMENTS EXAMPLE</title>
<script type="text/javascript" src="radioclick1.js">
</script>
</head>
<body>
<h3> AGE GROUP DESCRIPTIONS</h3>
<form id="myForm" action="">
<p>
<label> <input type="radio" name="ageButton" value="1" onclick="ageChoice(1)" />11-20</label>
<label><input type="radio" name="ageButton" value="2" onclick="ageChoice (2)" />21-30</label>
<label><input type="radio" name="ageButton" value="3" onclick="ageChoice (3)" />31-40</label>
<label><input type="radio" name="ageButton" value="4" onclick="ageChoice (4)" />41-50</label>
</p>
</form>
</body>
</html>

9.What are Web Services? How Webservices Work ?


Web services are XML-based information exchange systems that use the Internet for direct application-to-
application interaction. These systems can include programs, objects, messages, or documents.

The following steps outline the general process of how web services work :
1. Service Publication: A provider publishes the description of the web service, including its Interface,
operations, and data formats, using a standardized format such as WSDL (Web Services Description
Language). This description is made available to potential service consumers.
2. Service Discovery: Potential consumers can discover and identify available web services through
service registries or directories, such as UDDI (Universal Description, Discovery, and Integration).
which provide information about the location and capabilities of web services.
3. Service Invocation: A consumer (client) of the web service initiates a request by sending a message to
the service endpoint. The request is typically formatted as an XML-based SOAP (Simple Object
Access Protocol) message, which includes the details of the operation to be performed and any
necessary input parameters.
4. Message Transmission: The SOAP message is transmitted over a network using standard
communication protocols, such as HTTP or HTTPS. This allows the message to reach the web service
provider's endpoint.
5. Service Processing: Upon receiving the request, the web service provider processes the incoming
message, performs the requested operation, and generates a response. The processing may involve
accessing data, executing business logic, or interacting with other systems.
6. Response Generation: The web service provider constructs a response message, typically in the form
of another SOAP message, containing the results of the requested operation or any relevant data.
7. Message Transmission: The response message is transmitted back to the consumer over the network,
following the same communication protocols used for the request.
8. Response Handling: The consumer receives the response message and processes the returned data or
results as needed for its own application logic.

10.Explain Variable Scope in PHP. Discuss the types of Variable Scope with examples.
Variable Scope in PHP refers to the part of a program where a variable can be accessed or referenced.
Understanding variable scope is crucial for effective programming. Variable scope determines the
accessibility or visibility of a variable within different parts of a PHP script. There are four main types of
variable scope in PHP: local, global, static, and superglobal.
1.Local Variables and local scope:
• Local Variables: Local variables in PHP are declared inside a function and can only be accessed
within that function. They are temporary and exist only for the duration of the function's
execution. Once the function ends, the local variable is destroyed, and its value is no longer
accessible.
• Local Scope: They are not the local scope can only be accessed within the function where they are
declared. They are not known outside of their function's scope, meanfunweawore they them from
outside the function in which they are declared.
Example
function testFunction() {
$localvar "I'm local"; // Local to testFunction
echo $localvar;
}
testFunction(); // Outputs: I'm local
// Outside the function
echo $localVar; // Error: Undefined variable: localvar

2.Global Variables and Global scope


• Global Variables: Global variables in PHP are variables that are declared outside of a function or
class and can be accessed from anywhere in the program, including inside functions and classes. To
access a global variable inside a function, the 'global' keyword followed by the variable name is used.
• Global Scope: Variables with global scope can be accessed from anywhere in the program, including
inside functions and classes.
Example
$globalvar "I'm global"; // Global variable
function testGlobal() {
// Declare Sglobalvar as global within the function
global $globalvar; echo $globalvar;
// Accessible here due to the global declaration
testGlobal(); // Outputs: I'm global
echo $globalVar;

3.Static Variable and static scope


• Static Variables: Static variables in PHP are local variables that retain their value between function
calls. They are declared using the 'static' keyword inside a function and can only be accessed within
that function.
• Static Scope: Static variables maintain their state between function calls. The scope is local to the
function, but they do not lose their value when the function execution is completed.
Example
function countCalls() {
static $count = 0; // Static variable
$count++;
echo "This function has been called “ .$count.”.times.’;
}
countCalls(); // Outputs: This function has been called 1 times.
countCalls(); // Outputs: This function has been called 2 times.
countCalls(); // Outputs: This function has been called 3 times.
echo $count;

11.Discuss the use of default arguments in functions with examples.


In PHP, the default arguments are values that are assigned to function parameters if no value is provided
when the function is called. This allows for more flexible and customizable functions, as well as
simplifying function calls by providing default values for optional parameters.
Default arguments can be very useful in situations where the function has optional parameters or when
we want to provide a default value for a parameter. They can simplify function calls and make code more
fexible and customizable.
When the function is called, if an argument is provided for a parameter, it will override the default value.
If no argument is provided, the default value will be used.
Syntax : Default Arguments
function functionName($arg1 = defaultValuel, $arg2= defaultValue2, ...) {
// Function body
}
function Name: It is the name of the function.
Arguments: Sarg1, Sarg2, etc. are the arguments (if any) passed to the function.
Default Values: defaultValue1, defaultValue2, etc. are the default values assigned to the arguments.

Example: Default Arguments

<?php
function display($fontSize ="medium", $theme = "light") {
return "Font Size: $fontSize, Theme: $theme";
}
echo display()."<br>";
echo display("large")."<br>";
echo display("large", "dark")."<br>";

Output:
Font Size: medium, Theme: light
Font Size: large, Theme: light
Font Size: large, Theme: dark

12.Describe the format specifiers used in the date() function in PHP.

Format Description Returned Value Example


d Day of month, two 01 to 31 echo date(“Y-m-d");
digits, with zero Outputs : 2023-03-05
(for March 5th 2023)
D Day of week, Mon to Sun echo date(“Y-m-d D");
Three letters Outputs : 2023-03-05 Sun
(for Sunday, March 5th 2023)
j Day of month, no 1 to 31 echo date(“Y-m-j");
leading zero Outputs : 2023-03-5
(for March 5th 2023)
l Day of week, full Sunday to Saturday echo date(“1,Y-m-d");
names Outputs : Sunday,2023-03-05
N Day of week, 1 to 7 echo date(“Y-m-d N");
numeric, Mon to Outputs : 2023-03-05 7
Sun (for Sunday)
S Suffix for day of st,nd,rd,th echo date(“Y-m-dS");
month Outputs : 2023-03-05th
w Day of week, 0 to 6 echo date(“Y-m-d w");
numeric, Sun to Outputs : 2023-03-05 0
Sat (for Sunday)
z Day of year 0 to 365 echo date(“Y-m-d z");
Outputs : 2023-03-05 63
(63rd day of the year)
W Week number of 01 to 52 echo date(“Y-W");
year Outputs : 2023-09
(for the 9th week of the year)

F Month name January to December echo date(“F Y");


Outputs : March 2023
m Month number 01 to 12 echo date(“Y-m");
with zero Outputs : 2023-03
M Month name, Jan to Dec echo date(“F Y");
three letters Outputs : March 2023
n Month number, 1 to 12 echo date(“Y-n");
no zero Outputs : 2023-3
t Number of days 28 to 31 echo date(“Y-m-t");
in given month Outputs : 2023-03-31
(for March 2023)
L Leap year 1 = Yes echo date(“Y L");
0 = No Outputs : 2023 0
(0 indicates non-leap year)
y Year, 2 digits 00 to 99 echo date(“y-m-d");
Outputs : 23-03-05
Y Year, 4 digits 0000 to 9999 echo date(“Y-m-d");
Outputs : 2023-03-05
a AM/PM am or pm echo date(“h:i:s a");
lowercase Outputs : 03:15:30 pm
A AM/PM AM or PM echo date(“h:i:s A");
uppercase Outputs : 03:15:30 PM
g Hour, 12 Hour 1 to 12 echo date(“g:i:s A");
Format, no zeros Outputs : 03:15:30 pm
G Hour, 24 Hour 0 to 23 echo date(“G:i:s");
Format, no zeros Outputs : 15:15:30
h Hour, 12 Hour 01 to 12 echo date(“h:i:s A");
Format, with Outputs : 03:15:30 PM
zeros
H Hour, 24 Hour 00 to 23 echo date(“H:i:s A");
Format, with Outputs : 15:15:30 PM
zeros

i Minutes with 00 to 59 echo date(“Y-m-d H:i “);


zeros Outputs : 2023-03-05 15:08
(for 3:08)
s Seconds with 00 to 59 echo date(“Y-m-d H:i:s “);
zeros Outputs : 2023-03-05 15:08:09
(for 3:08 PM and 9 seconds)

Section-C
III. Answer any four question. Each question carries eight marks: (4 X 8 = 32)

13.Explain Handling Events from Text box and Password Elements with an example.
Focus and Blur Events :
The focus and blur events are JavaScript events that are associated with text box and
password input elements.
1. The onfocus event is triggered when an element receives focus, such as when the user
clicks on it or tabs into it using the keyboard.
2. The onblur event is triggered when an element loses focus, such as when the user
clicks on another element or tabs out of the current element.
• These events can be used in web development to perform actions in response to user
input, such as validating user input or updating the user interface

Program :Textbox and Password validations using onfocus and onblur

<!DOCTYPE html>
<html>
<title>Focus and Blur Event</title>
<script type="text/javascript">
<head>
function checkUserName() {
var username = document.getElementById("nameText").value;
var message = '';
if (username.length < 8) {
message "User name cannot be less than 8 characters";
}
document.getElementById("usernameMessage").innerText message;
}
function displayPwdRules() {
var message = '';
message = "Password must be minimum 6 characters";
document.getElementById("passwordMessage").innerText = message;
}
</script>
</head>
<body>
<form>
<input type="text" id="nameText" onblur="checkUserName()"/>
<span id="usernameMessage" style="color:red;"></span><br/><br/>
<input type="password" id="pwdText" onfocus="displayPwdRules()">
<span id="passwordMessage" style="color: blue;"></span>
</form>
</body>
</html>

Onselect Event :
The onselect event is a JavaScript event that is triggered when the user selects text in an
input element, such as a text box or a text area. This event can be used to perform
actions in response to user input, such as updating the user interface or validating user
input.

Example :
Let us create one text box called age. It display the default value in the text box Select
Age". When we select the words in the box, onselect event will be triggend and it
should display that "Please Enter only integers

<!DOCTYPE html>
<html>
<head>
<title>Onselect Event Example</title>
<script type="text/javascript">
function showSelectMessage() {
alert("Please Enter only integers");
}
</script>
</head>
<body>
<form>
<label for="age">Age:</label>
<input type="text" id="age" value="Select Age" onselect="showSelectMessage()">
</form>
</body>
</html>

14. Write a program to Demonstrate mousedown and mouseup events.

<!DOCTYPE html>
<title>Mouseup and Mousedown Example</title>
<img id="image" src="boy.jpg"
<html>
<head>
</head>
<body>
onmouseup="changeImage()"
onmousedown="revertImage()">
<script>
function changeImage() {
document.getElementById('image').src = 'girl.jpg';
}
function revertImage() {
document.getElementById('image').src = 'boy.jpg';
}
</script>
</body>
</html>

15. Explain the basic syntax of XML. What are the XML syntax rules? What is the
difference between well formed and valid XML documents?
XML Syntax :
An xml file consists of various elements. This section presents a brief introduction to key
terminologies used in relation to xml. This section shows how XML documents are constructed
and its syntax.
1.XML. Declaration:
• The XML declaration indicates that the document is written in XML and specifies which
Version of XML. The XML declaration, if included, must be on the first line of the document.
The XML declaration can also specify the language encoding for the document. In our
example, we specify that the document uses UTF-8 encoding. Although the XML declaration is
optional, the W3C recommends that we include it in our XML documents. In any case, we will
need the XML declaration to successfully validate our document.

Example : <?xml version="1.0" encoding="UTF-8"?>


Version - Version of the XML standard that the XML document conforms to. It is required if the
XML declaration is declared.
Encoding - Encoding name of the most common character sets like UTF-8, UTF-16, ISO-10646-
UCS-2 etc.

2. Root Element :
• All XML documents must have one (and only one) root element. All other elements must be
nested inside this root element. In other words, the root element must contain all other elements
within the document. Therefore, the first tag in the document will always be the opening tag of
the root element (the closing tag will always be at the bottom of the document).
• XML documents contains an element which is the parent of all other child elements. This first
element of the document is called the root element.

Example : <books>
----------
----------
</books>
<books> is the root element of the XML document. It serves as the top-level element encloses all
other elements in the document. In this case, '<books" is the outermost encapsulating the entire
content of the XML document.

3. Child Elements :
These are the elements that are contained within the root element Elements are usual
represented by an opening and closing tag. Data and other elements reside between opening and
closing tag of an element.

Example
<books>
<book>
<title>Web programming</title>
<author> Srikanth.S</author>
</book>
</books>
• <book is a child element of the 'books>' element. It is nested within the '<books>' element and
serves as a direct descendant of the root element. In this context, '<book>' is a sub-element of
books>', representing a specific book within the collection.
• Within the books' element, '<title>' and '<author>' are child elements. They are nested within
the 'book' element and represent specific attributes or properties of the book. In this case,
titles and <author>' are sub-elements of '<bool>', providing details about the title and author of
the book, respectively.
• XML tags are similar as in html. Tag starts with < and ends with > characters. Tags can have
attributes to provide information about tag.

• These are of three types :


1. Start tag (Example: <books)
2. End tag (Example: </book>)
3. Empty-element tag: This is also known as bodyless tag. It has a start tag but does not have a
matching end tag.
Example : <book/>

• Opening and closing tags collectively are called tag pair.


• XML tags follow some rules given below:
1. Tags must be nested properly.
2. Tags are case sensitive.
3. They must have a beginning and an end and enclosed in <and>.

4.Empty Elements :
Empty elements in XML are elements that do not have any content, and they are represented
in a specific format. In XML, empty elements can be expressed using a self-closing tag, which
Combines the start tag and end tag into a single tag

Example

<book>
<title>Web programming</title>
<author/>
</books>

• The <author>' element is also a child element of '<bool>', but it is an empty element. It does not
have any content, and it is represented using a self-closing tag. This is also known as bodyless
tag. It has a start tag but doesnot have a matching endtag
• Empty elements are used in XML to represent elements that do not have any content. In this
case, the <author>' element is empty because it does not contain any text or child elements.
The use of a self-closing tag ('<author/>') indicates that the element is empty.

5.Elements:
• The content between start tag and end tag including tags is called element. An element can
contain other child elements.

Example
<book>
<title>Web programming</title>
<author> Srikanth.sc/author>
</books>

Here, book is a tag and it has two children title and author. The "<title>Web programming</ title>"
and "<author> Srikanth S</author>" are elements. The "Web programming and "Srikanth S" are
text.

6.Attributes:
• Elements can also contain one or more attributes. An attribute is a name/value pair, that we
place within an opening tag, which allows us to provide extra information about an element. We
may be familiar with attributes in XHTML. For example, the XHTML img tag requires the src
attribute which specifies the location of an image

Example
<img src="myImage.gif"/>

• XML elements can contain attributes which provides some additional information about element.
For example, book element contains "type" attribute and it is assigned value "technical".
<book type="technical">
</book>
• Attributes often provide information that is not a part of the data. Attribute values must al be
enclosed in either single or double quotes. If the value of the attribute contains d quotes then use
single quote to enclose the value of the attribute.

7. Comments:
XML. comments begin with <!-- and end with -->. Similar to XHTML comments, XML, comment
allow us to write comments within the document and cooments are ignored by XML. parsers We
normally write comments as an explanatory note to ourselves or another programmer
Comments can appear anywhere within the document.

Example <!-- This file is related to books information -->

8. Root Element Closing Tag


• The last tag of the document will always be the closing tag of the root element. This is because
all other elements are nested inside the root element

Example </books>
XML Syntax Rules:
The syntx of XML is governed by a set of rules that define how XML documents should be
structured and formatted. The syntax rules for XML documents are discussed in this section .
1. All XML Documents must have root tag: All XML documents must contain a single tant pair to
define the vet sub (children) bier elements must be nested within the root element. All elements
can have sub (children) elements. Sub elements must be in pairs and correctly nested within their
parent element:

<root>
<child>
<subchild>
</subchild>
</child>
</root>

2. XML Is Case Sensitive: XML tags are case sensitive. The tag <Author> is different from the tag
<author>. Opening and closing tags must therefore be written with the same case:

<Author>This is different from author</Author>


<author>This is different from Author</author>

3. All XML Elements must have a Closing Tag: In XML all elements must have a closing tag like this:

<p>This is a paragraph</p>
<p>This is another paragraph</p>

4. All XML Elements must be properly Nested: In XML all elements must be properly nested within
each other like this

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

5. Attribute Values must always be Quoted: XML elements can have attributes in name/value pairs
just like in HTML. In XML, the attribute value must always be quoted.

Wrong: <book type-technical>


Correct: <book type="technical>

6. XML Restricts the Use of Certain Characters: XML tags use angle brackets (> and <symbols) for
enclosing tag names. Thus, these characters cannot appear in the element data. If we want to
include these symbols in our data, we must use replacement character sequences. The below
table lists all special characters and their corresponding replacement character sequences in XML.

Special Character Replacement


& &amp;
‘ &apos;
“ &quot;
< &lt;
> &gt;
Wrong : <num>2508500</num>
Correct: <num>250&amp;500</num>

7. Elements in an XML: Document Can be Nested: An XML document typically consists of several
element declarations. The document starts with a root element, and all other elements appear
under this root. The element declarations can be nested; however, we must observe proper
scoping while nesting the elements. A partial overlap during nesting is not permitted

8. Rules for Naming Tags in XML:


XML documents are extensible, thus it's the author's responsibility to create and name the markup
tags. However, in doing so, the author must comply with the following guidelines:
• The first character of each tag name must be a letter or the "_" character, but not numbers or
other punctuation.
Wrong <title>Web Programming</title>
Correct: <title>Web programming </title>

• After the first character, numbers are allowed as are the "-" and "." characters.
Correct: <K-12 First Grade</K-12>
Correct: cwww.gmail.com></www.gmail.com>

• Tag names cannot contain spaces

Wrong: <Employee Names></Employee Names>


Correct: <EmployeeNames></EmployeeNames>

Difference between Well formed and Valid Document :


1. Well-Formed Document:
• A well-formed XML document adheres to the syntax rules of XML.
• It must satisfy the basic structural requirements, such as having a single root element,
properly nested elements, correct usage of tags and attributes, and proper handling of
special characters.
• Well-formedness is a prerequisite for an XML document to be processed by XML parsers.
• All XML documents must be well-formed to be considered valid for processing.

2. Valid Document:
• A valid XML document not only meets the criteria for being well-formed but also conform to a
specific Document Type Definition (DTD) or XML Schema.
• It must adhere to the rules and structure defined in the DTD or XML Schema, including the
allowed elements, attributes, and their arrangement.
• Validation ensures that the document complies with the constraints and rules specified in the
DTD or XML Schema, providing a higher level of structural integrity and data consistency.
• Validation can be performed using an internal DTD, an external DTD, or an XML Schema.
16.Elobrate the process of performing database operations in PHP, including
querying, inserting, updating, and deleting records.

Connecting to Database:
Connecting to a database in PHP is a fundamental step when building dynamic web applications
that interact with databases. Databases store and manage data, and PHP provides various
database extensions and libraries to connect and work with different types of databases.

Connecting to a database in PHP typically involves using the PHP Data Objects (PDO) extension
or MySQLI (MySQL Improved) extension. PDO provides a data-access abstraction layer, which
means we can use the same functions to issue queries and fetch data regardless of the database
we are using. MySQLi is a PHP extension specifically designed for use with MySQL databases.

A step-by-step explanation of how to connect to a database in PHP is given below.


1. Choose the Database and Prepare Credentials:
We need to decide the database management system to use (e.g., MySQL, or others). We
Need the following information:
• Database server hostname or IP address
• Database username and password
• Database name (if it already exists)

2. Select the Database Extension:

PHP supports different database extensions or libraries to connect to various database


systems. Commonly used extensions include mysqli (MySQL Improved), PDO (PHP Data
Objects), and others. Choose the appropriate extension based on database system and
project requirements

3. Write PHP Code to Establish a Connection:


Depending on the selected extension, we can write code to establish a connection to the
Database.

Example : Using mysqli


// Database credentials
$servername = "localhost";
$username ="db_user";
$password ="db_password";
$dbname ="db_name";
// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: $conn->connect_error);
}

Example :Using PDO


// Database credentials
$servername = "localhost";
$username ="db_user";
$password ="db_password";
$dbname ="db name";
try {
// Create a PDO instance
$conn = new PDO("mysql:host =$servername; dbname=$dbname", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
die("Connection failed: $e->getMessage());
}

4 . Perform Database Operations:


Once the connection is established, we can perform various database operations, such as
querying data, inserting records, updating data, and deleting records. We will typically use SQL
queries or prepared statements to interact with the database.

Example :Selecting data using mysqli


$sql = "SELECT* FROM users";
$result= $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " $row["id"]." Name:" $row["name"]."<br>";
}
} else {
echo "No records found";

5. Close the Database Connection:


After we have finished working with the database, it's essential to close the connection to
release resources and improve performance.
Example: $conn->close();

17.Explain file read and file write methods with an example.

File Writing Methods :

Method and Description Example


fwrite(): <?php
$file = fopen("example.txt", "w");
The 'fwrite' function is used to write if ($file) { fwrite($file, "Hello, World!");
data to a file. It takes two fclose($file);
parameters: the file handle returned }
by 'fopen' and the data to be written ?>
to the file. If the write operation is
successful, 'fwrite' returns the This script opens "example.txt" for writing and writes "Hello,
number of bytes written; otherwise, World!" into it.
it returns 'false'.
file_put_contents(); <?php
$text = "Web Programming";
The 'file_put_contents' function is a file_put_contents("example.txt", $text);
simpler way to write data to a file. It ?>
takes two parameters: the file name
or path, and the data to be written to - In this example, the content "Web Programming" is written
the file. If the write operation is to the file "example.txt". This function handles the opening,
successful, 'file_put_contents' writing, and closing of the file internally
returns the number of bytes written;
otherwise, it returns 'false'.

File Reading Methods :

Method and Description Example


fopen() and fgets(): <?php
$file = fopen("example.txt","r");
Opens a file and reads it line by line. if ($file) {
fgets reads a line from the file until a while (($line = fgets($file)) !== false) {
newline or EOF. echo $line;
}
fclose($file);
}
?>
This script opens "example.txt", reads it line by line using
fgets(), and echoes each line until the end of the file is
reached.
file_get_contents(): <?php
$content = file_get_contents("example.txt");
Reads the entire file into a string. echo $content;
Best for reading the whole file at ?>
once but not suitable for very large
files. This example reads the entire content of "example.txt" and
stores it in $content, which is then echoed.
fread(): <?php
$file = fopen("example.txt", "r");
if ($file) {
Reads up to a specified length from a $content = fread($file, 100);
file. Used in conjunction with echo $content;
fopen(). fclose($file);
}
?>

The fopen() function opens "example.txt" in read-only mode.


The fread($file, 100) reads the first 100 bytes of the file. If the
file is smaller than 100 bytes, it reads until the end of the file.
file(): <?php
$lines = file("example.txt");
Reads the entire file into an array, foreach ($lines as $line)
with each line as an element of the {
array. Useful for processing files line echo $line;
by line. }
?>

This reads example.txt into an array and prints each line


fgetc(): <?php
$file = fopen("example.txt","r");
Reads a single character from the if ($file) {
file at a time. Useful for character- while (($char = fgetc($file)) !== false) {
by- character file processing echo $char;
}
fclose($file);
}
?>

In this example, "example.txt" is opened and read character


by character using fgetc(). Each character is echoed until
EOF is reached.

18.Write a PHP program to find the sum, subtraction, multiplication, and division
of two number using switch statement.

<!DOCTYPE HTML>
<html>
<head>
<title>PHP Program To Calculate Arithmetic operations using Switch Case</title>
</head>
<body>
<form method="post">
<table border="0">
<tr>
<td> <input type="text" name="num1" value="" placeholder="Enter 1st number"/> </td>
</tr>
<tr>
<td> <input type="text" name="num2" value="" placeholder="Enter 2nd number"/> </td>
</tr>
<tr>
<td> <input type="text" name="option" value="" placeholder="Enter any option"/> </td>
</tr>
<tr>
<td> <input type="submit" name="submit" value="Submit"/> </td>
</tr>
</table>
</form>
<?php
if(isset($_POST['submit']))
{
$a = $_POST['num1'];
$b = $_POST['num2'];
$ch = $_POST['option'];
echo "1 -> Addition<br>";
echo "2 -> Subtraction<br>";
echo "3 -> multiplication<br>";
echo "4 -> Divison<br>";
switch($ch)
{
case 1: $r = $a+$b;
echo " Addition = ".$r ;
break;
case 2: $r = $a-$b;
echo " Subtraction = ".$r ;
break;
case 3: $r = $a*$b;
echo " Multiplication = ".$r ;
break;
case 4: $r = $a/$b;
echo " Division = ".$r ;
break;
default: echo ("invalid option\n");
}
return 0;
}
?>
</body>
</html>

You might also like