Web Technology Lab
Web Technology Lab
II YEAR / IV SEM
OBJECTIVES:
1. The objectives of this course are to have a practical understanding about how to write PHP
code to solve problems.
2. Display and insert data using PHP and MySQL.
3. Test, debug, and deploy web pages containing PHP and MySQL.
4. It also aims to introduce practical session to develop simple applications using PHP and
MySQL.
OUTCOMES:
LIST OF PRACTICALS
1. Write a PHP program which adds up columns and rows of given table
2. Write a PHP program to compute the sum of first n given prime numbers
3. Write a PHP program to find valid an email address
4. Write a PHP program to convert a number written in words to digit.
5. Write a PHP script to delay the program execution for the given number of seconds.
6. Write a PHP script, which changes the colour of the first character of a word
7. Write a PHP program to find multiplication table of a number.
8. Write a PHP program to calculate Factorial of a number.
9. Write a PHP script to read a file, reverse its contents, and write the result back to a new
file
10. Write a PHP script to look through the current directory and rename all the files with
extension .txt to extension .xtx.
11. Write a PHP script to read the current directory and return a file list sorted by last
modification time. (using filemtime())
12. Write a PHP code to create a student mark sheet table. Insert, delete and modify records.
13. From a XML document (email.xml), write a program to retrieve and print all the e-mail
addresses from the document using XML
14. From a XML document (tree.xml), suggest three different ways to retrieve the text value
'John' using the DOM:
15. Write a program that connects to a MySQL database and retrieves the contents of any one
of its tables as an XML file. Use the DOM
Sl. Teacher’s
Date Name of the Experiment
No Signature
PHP PROGRAM WHICH ADDS UP COLUMNS AND
1
ROWS OF GIVEN TABLE
PHP PROGRAM TO COMPUTE THE SUM OF FIRST N
2
GIVEN PRIME NUMBERS
PHP PROGRAM TO VALIDATE THE GIVEN EMAIL
3
ADDRESS
PHP PROGRAM TO CONVERT A NUMBER
4
WRITTEN IN WORDS TO DIGIT
PHP SCRIPT TO DELAY THE PROGRAM
5 EXECUTION FOR THE GIVEN NUMBER OF
SECONDS
PHP SCRIPT WHICH CHANGES THE COLOR OF
6
THE FIRST CHARACTER OF A WORD
PHP PROGRAM TO PRINT THE MULTIPLICATION
7
TABLE FOR A GIVEN NUMBER
PHP PROGRAM TO CALCULATE THE FACTORIAL
8
OF A NUMBER
PHP SCRIPT TO READ A FILE, REVERSE ITS
9 CONTENTS, AND WRITE THE RESULT BACK TO A
NEW FILE
PHP SCRIPT TO LOOK THROUGH THE CURRENT
10 DIRECTORY AND RENAME ALL THE FILES WITH
EXTENSION .TXT TO EXTENSION .XTX
PHP SCRIPT TO READ THE CURRENT DIRECTORY
11 AND RETURN A FILE LIST SORTED BY LAST
MODIFICATION TIME. (Using filemtime())
PHP CODE TO CREATE A STUDENT MARKSHEET
12
TABLE. INSERT, DELETE AND MODIFY RECORDS
PROGRAM TO RETRIEVE AND PRINT ALL THE E-
13 MAIL ADDRESSES FROM THE DOCUMENT
(email.xml) USING XML
SUGGESTING THREE DIFFERENT WAYS TO
14 RETRIEVE THE TEXT VALUE 'JOHN' FROM AN
XML DOCUMENT (tree.xml), USING THE DOM
PROGRAM THAT CONNECTS TO A MYSQL
DATABASE AND RETRIEVES THE CONTENTS OF
15
ANY ONE OF ITS TABLES AS AN XML FILE. USE
THE DOM
1. PHP PROGRAM WHICH ADDS UP COLUMNS AND ROWS OF GIVEN TABLE
Aim:
To write a PHP program that adds up columns and rows of a given table.
Algorithm:
Step 1 : Start the execution.
Step 2 : Declare and initialize a two-dimensional array a.
Step 3 : Input the number of rows and columns of the matrix.
Step 4 : Input the matrix elements.
Step 5 : Print the matrix elements.
Step 6 : Maintain two variables ColSum and RowSum to store the sum of elements in the
specific column and the sum of elements in specific row respectively.
Step 7 : To calculate the sum of elements in each column:
a. Two loops will be used to traverse the array where the outer loop select a
column, and the inner loop represents the rows present in the matrix a.
b. Calculate the sum by adding the elements present in a column.
c. Display ColSum.
d. Repeat this for each column.
Step 8 : To calculate the sum of elements in each row:
a. Two loops will be used to traverse the array where the outer loop selects a
row, and the inner loop represents the columns present in the matrix a.
b. Calculate the sum by adding the elements present in a row.
c. Display RowSum.
d. Repeat this for each row.
Step 9 : Open any text editor (like Notepad) and enter the code.
Step 10: Save the script in the folder c:\wamp\bin\php\php5.3.0\Col_Row_Sum_Table.php.
That can be done by clicking File then Save As.
Step 11 : Execute the script in the command prompt as:
c:\wamp\bin\php\php5.3.0>php Col_Row_Sum_Table.php
Step 12 : Stop the execution
Program:
<?php
// PHP program to find the sum of each column and row of a table
// Col_Row_Sum_Table.php
echo "\nPHP program to find the sum of each column and row of a table";
echo "\n ";
echo "\nEnter the number of rows: ";
fscanf(STDIN,"%d",$m);
echo "\nEnter the number of columns: ";
fscanf(STDIN,"%d",$n);
$a=array(array());
echo "\nEnter $m x $n elements of matrix a\n";
for($i=0;$i<$m;$i++)
{
for($j=0;$j<$n;$j++)
{
fscanf(STDIN,"%d",$a[$i][$j]);
}
}
// Printing the matrix
echo "\nThe given matrix:\n\n";
for($i=0;$i<$m;$i++)
{
for($j=0;$j<$n;$j++)
{
echo ($a[$i][$j]." ");
}
echo "\n";
}
// Finding the sum of each column
echo "\nSum of each column\n\n";
for($i=0;$i<$m;$i++)
{
$ColSum = 0;
for($j=0;$j<$n;$j++)
{
$ColSum = $ColSum + $a[$j][$i];
}
echo("Sum of ".($i+1)." Column ".$ColSum);
echo "\n";
}
// Finding the sum of each row
echo "\nSum of Each row\n\n";
for($i=0;$i<$m;$i++)
{
$RowSum = 0;
for($j=0;$j<$n;$j++)
{
$RowSum = $RowSum + $a[$i][$j];
}
echo ("Sum of ".($i+1)." Row ".$RowSum);
echo "\n";
}
?>
Output:
C:\wamp\bin\php\php5.3.0>php Col_Row_Sum_Table.php
PHP program to find the sum of each column and row of a table
456
123
789
Sum of each column
Sum of 1 Column 12
Sum of 2 Column 15
Sum of 3 Column 18
Sum of 1 Row 15
Sum of 2 Row 6
Sum of 3 Row 24
C:\wamp\bin\php\php5.3.0>
Result:
Thus, the PHP program that adds up columns and rows of given table has been executed
successfully.
2. PHP PROGRAM TO COMPUTE THE SUM OF FIRST N GIVEN PRIME NUMBERS
Aim:
To write a PHP program to compute the sum of first n given prime numbers.
Algorithm:
Step 1: Start the execution.
Step 2: Enter a list of numbers, separated by commas.
Step 3: Define an array named primes that will store all the prime numbers.
Step 4: Using for loop, check for each number to be a prime number. If it is a prime
number, then store that number into the primes array.
Step 5: Print the list of prime numbers.
Step 6: Using the array_sum() method, find the sum of all prime numbers from the primes
array.
Step 7: Print the sum of all prime numbers.
Step 8: Open any text editor (like Notepad) and enter the code.
Step 9: Save the script into the folder c:\wamp\www\Prime_Nos_Sum.php
That can be done by clicking File then Save As.
Step 10: Start the WampServer.
Step 11: Execute the script by typing localhost/Prime_Nos_Sum.php in the address bar of
the browser.
Step 12: Stop the execution.
Program:
<! -- PHP program to compute the sum of first n given prime numbers -- >
<! -- Prime_Nos_Sum.php -- >
<!DOCTYPE html>
<html>
<head>
<title>PHP program to find the sum of prime numbers</title>
</head>
<body>
<h4><u>Compute the sum of first n given prime numbers</u></h4>
<form method="post">
Enter a list of numbers, separated by commas: <br /></br>
<input type="text" name="num" />
<p>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
if (isset($_POST['submit']))
{
$numStr = $_POST['num'];
$numArr = explode(',', $_POST['num']);
$primes = array();
$Flag = 0;
foreach ($numArr as $n)
{
$n = trim(abs($n));
for ($i=2; $i<$n; $i++)
{
$Flag = 0;
if (($n%$i) == 0)
{
break;
}
$Flag = 1;
}
// If prime add to primes array
if ($Flag == 1)
{
array_push($primes, $n);
}
}
$Total=count($primes);
echo "\nThe prime numbers are: ";
for ($i=0;$i<$Total;$i++)
{
echo($primes[$i]." ");
}
$S=array_sum($primes);
echo "<br><br>The sum of prime numbers = ".$S;
}
?>
</body>
</html>
Output:
Algorithm:
Result:
Thus, the email address validation program using PHP has been executed successfully.
4. PHP PROGRAM TO CONVERT A NUMBER WRITTEN IN WORDS TO DIGIT
Aim:
Algorithm:
Result:
Thus, the PHP program to convert a number written in words to digit has been executed
successfully.
5. PHP SCRIPT TO DELAY THE PROGRAM EXECUTION FOR THE GIVEN
NUMBER OF SECONDS
Aim:
To write a PHP script to delay the program execution for a given number of seconds.
Algorithm:
Thus, the PHP script to delay the program execution for a given number of seconds has
been executed successfully.
6. PHP SCRIPT WHICH CHANGES THE COLOR OF THE FIRST CHARACTER
OF A WORD
Aim:
To write PHP script which changes the color of the first letter of a word.
Algorithm:
<!-- 6. PHP Script to change the color of the first letter of a word -- >
<!-- Change_Word_Color.php -- >
<!DOCTYPE html>
<html>
<head>
<title>PHP Script to change the color of the first letter of a word</title>
</head>
<body>
<h4><u>Changing the Color of the First Letter of Each Word</u></h4>
<form method="post">
Enter the text:
<input type="text" name="text" /><br><br>
<input type="submit" name="submit" value="Changing the Color"><br><br>
</form>
<?php
if(isset($_POST['submit']))
{
$text = $_POST['text'];
$text = preg_replace('/(\b[a-z])/i','<span style="color:red;">\1</span>',$text);
echo $text;
}
?>
</body>
</html>
Output:
Result:
Thus, the PHP Script to change the color of the first letter of a word has been executed
successfully.
7. PHP PROGRAM TO PRINT THE MULTIPLICATION TABLE FOR A GIVEN
NUMBER
Aim:
To write a PHP program to print the multiplication table for a given number.
Algorithm:
Result:
Thus, the PHP program to print the Multiplication Table has been executed successfully.
8. PHP PROGRAM TO CALCULATE THE FACTORIAL OF A NUMBER
Aim:
To write a PHP program to find the factorial value of a given number.
Algorithm:
Step 1 : Start the execution.
Step 2 : Read the value of n.
Step 3 : Calculate $f=1.
Step 4 : Within the for loop use the formula, $f=$f * $i to compute the factorial value.
Step 5 : Open any text editor (like Notepad) and enter the code.
Step 6 : Print the factorial value.
Step 7 : Save the script into the folder c:\wamp\www\fact.php
That can be done by clicking File then Save As.
Step 8 : Start the WampServer.
Step 9 : Execute the script by typing localhost/fact.php in the address bar of the browser.
Step 10 : Stop the execution.
Program:
<!-- 8. PHP Program to calculate the Factorial of a number -- >
<!-- fact.php -->
<!DOCTYPE html>
<html>
<head>
<title>PHP Program to calculate the Factorial value </title>
</head>
<body>
<h4><u>Factorial of a Number</u></h4>
<form method="post">
Enter the value of n:
<input type="Number" name="n" /><br><br>
<input type="submit" name="submit" value="Calculate Factorial"><br><br>
</form>
<?php
if(isset($_POST['submit']))
{
$n = $_POST['n'];
$f=1;
for ($i=1; $i<=$n; $i++)
{
$f = $f * $i;
}
echo "Factorial of $n is $f";
}
?>
</body>
</html>
Output:
Result:
Thus, the PHP program to calculate the factorial value of a given number has been
executed successfully.
9. PHP SCRIPT TO READ A FILE, REVERSE ITS CONTENTS, AND WRITE THE
RESULT BACK TO A NEW FILE
Aim:
To write a PHP Script to read a file, reverse its contents, and write the result back to a
new file.
Algorithm:
<!-- 9. PHP script to read a file, reverse its contents, and write the result back to a new file-- >
<!-- File_Program.php -- >
<!DOCTYPE html>
<html>
<head>
<title>PHP Script to read a file, reverse its contents, and write the result back to a new file
</title>
</head>
<body>
<?php
// Fetch each line from File1.txt into an array
$FileLines = file('File1.txt');
// Reverse the array elements
$ReversedLines = array_reverse($FileLines);
// Write the reversed array into File2.txt
file_put_contents('File2.txt', $ReversedLines);
echo ‘The content of File1.txt has been written into File2.txt in the reverse order’
?>
</body>
</html>
Output:
The content of File1.txt has been written into File2.txt in the reverse order
File1.txt
1 Sujatha T 52
2 Saraswathi P 41
3 Alexander M 42
4 Senthil S Sekhar 47
5 Geetha K 43
6 Duggi Chandra Mouli 43
7 Kavitha D 39
File2.txt
7 Kavitha D 39
6 Duggi Chandra Mouli 43
5 Geetha K 43
4 Senthil S Sekhar 47
3 Alexander M 42
2 Saraswathi P 41
1 Sujatha T 52
Result:
Thus, the PHP script to read a file, reverse its contents, and write the result back to a new
file has been executed successfully.
10. PHP SCRIPT TO LOOK THROUGH THE CURRENT DIRECTORY AND
RENAME ALL THE FILES WITH EXTENSION .TXT TO EXTENSION .XTX
Aim:
To write a PHP script to look through the current directory and rename all the files with
extension .txt to extension .xtx.
Algorithm:
Step 1 : Start the execution.
Step 2 : Get the current directory path by using the getcwd() function.
Step 3 : Set the file pattern like $dirpath .= "\*.txt";
Step 4 : Copy the files into an array.
Step 5 : Use the rename() function to rename all the files in the current directory with
the extension .txt to .xtx.
Step 6 : Print the current directory after renaming the files.
Step 7 : Save the script into the folder c:\wamp\www\Ren_Files.php
That can be done by clicking File then Save As.
Step 8 : Start the WampServer.
Step 9 : Execute the script by typing localhost/Ren_Files.php in the address bar of
the browser.
Step 9 : Stop the execution.
Program:
<!-- 10. PHP script to look through the current directory and rename all the files -- >
<!-- with the extension .txt to .xtx -- >
<!-- Ren_Files.php -- >
<!DOCTYPE html>
<html>
<head>
<title>PHP Script to look through the current directory and rename all the files </title>
</head>
<h4><u>Rename all the files with the extension .txt to .xtx</u></h4>
<?php
// Get the current directory path
$dirpath = getcwd();
// Set the file pattern
$dirpath .= "\*.txt";
// Copy filenames to array
$files = array();
// The glob() function returns an array of filenames or directories matching a specified
pattern
$files = glob($dirpath);
echo "Original .txt Files"."<br><br>";
foreach($files as $item)
{
echo $item."<br>";
//echo(rename($tem,($item.”.xtx”)))."<br>";
}
?>
</body>
</html>
Output:
Result:
Thus, the PHP script to look through the current directory and rename all files with the
extension .txt to .xtx has been executed successfully.
11. PHP SCRIPT TO READ THE CURRENT DIRECTORY AND RETURN A FILE
LIST SORTED BY LAST MODIFICATION TIME. (Using filemtime())
Aim:
To write a PHP script to read the current directory and return a file list sorted by last
modification time.
Algorithm:
<!-- 11. PHP script to read the current directory and return a file list sorted by -- >
<!-- last modification time -- >
<!-- Files_Sorted_By_Last_Modification_Time.php -- >
<!DOCTYPE html>
<html>
<head>
<title>File List Sorted by Last Modification Time </title>
</head>
<body>
<h4><u>File List Sorted by Last Modification Time</u></h4>
<?php
// Get the current directory path
$dirpath = getcwd();
// Set the file pattern
$dirpath .= "\*.txt";
// Copy the filenames to array
$files = array();
// The glob() function returns an array of filenames or directories matching a specified pattern
$files = glob($dirpath);
// Sort files by last modified date
usort($files, function($x, $y)
{
return filemtime($x) < filemtime($y);
});
foreach($files as $item)
{
echo basename($item) . " Last Modified On " . date('F d Y H:i:s.', filemtime($item)) . "<br>";
}
?>
</body>
</html>
Output:
Aim:
To write a PHP code to create a student mark sheet table and perform Insert, Delete and
Modify records.
Algorithm:
Step 1 : Start the execution.
Step 2 : Create a database named Student in the mysql prompt.
Step 3 : Use the database Student.
Step 4 : Create a table named Mark_Sheet in the mysql prompt.
Step 5 : Use the following steps to Insert, Select, Update and delete records using PHP and
MySQL.
• Index.php – Main Program
• DB.php – Connecting Database
• Add_Record.php – Insert Records Into MySQL DB
• View_Record.php – Select Record From MySQL DB
• Modify_Record.php – Update Record Into MySQL DB
• Delete_Record.php – Delete Record From MySQL DB
Step 6 : Save the above 6 files into the Folder c:\wamp\www\Ex_12
Step 7 : Start the WampServer.
Step 8 : Execute the script by typing localhost in the address bar of the browser.
Step 9 : The WampServer screen will be displayed.
Step 10 : Click on the item Your Projects. Select the file Index.php from the folder Ex_12.
Step 11 : Stop the execution.
To start mysql at the DOS prompt, type cmd in the Windows search box.
C:\>cd\wamp\bin\mysql\mysql5.1.36\bin ↵
C:\wamp\bin\mysql\mysql5.1.36\bin>mysql –u root –p ↵
mysql>
To create a database,
mysql>Create Database Student;
Query OK, 1 row affected (0.05 sec)
To use the database,
mysql;>Use Student;
Database Changed
To create a Student Mark Sheet Table,
mysql> CREATE TABLE Mark_Sheet (Roll_No INT(6) PRIMARY KEY,
-> Student_Name VARCHAR (20), MARK1 INT(3),
-> MARK2 INT(3), MARK3 INT(3), MARK4 INT(3));
Query OK, 0 rows affected (0.07 sec)
mysql>exit ↵
Aim:
To write an XML program to retrieve and print all the e-mail addresses from the document
email.xml.
Algorithm:
Step 1 : Start the execution.
Step 2 : Create an XML file named email.xml using any text editor and store some email
addresses.
Step 3 : Create a PHP file named Retrieve_Email.php to retrieve all the e-mail addresses
and print the same on the screen.
Step 4 : Save the above files into the folder c:\wamp\www.
Step 5 : Start the WampServer.
Step 6 : Execute the PHP script by typing localhost/Retrieve_Email.php in the address bar
of the browser
Step 7 : Stop the execution.
Program:
<?xml version = "1.0"?>
<!-- 13. XML program to store E-Mail Addresses -->
<!-- email.xml-->
<Email_Address>
<Email Id="1">
<Email_Addr>[email protected]</Email_Addr>
<Name>T. Sujatha</Name>
</Email>
<Email Id="2">
<Email_Addr>[email protected]</Email_Addr>
<Name>P. Saraswathi</Name>
</Email>
<Email Id="3">
<Email_Addr>[email protected]</Email_Addr>
<Name>M. Alexander</Name>
</Email>
<Email Id="4">
<Email_Addr>[email protected]</Email_Addr>
<Name>Senthil .S. Sekhar</Name>
</Email>
<Email Id="5">
<Email_Addr>[email protected]</Email_Addr>
<Name>K. Geetha</Name>
</Email>
<Email Id="6">
<Email_Addr>[email protected]</Email_Addr>
<Name>Duggi Chandra Mouli</Name>
</Email>
<Email Id="7">
<Email_Addr>[email protected]</Email_Addr>
<Name>R. Kavitha</Name>
</Email>
<Email Id="8">
<Email_Addr>[email protected]</Email_Addr>
<Name>S. Lawrence</Name>
</Email>
<Email Id="9">
<Email_Addr>[email protected]</Email_Addr>
<Name>D. Kavitha</Name>
</Email>
<Email Id="10">
<Email_Addr>[email protected]</Email_Addr>
<Name>V. Murugan</Name>
</Email>
</Email_Address>
<! -- PHP program to retrieve all the email addresses and display the same on the screen -- >
<!-- Retrieve_Email.php -->
<!DOCTYPE html>
<html>
<head>
<title>Display Email Addresses</title>
</head>
<body>
<h4><u>Email Addresses</u></h4>
<?php
// Load XML file
$xml = simplexml_load_file('email.xml') or die ("Unable to load XML!");
// Loop over XML data as array
// Print Email Addresses
foreach ($xml->Email as $Email)
{
echo $Email->Email_Addr . "<br>";
}
?>
</body>
</html>
Output:
Result:
Thus, the XML program to retrieve and print all the e-mail address from the document
email.xml has been executed successfully.
14. SUGGESTING THREE DIFFERENT WAYS TO RETRIEVE THE TEXT
VALUE 'JOHN' FROM AN XML DOCUMENT (tree.xml), USING THE DOM
Aim:
To write an XML program to create a document named tree.xml and suggesting three
different ways to retrieve the text value ‘John’ using the DOM.
Algorithm:
Step 1 : Start the execution.
Step 2 : Create an XML document named “tree.html” using any text editor.
Step 3 : Create a file named Retrieve_Name.php to retrieve the text value ‘John’ using the
DOM.
Step 4 : Save the above two files into the Folder c:\wamp\www.
Step 5 : Start the WampServer.
Step 6 : Execute the script by typing localhost/Retrieve_Name.php in the address bar of
the browser
Step 7 : Stop the execution.
Program:
<?xml version = "1.0"?>
<!-- 14. XML program to retrieve the text value John using the DOM -- >
<!-- tree.xml-->
<Students>
<Student>
<Name>John</Name>
<Age>30</Age>
<Gender>Male</Gender>
</Student>
<Student>
<Name>Akash Kumar</Name>
<Age>21</Age>
<Gender>Male</Gender>
</Student>
<Student>
<Name>Selva Madhavan</Name>
<Age>18</Age>
<Gender>Male</Gender>
</Student>
<Student>
<Name>Keerthiga</Name>
<Age>19</Age>
<Gender>Female</Gender>
</Student>
<Student>
<Name>Abilash Kumar</Name>
<Age>15</Age>
<Gender>Male</Gender>
</Student>
<Student>
</Students>
<! -- PHP program to retrieve the text value ‘John’ using the DOM -- >
<!-- Retrieve_Name.php -->
<!DOCTYPE html>
<html>
<head>
<title>Retrieve the text value ‘John’</title>
</head>
<body>
<h3><u>Retrieving the text value John using the DOM</u></h3>
<?php
// Load XML file
$xml = simplexml_load_file('treel.xml') or die ("Unable to load XML!");
// Loop over XML data as array
// Printing the text value ‘John’
foreach ($xml->Student as $Student)
{
echo strstr($Student->Name,”John”) . "<br>";
}
?>
</body>
</html>
Output:
Result:
Thus, the XML program to create a document named tree.html and suggesting three
different ways to retrieve the text value ‘John’ using the DOM has been executed
successfully.
15. PROGRAM THAT CONNECTS TO A MYSQL DATABASE AND RETRIEVES THE
CONTENTS OF ANY ONE OF ITS TABLES AS AN XML FILE. USE THE DOM
Aim:
To write an XML program that connects to a MySQL database and retrieve the contents of
any one of its tables using the DOM.
Algorithm:
Step 1: Start the execution.
Step 2: Create a database named Library in MySQL.
Step 3: Use the database that has been created.
Step 4: Create a table named Books.
Step 5: Insert some records into the table.
Step 6: Fetch data from the database and generate XML file.
Step 7: Stop the execution.
Program:
<! -- 15. PHP program that connects to a MySQL database and retrieves -- >
<!-- the contents of any one of its tables as an XML file -- >
<!-- generatexml.php -->
<!DOCTYPE html>
<html>
<head>
<title>Retrieve the contents of the table as an XML File</title>
</head>
<body>
<h4><u>Retrieving the Contents of the Table as an XML File</u></h4>
<?php
// Create XML file
$mysqli = new mysqli("localhost", "root", "", "Library");
// Check connection
if ($mysqli->connect_errno) '
{
echo "Connection failed ".$mysqli->connect_error;
exit();
}
$query = "SELECT * FROM books";
$booksArray = array();
if ($result = $mysqli->query($query))
{
// Fetch associative array
while ($row = $result->fetch_assoc())
{
array_push($booksArray, $row);
}
if(count($booksArray))
{
createXMLfile($booksArray);
}
// Free result set
$result->free();
}
// Close connection
$mysqli->close();
function createXMLfile($booksArray)
{
$filePath = 'book.xml';
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('books');
for($i=0; $i<count($booksArray); $i++)
{
$BookId = $booksArray[$i]['Book_No'];
$BookName = $booksArray[$i]['Book_Name']);
$BookAuthor = $booksArray[$i]['Author'];
$BookPrice = $booksArray[$i]['Price'];
$BookISBN = $booksArray[$i]['ISBN'];
$BookPub = $booksArray[$i]['Publication'];
$book = $dom->createElement('book');
$book->setAttribute('Book_No', $BookId);
$name = $dom->createElement('Book_Name', $BookName);
$book->appendChild($name);
$author = $dom->createElement('Author', $BookAuthor);
$book->appendChild($author);
$price = $dom->createElement('Price', $BookPrice);
$book->appendChild($price);
$isbn = $dom->createElement('ISBN', $BookISBN);
$book->appendChild($isbn);
$publication = $dom->createElement('Publication', $BookPub);
$book->appendChild($publication);
$root->appendChild($book);
}
$dom->appendChild($root);
$dom->save($filePath);
}
?>
</body>
</html>
Output:
Result:
Thus, the XML program that connects to a MySQL database and retrieves the contents of
any one of its tables using the DOM has been executed successfully.
<! -- PHP program to retrieve the name in different ways -- >
<!-- Retrieve_Name_Different_Ways.php -->
<!DOCTYPE html>
<html>
<head>
<title>Retrieve the name in different ways</title>
</head>
<body>
<form method="post">
Enter Your Name: <input type="text" name="Name"/><br>
<input type="submit" name="submit" /><br>
</form>
<?php
// Check if the form is submitted
if ( isset( $_POST['submit'] ) )
{
// Retrieve the form data by using the element's name attributes value as key
echo '<h4>Form data retrieved by using the $_REQUEST variable<h4/>';
$Name = $_REQUEST['Name'];
// Display the results
echo 'Your name is ' . $Name;
// Check if the post method is used to submit the form
if ( filter_has_var( INPUT_POST, 'submit' ) )
{
echo '<h4>Form data retrieved by using $_POST variable<h4/>';
$Name = $_POST['Name'];
// Display the results
echo 'Your name is ' . $Name;
}
// Check if the get method is used to submit the form
if ( filter_has_var( INPUT_GET, 'submit' ) )
{
echo '<h4>Form data retrieved by using $_GET variable<h4/>';
$Name = $_GET['Name'];
// Display the results
echo 'Your name is ' . $Name;
}
}
?>
</body>
</html>