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

Web Technology Lab

The PHP program takes a list of numbers as input, separates them into an array, checks each number to determine if it is prime, stores the prime numbers in a new array, prints the prime numbers, and calculates the sum of all the prime numbers using the array_sum() function. It successfully computes the sum of the first n prime numbers from a given list of numbers.

Uploaded by

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

Web Technology Lab

The PHP program takes a list of numbers as input, separates them into an array, checks each number to determine if it is prime, stores the prime numbers in a new array, prints the prime numbers, and calculates the sum of all the prime numbers using the array_sum() function. It successfully computes the sum of the first n prime numbers from a given list of numbers.

Uploaded by

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

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

❖ On the completion of this laboratory course the students ought to


❖ Obtain knowledge and develop application programs using Python.
❖ Create dynamic Web applications such as content management, user registration, and e-
commerce using PHP and to understand the ability to post and publish a PHP website.
❖ Develop a MySQL database and establish connectivity using MySQL.

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

Enter the number of rows: 3

Enter the number of columns: 3

Enter 3 x 3 elements of matrix a


4
5
6
1
2
3
7
8
9

The given matrix:

456
123
789
Sum of each column

Sum of 1 Column 12
Sum of 2 Column 15
Sum of 3 Column 18

Sum of Each row

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:

The prime numbers are: 17 53 11 67 31


The sum of prime numbers = 179
Result:
Thus, the PHP program to find the sum of prime numbers in an array has been executed
successfully.
3. PHP PROGRAM TO VALIDATE THE GIVEN EMAIL ADDRESS
Aim:

To write a PHP program to validate the given email address.

Algorithm:

Step 1 : Start the execution.


Step 2 : Read the email address.
Step 3 : Use the filter_var() method, check whether the email address we have entered
is correct or not.
Step 4 : If the email address is correct, then print the message “Valid email address”.
Step 5 : Else, display the message “Not a valid email address”.
Step 6 : Open any text editor (like Notepad) and enter the code.
Step 7 : Save the script into the folder c:\wamp\www\Email_Validation.php
That can be done by clicking File then Save As.
Step 8 : Start the WampServer.
Step 9 : Execute the script by typing localhost/Email_Validation.php in the address bar
of the browser.
Step 10 : Stop the execution.
Program:
<!-- 3. PHP Program to validate the given Email Address-->
<!-- Email_Validation.php -- >
<!DOCTYPE html>
<html>
<head>
<title>PHP Program to validate the given email address</title>
</head>
<body>
<h4><u>Email Address Validation</u></h4>
<form method="post">
Enter the email address: <input type="text" name="email" /><br><br>
<input type="submit" name="submit" value="Check Email Address" /><br><br>
</form>
<?php
if(isset($_POST['submit']))
{
$email = $_POST['email'];
// Validate email address
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo("$email is a valid email address");
}
else
{
echo("$email is not a valid email address");
}
}
?>
</body>
</html>
Output:

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:

To write a PHP program to convert a number in words to digit.

Algorithm:

Step 1 : Start the execution.


Step 2 : Read the number to be written in word.
Step 3 : Call the function word_digit().
Step 4 : Display the corresponding number for each word.
Step 5 : Open any text editor (like Notepad) and enter the code.
Step 6 : Save the script in the folder c:\wamp\www\word_to_digits.php
That can be done by clicking File then Save As.
Step 7 : Start the WampServer.
Step 8 : Execute the script by typing localhost/word_to_digits.php in the address bar of
the browser.
Step 9 : Stop the execution.
Program:
<!-- 4. PHP Program to convert a number written in words to digits -- >
<! – word_to_digits.php -- >
<!DOCTYPE html>
<html>
<head>
<title>PHP Program to convert a number written in words to digit</title>
</head>
<body>
<h4><u>Conversion of a number written in words to digit</u></h4>
<form method="post">
Enter the number in words: <input type="text" name="word" /><br><br>
<input type="submit" name="submit" value="Convert"><br><br>
</form>
<?php
if(isset($_POST['submit']))
{
$word = $_POST['word'];
echo word_digit($word)."\n";
}
// Function to convert number written in words to digits
function word_digit($word)
{
$warr = explode(';',$word);
$result = '';
foreach($warr as $value)
{
switch(trim($value))
{
case 'zero':
$result .= '0';
break;
case 'one':
$result .= '1';
break;
case 'two':
$result .= '2';
break;
case 'three':
$result .= '3';
break;
case 'four':
$result .= '4';
break;
case 'five':
$result .= '5';
break;
case 'six':
$result .= '6';
break;
case 'seven':
$result .= '7';
break;
case 'eight':
$result .= '8';
break;
case 'nine':
$result .= '9';
break;
}
}
return $result;
}
?>
</body>
</html>
Output:

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:

Step 1 : Start the execution.


Step 2 : Use the sleep() method to delay the program execution for 5 seconds..
Step 3 : Display the current date.
Step 4 : Again use the sleep() method to delay the program execution for 5 seconds.
Step 5 : Display the current time.
Step 6 : Open any text editor (like Notepad) and enter the code.
Step 7 : Save the script into the folder c:\wamp\www\delay.php
That can be done by clicking File then Save As.
Step 8 : Start the WampServer.
Step 9 : Execute the script by typing localhost/delay.php in the address bar of the browser.
Step 10 : Stop the execution.
Program:
<!-- 5. PHP Script to delay the program execution for a given number of seconds -->
<!-- delay.php -->
<!DOCTYPE html>
<html>
<head>
<title>PHP Script to delay the program execution for a given number of seconds</title>
</head>
<body>
<h4><u>Current Date and Time</u></h4>
<?php
// Current Date and Time
sleep(3);
echo "Current Date: " . date('Y/m/d') . "<br><br>";
sleep(5);
echo "Current Time: " . date('h:i:s');
?>
</body>
</html>
Output:
Result:

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:

Step 1 : Start the execution.


Step 2 : Read the string.
Step 3 : Use the preg_replace() method, change the first color of each word to red color.
Step 4 : Print the text after changing the color of the first letter of each word.
Step 5 : Open any text editor (like Notepad) and enter the code.
Step 6 : Save the script into the folder c:\wamp\www\Change_Word_Color.php
That can be done by clicking File then Save As.
Step 7 : Start the WampServer.
Step 8 : Execute the script by typing localhost/Change_Word_Color.php in the address bar of
the browser.
Step 9 : Stop the execution.
Program:

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

Step 1 : Start the execution


Step 2 : Read the value of table.
Step 3 : Read the length of the table.
Step 4 : Using for loop, print the multiplication table.
Step 5 : Open any text editor (like Notepad) and enter the code.
Step 6 : Save the script into the folder c:\wamp\www\Multiplication_Table.php
That can be done by clicking File then Save As.
Step 7 : Start the WampServer.
Step 8 : Execute the script by typing localhost/Multiplication_Table.php in the address bar of
the browser.
Step 9 : Stop the execution.
Program:

<!-- 7. PHP Program to print the Multiplication Table -- >


<!-- Multiplication_Table.php-->
<!DOCTYPE html>
<html>
<head>
<title>PHP Program to print the Multiplication Table </title>
</head>
<body>
<h4><u>Printing Multiplication Table</u></h4>
<form method="post">
Enter the table : <input type="Number" name="table" /><br><br>
Enter the length : <input type="Number" name="length" /><br><br>
<input type="submit" name="submit" value="Print Multiplication Table"><br><br>
</form>
<?php
if(isset($_POST['submit']))
{
$table = $_POST['table'];
$length= $_POST['length'];
echo "Multiplication Table<br><br>";
for($i=1; $i<=$length; $i++)
{
echo "$i * $table = ".$i * $table. "<br>";
}
}
?>
</body>
</html>
Output:

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:

Step 1 : Start the execution.


Step 2 : Fetch each line from File1.txt and store it into an array named $FileLines.
Step 3 : Reverse the contents of an array using the array_reverse() fun ction.
Step 4 : Store the reversed array elements into an array named $Reversed_Lines.
Step 5 : Write the content of the array $Reversed_Lines into a file named “File2.txt”.
Step 6 : Save the script into the folder c:\wamp\www\File_Program.php
That can be done by clicking File then Save As.
Step 7 : Start the WampServer.
Step 8 : Execute the script by typing localhost/File_Program.php in the address bar of
the browser.
Step 9 : Stop the execution.
Program:

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

Step 1 : Start the execution


Step 2 : Get the current directory path using the getcwd() function.
Step 3 : Set the desired file pattern.
Step 4 : Copy the filenames into an array.
Step 5 : Use the globe() function to store the filenames in an array that matches the specified
pattern.
Step 6 : Sort the files in the array using the usort() function.
Step 7 : Use the filemtime() function and foreach loop, display the list of files sorted by last
modification time.
Step 8 : Save the script into the folder
c:\wamp\www\Files_Sorted_By_Last_Modification_Time.php.
That can be done by clicking File then Save As.
Step 9 : Start the WampServer.
Step 10 : Execute the script by typing
localhost/Files_Sorted_By_Last_Modification_Time.php in the address bar of the
browser.
Step 11 : Stop the execution.
Program:

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

File List Sorted by Last Modification Time


File2.txt=> Last Modified On January 21 2022 00:14:49.
File1.txt=> Last Modified On January 21 2022 00:12:06.
Result:
Thus, the PHP Script to read the current directory and return a file list sorted by last
modification time has been executed successfully.
12. PHP CODE TO CREATE A STUDENT MARKSHEET TABLE. INSERT,
DELETE AND MODIFY RECORDS

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)

To exit from mysql,

mysql>exit ↵

1. Index.php – Main Program

<!-- 12. PHP Program to perform database operations -- >


<!-- Index.php -->
<!DOCTYPE html>
<html>
<head>
<title>PHP Program to perform database operations</title>
</head>
<body>
<h4><u>Database Operations</u></h4>
<form method="post">
1. Add New Records <br>
2. View Records <br>
3. Modify Records<br>
4. Delete Records<br><br>
Enter Your Choice [1..4]: <input type="Number" name="Ch" /><br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
</form>
<?php
if(isset($_POST['submit']))
{
$Ch = $_POST['Ch'];
switch($Ch)
{
case 1:
header('location:Add_Record.php');
break;
case 2:
header('location:View_Record.php');
break;
case 3:
header('location:Modify_Record.php');
break;
case 4:
header('location:Delete_Record.php');
break;
default:
echo"Wrong Choice";
exit(0);
}
}
?>
</body>
</html>

2. DB.php – Connecting Database

<!-- 12. Connecting MySQL database with PHP-->


<!-- DB.php -- >
<!DOCTYPE html>
<html>
<head>
<title>Connecting to MySQL Database </title>
</head>
<body>
<?php
$host='localhost';
$username='root';
$password='';
$dbname = "Student";
$conn=mysqli_connect($host,$username,$password,$dbname);
if(!$conn)
{
die('Could not Connect MySQL Server:' .mysql_error());
}
?>
</body>
</html>
3. Add_Record.php – Insert Records Into MySQL Database
<!-- 12. PHP program to add new records into the MySQL Database -->
<!-- Add_Record.php -->
<!DOCTYPE html>
<html>
<head>
<title>Inserting Records into MySQL Database </title>
</head>
<body>
<h4><u>Student Mark Sheet</u></h4>
<form method="post">
<pre>
Enter Roll Number : <input type="Number" name="Rno" /><br>
Enter Student Name : <input type="Text" name="Name" /><br>
Enter Mark1 : <input type="Number" name="M1" /><br>
Enter Mark2 : <input type="Number" name="M2" /><br>
Enter Mark3 : <input type="Number" name="M3" /><br>
Enter Mark4 : <input type="Number" name="M4" /><br>
<input type="submit" name="submit" value="Add New Records"><br><br>
</pre>
</form>
<?php
include_once 'Db.php';
if(isset($_POST['submit']))
{
$Rno = $_POST['Rno'];
$Name = $_POST['Name'];
$M1 = $_POST['M1'];
$M2 = $_POST['M2'];
$M3 = $_POST['M3'];
$M4 = $_POST['M4'];
mysqli_query($conn,"INSERT INTO MARK_SHEET (Roll_No, Student_Name,
Mark1, Mark2, Mark3, Mark4) VALUES ('$Rno','$Name','$M1', '$M2', '$M3',
'$M4')") or die(mysqli_error());
echo "<p align=center>Record Added Successfully.</p>";
mysqli_close($conn);
header('Location: index.php') ;
}
?>
</body>
</html>
4. View_Record.php – Select Record from MySQL DB
<!-- 12. PHP Program to display records -- >
<!-- View_Record.php -->
<html>
<head>
<title> Retrieve Records</title>
</head>
<body>
<h4><u>Student Mark Sheet</u></h4>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Student";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection Failed: " . mysqli_connect_error());
}
$sql = "SELECT * From Mark_Sheet";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
// Output data of each row
echo " ";
while($row = mysqli_fetch_assoc($result))
{
echo "<pre>";
echo "Roll Number : " . $row["Roll_No"]. "<br>" ;
echo "Student Name : " . $row["Student_Name"]. "<br>";
echo "Mark1 : " . $row["MARK1"]. "<br>";
echo "Mark2 : " . $row["MARK2"]. "<br>";
echo "Mark3 : " . $row["MARK3"]. "<br>";
echo "Mark4 : " . $row["MARK4"]. "<br>";
echo "</pre>";
echo " ";
}
echo "<br>Fetched Data Successfully";
}
else
{
echo "No Records";
}
mysqli_close($conn);
?>
</body>
</html>
5. Modify_Record.php – Update Record into MySQL Database
<!-- 12. PHP program to modify the record into the MySQL Database -->
<!-- Modify_Record.php -->
<!DOCTYPE html>
<html>
<head>
<title>Updating a Record </title>
</head>
<body>
<h4><u>Updating a Record</u></h4>
<form method="post">
<pre>
Enter Roll Number : <input type="Number" name="Rno" /><br>
Enter Student Name : <input type="Text" name="Name" /><br>
Enter Mark1 : <input type="Number" name="M1" /><br>
Enter Mark2 : <input type="Number" name="M2" /><br>
Enter Mark3 : <input type="Number" name="M3" /><br>
Enter Mark4 : <input type="Number" name="M4" /><br><br>
<input type="submit" name="submit" value="Update Record"/><br><br>
</pre>
</form>
<?php
include_once 'Db.php';
if(isset($_POST['submit']))
{
$Rno = $_POST['Rno'];
$Name = $_POST['Name'];
$M1 = $_POST['M1'];
$M2 = $_POST['M2'];
$M3 = $_POST['M3'];
$M4 = $_POST['M4'];
$sql = "UPDATE Mark_Sheet SET Student_Name = '$Name', Mark1='$M1',
Mark2='$M2', Mark3='$M3', Mark4='$M4' WHERE Roll_No=$Rno";
$query = mysqli_query($conn,$sql);
if(!$query)
{
echo "Query does not work.".mysqli_error($conn);die;
}
else
{
echo "Record updated successfully";
}
header('Location: index.php') ;
}
?>
</body>
</html>
6. Delete_Record.php – Delete Record from MySQL Database
<!-- 12. PHP program to delete records from MySQL Database -- >
<!-- Delete_Record.php -->
<!DOCTYPE html>
<html>
<head>
<title>Deleting a Record </title>
</head>
<body>
<h4><u>Deleting a Record</u></h4>
<form method="post">
Enter the Roll Number to Delete: <input type="Number" name="Rno" /><br><br>
<input type="submit" name="submit" value="Delete Record">
<br><br>
</form>
<?php
include_once 'Db.php';
if(isset($_POST['submit']))
{
$Rno = $_POST['Rno'];
$sql = "DELETE FROM Mark_Sheet WHERE Roll_No='" . $Rno . "'";
if (mysqli_query($conn, $sql))
{
echo "Record deleted successfully";
}
else
{
echo "Error in deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: index.php') ;
}
?>
</body>
</html>
Output:
Fetched Data Successfully
Result:
Thus, the PHP code to create a student mark sheet table and Insert, delete and modify
records operations has been executed successfully.
13. PROGRAM TO RETRIEVE AND PRINT ALL THE E-MAIL ADDRESSES FROM
THE DOCUMENT email.xml USING XML

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>

You might also like