[go: up one dir, main page]

0% found this document useful (0 votes)
29 views50 pages

PHP Lab Manual Odd Sem Bca

The document outlines the Web Technology Practical course for III BCA A at Thiruthangal Nadar College, detailing its learning objectives and course outcomes focused on PHP and MySQL. It includes a list of practical programs students will implement, such as calculating sums, validating email addresses, and manipulating files. The document also specifies the lab setup, including hardware and software configurations.

Uploaded by

23bca118
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views50 pages

PHP Lab Manual Odd Sem Bca

The document outlines the Web Technology Practical course for III BCA A at Thiruthangal Nadar College, detailing its learning objectives and course outcomes focused on PHP and MySQL. It includes a list of practical programs students will implement, such as calculating sums, validating email addresses, and manipulating files. The document also specifies the lab setup, including hardware and software configurations.

Uploaded by

23bca118
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

THIRUTHANGALNADARCOLLEGE

(Belongs to the Chennaivazh Thiruthangal Hindu Nadar Uravinmurai Dharma Fund)


A Self Financing Co-Educational College of Arts & Science
Affiliated to the University of Madras
Re-accreditedat ‘B++’Grade by NAAC & An ISO 9001:2015 Certified Institution
Selavayal, Chennai, Tamil Nadu, India

Department: BCA
Subject Name: Web Technology Practical
Subject Code : 320C51
Class: III BCA A
Staff:S.Sangeetha

Learning Objectives: (for teachers: what they have to do in the class/lab/field)


• The objectives of this course are to have a practical understanding about
how to write PHP code to solve problems.
• Display and insert data using PHP and MySQL.
• Test, debug, and deploy web pages containing PHP and MySQL.
• It also aims to introduce practical session to develop simple applications using PHP
• andMySQL.

Course Outcomes: (for students: To know what they are going to learn)
1. On the completion of this laboratory course the students ought to
2. Obtain knowledge and develop application programs using Python.
3. Create dynamic Web applications such as content management, user registration, and
ecommerce using PHP and to understand the ability to post and publish a PHP website.
4. Develop a MySQL database and establish connectivity using MySQL

LAB II System & Software Available:


There are 50 systems(HP)installed in this Lab.
Configurations:
Processor: 12thgenintel®core™i5-12500
RAM: 8 GB
SSD: 512 GBNVME
Mouse: Optical Mouse
Operatingsystem: Windows 11 pro
Software: XAMP
List of Programs:

1. Write a PHP program whic

2. h adds up columns and rows of given table


3. Write a PHP program to compute the sum of first n given prime numbers
4. Write a PHP program to find valid an email address
5. Write a PHP program to convert a number written in words to digit.
6. Write a PHP script to delay the program execution for the given number of seconds.
7. Write a PHP script, which changes the colour of the first character of a word
8. Write a PHP program to find multiplication table of a number.
9. Write a PHP program to calculate Factorial of a number.
10. Write a PHP script to read a file, reverse its contents, and write the result back to a new file
11. Write a PHP script to look through the current directory and rename all the files
With extension .txt to extension .xtx.
12. Write a PHP script to read the current directory and return a file list sorted by
Last modification time. (using filemtime())
13. Write a PHP code to create a student mark sheet table. Insert, delete and modify records.
14. From a XML document (email.xml), write a program to retrieve and print all the email addresses
from the document using XML
15. From a XML document (tree.xml), suggest three different ways to retrieve the text
value 'John' using the DOM:
16. 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
INDEX

PAGE
S NO. DATE PROGRAM NO. SIGNATURE

1. Row, Column Sum of Matrix

2. Sum of First n prime numbers

3. Finding valid email address

4. Converting a number written in words to digit

5. Delaying the program execution

6. Changing the color of the first character of a word

7. Printing multiplication table

8. Factorial of given number

9. Reading the file, reversing its content and storing into


new file

10. Changing the File Extension

11. Sorted the files in current directory by last


modification time
12. Database Connectivity

13. Retrieving & printing all the e-mail addresses from


XML
14. Retrieving the text value using the DOM from XML

15. Retrieves the contents of MySQL tables as an XML


file using the DOM
Ex. No: 01

ROW COLUMN SUM OF MATRIX

Aim:

To write a php program to find the row and column sum of a matrix.

Algorithm:

Step 1: Start

Step 2: Get the number of rows and columns of matrix.

Step 3: Get the matrix elements.

Step 4: Calculated sum of row elements using function.

Step 5: Print sum of row values.

Step 6: Calculate sum of column elements using function.

Step 7: Print the sum of column values.

Step 8: Stop.
// 1.PHP program to find the sum of each row and column of a matrix
<?php

// Get the size m and n


$m=4;
$n=4;

// Function to calculate sum of each row function rowsum(&$arr)


{
$sum = 0;
$m=4;
$n=4;
echo "Finding Sum of each row:\n\n";

// finding the row sum


for ($i = 0; $i < $m; ++$i)
{
for ($j = 0; $j < $n; ++$j)
{

// Add the element


$sum = $sum + $arr[$i][$j];
}

// Print the row sum


echo "Sum of the row " . $i . " = " . $sum . "\n";

// Reset the sum


$sum = 0;
}
}

// Function to calculate sum of each column function column_sum(&$arr)


{
$sum = 0;
$m=4;
$n=4;
echo "\nFinding Sum of each column:\n\n";

// finding the column sum for ($i = 0; $i < $m; ++$i)


{
for ($j = 0; $j < $n; ++$j)
{

// Add the element


$sum = $sum + $arr[$j][$i];
}

// Print the column sum


echo "Sum of the column " . $i .
" = " . $sum . "\n";

// Reset the sum


$sum = 0;
}
}

// Driver code
$arr= array_fill(0, $m, array_fill(0, $n, NULL));

// Get the matrix elements


$x = 1;
$m=4;
$n=4;
for ($i = 0; $i < $m; $i++)
for ($j = 0; $j < $n; $j++)
$arr[$i][$j] = $x++;

// Get each row sum rowsum($arr);

// Get each column sum column_sum($arr);

?>
Output:

Result:

Thus the program has been executed successfully.


Ex. No: 02

SUM OF FIRST N PRIME NUMBERS

Aim:

To write a php program to find out the sum of first n prime numbers.

Algorithm:

Step 1: start

Step 2: get the number of prime numbers (n) to be added up.

Step 3: generated n prime numbers and store it in an array.

Step 4: add the prime elements of array to get sum.

Step 5: print the result.

Step 6: stop.
2. Sum of First n prime numbers
<?php
$max = 105000;
$arr = new SplFixedArray($max + 1); for ($i = 2; $i <= $max; $i++) {
$arr[$i] = 1;
}
for ($i = 2, $len = sqrt($max); $i <= $len; $i++) { if (!$arr[$i]) {
continue;
}
for ($j = $i, $len2 = $max / $i; $j <= $len2; $j++) {
$arr[$i * $j] = 0;
}
}
while (($line = trim(fgets(STDIN))) !== '0') {
$n = (int)$line;
$result = 0;
$cnt = 0;
for ($i = 2; $i <= $max; $i++) { if ($cnt === $n) {
break;
} elseif ($arr[$i]) {
$result += $i;
$cnt++;
}
}
echo "Sum of first ".$n." prime numbers:"; echo $result, PHP_EOL;
}
?>
Output:

Result:

Thus the program has been executed successfully.


Ex. No: 03

FINDING VALID EMAIL ADDRESS

Aim:

To write a php program to find a valid email address from the given list of email address.

Algorithm:

Step 1: Start

Step 2: Trim the unwanted spaces in email

Step 3: Filter the trimmed email into its components (user id, server, domain) and invalid it.

Step 4: Print the email address which is valid.


Step 5: Stop
//3.Finding valid email address

<?php
function valid_email($email)
{
$result = trim($email);
if (filter_var($result,FILTER_VALIDATE_EMAIL))
{
return "Valid Email";
}
else
{
echo "Invalid Email";
}
}
echo "abc@example.com\n";
echo valid_email("abc@example.com")."\n"; echo "abc#example.com\n";
echo valid_email("abc#example.com")."\n";
?>

Output:

Result:

Thus the program has been executed successfully.


Ex. No: 04

CONVERTING A NUMBER IN WORDS TO DIGIT

Aim:

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

Algorithm:

Step 1: Start

Step 2: Input the number which in words write elements as word separator.

Step 3: Letter each word in the input using the explode function in php.

Step 4: Represent each word separated as value.

Step 5: Using switch construct print the digit corresponding to the value obtained in step 4.

Step 6: Print the digit.

Step 7: Stop.
//4.program to convert a number written in words to digit

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

echo "zero three five six eight one\n";


echo word_digit("zero;three;five;six;eight;one")."\n"; echo "seven zero one\n";
echo word_digit("seven;zero;one")."\n";
?>
Output:

Result:

Thus the program has been executed successfully.


Ex. No: 05

DELAYING THE PROGRAM EXECUTION

Aim:

To write php program to delay the program execution.

Algorithm:

Step 1: Start

Step 2: Display the current time.

Step 3: Delay the program execution 5 sec by using sleep function.

Step 4: Now display the current time to check for the delay established.

Step 5: stop.
//5. delay the program execution for the given number of seconds

<?php
// current time
echo date('h:i:s') . "\n";
// sleep for 5 seconds sleep(5);
// wake up
echo date('h:i:s')."\n";
?>

Output:

Result:

Thus the program has been executed successfully.


Ex. No: 06

CHANGING THE COLOUR OF THE FIRST CHARACTER OF THE WORD

Aim:

To write a php program to change the colour of the first character of the word.

Algorithm:

Step 1: Start.

Step 2: Input the text, colour of whose first character to be changed.

Step 3: Search the first character from the input text using preg_replace function.

Step 4: Change the colour of first charact to red.

Step 5: Print the test.

Step 6: Stop.
//6. PHP script, which changes the colour of the first character of a word
<?php

// Text to replace
$text = "Geeks For Geeks";

// The preg_replace is used here to replace the


// color of first character of the word
$text = preg_replace('/(\b[a-z])/i',
'<span style="color:red;">\1</span>', $text);

// Display the text value echo $text


?>

Output:

Result:

Thus the program has been executed successfully.


Ex. No: 07

PRINTING THE MULTIPLICATION ON TABLE

Aim:

To write a php program to print the multiplication table.

Algorithm:

Step 1: Start

Step 2: Input the number (num) to print multiplication table.

Step 3: Initialize i to 1

Step 4: Calculate m = num * i and print "num" x "i" = "m"

Step 5: Increment i by 1

Step 6: Repeat step 4 and 5 until i becomes 10.

Step 7: Stop.
// 7.HTML program to print multiplication table- (mul.html)
<!DOCTYPE html>
<html>
<body>
<center>
<h1><b>
Program to print multiplication<br> table of any number in PHP
</b></h1>
<form method="POST" action="mul.php"> Enter a number:
<input type="text" name="number">
<input type="Submit"
value="Get Multiplication Table">
</body>
</html>
</form>
</center>

//PHP program to print multiplication table-(mul.php)


<?php if($_POST) {
$num = $_POST["number"];

echo nl2br("<p style='text-align: center;'> Multiplication Table of $num: </p>


");

for ($i = 1; $i <= 10; $i++) {


echo ("<p style='text-align: center;'>$num"
. " X " . "$i" . " = "
. $num * $i . "</p>
");
}
}
?>
Output:

Result:

Thus the program has been executed successfully.


Ex. No: 08

FACTORIAL OF A GIVEN NUMBER

Aim:

To write a php program to find the factorial of a given number.

Algorithm:

Step 1: Start.

Step 2: Input the number (num) to calculate factorial.

Step 3: Initialize factorial = 1.

Step 4: Assign x = num

Step 5: Calculate factorial = factorial x

Step 6: Decrement x by 1.

Step 7: Repeat step 5 & 6 until x becomes 1.

Step 8: Print factorial

Step 9: Stop.
// 8. Factorial of given number
<?php
$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>

Output:

Result:

Thus the program has been executed successfully.


Ex. No: 09

Reversing the content of a file

Aim:

To write a php program to reverse the content of a file.

Algorithm:

Step 1: Start

Step 2: Get the file to reverse its content.

Step 3: Open the given file and get its content using file_get_contents function.

Step 4: Reverse the content using strrev function.

Step 5: Append a new content using file_put_contents from its current location.

Step 6: Print the current content of a file.

Step 7: Stop.
// 9 . Reading the file,reversing its content and storing into new file

<?php
$file = 'sample.txt';
$file1='sample1.txt';

// Open the file to get existing content


$current = file_get_contents($file);

//reversing the contents of file


$current = strrev($current);

// Append a new person to the file


//$current .= "John Smith\n";

// Write the contents back to the file file_put_contents($file1, $current);


$current=file_get_contents($file1);
echo "After reversing the file content \n"; echo $current;
?>

Output:

Result:

Thus the program has been executed successfully.


Ex. No: 10

CHANGING THE FILE EXTENSION

Aim:

To write a php program to change the file extension.

Algorithm:

Step 1: Start

Step 2: Get the directory name & extension of file to be changed through a webpage.

Step 3: If the dir is empty, generate error message and stop.

Step 4: Scan the files under the given directory and collect it in an array.

Step 5: Each files in the array, do the steps 6 to 9, if it is not root directory.

Step 6: New file = dir name + ‘/’ + filename

Step 7: Cut the path into extension of new file if it is text.

Step 8: Find the sub str of the new file starting from first character until ‘.’.

Step 9: Append it with extension to be replaced print the new file name.

Step 10: Stop.


//10.To change every file name with extention txt into xtx in
//the directory dir

<html>
<body>
<h2>Change the Extension of all the files in a directory</h2>
<br>
<form method ="post action="<?php echo $_SERVER['PHP_SELF'];
?>">
Enter the Directory (. for current directory)<input type="text" name="dir" size="50"><br>
Enter the new file extension<input type="text" name="ext" size="20"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>

<?php
if (isset($_POST['submit']) && trim($_POST['dir']) != '')
{
$dirname = $_POST['dir'];
$newextension = $_POST['ext'];
$files = scandir($dirname); foreach($files as $file)
{
if(trim($dirname) != ".")
$newfile = $dirname."/".$file; else "<br>";
if(pathinfo ($newfile, PATHINFO_EXTENSION)=="text")
{
echo "<br>Old File:".$newfile;
$file_Woext = substr($newfile, 0,strrpos($newfile, ".")); rename($newfile,$file_Woext.".".$newextension);
echo "<br>New File:".$file_Woext.".".$newextension;
}
}
}
if(isset($_POST['submit']) && trim($_POST['dir']) == '')
{

echo "<br>Directory name can not be empty!";


}
?>
</body>
</html>
OUTPUT:

Result:

Thus the program has been executed successfully.


Ex. No: 11

SORTING THE FILES IN CURRENT DIRECTORY BY ITS LAST MODIFICATION


TIME

Aim:

To write a php program to sort the files in the current directory by its last modification
time.

Algorithm:

Step 1: Start.

Step 2: Get the current directory to list the files.

Step 3: Validate the dir name.

Step 4: Get the sub directory and files using glob function in an array by its last modification
time.

Step 5: Print the files in the sorted.

Step 6: Order the sorted list of files.

Step 7: Stop.
//11. Write a PHP script to read the current directory and //return a file list sorted by last modification
time. (using filemtime())
<html>
<body>
<h2>List the files in the given directory based on the Modification time</h2>
<br>
<form method="post action="<?php echo $_SERVER['PHP_SELF'];?>"> Enter the Directory (.for current
directory)<input type="text" name="dir' size="50"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>

<?php
if(isset($_POST['submit'])&& trim($_POST['dir']) !='')
{
$dirname = $_POST['dir']; if($dirname == ".")
{
$dirpath = '*';
}
else
{
$dirpath = $dirname.'/*';
}
foreach (glob($dirpath) as $filename)
{
$filesarrray[filemtime($filename)]=basename($filename);
}
echo "<br>Original Files:<br>"; foreach($filesarray as $modificationtime => $file)
{

echo "$Modificatin Time=" .$modification .", Filename=" .$file; echo"<br>";


}
ksort($filesarray);
echo "<br>Sorted Files:<br>"; foreach($filesarray as $modificationtime => $file)
{
echo "Modification Time=" .$modificationtime .",Filename=" .$file; echo"<br>";
}
}
if(isset($_POST['submit'])&& trim$_POST['dir']) =='')
{
echo "<br>Directory name can not be empty!";
}
?>
</body>
</html>
OUTPUT:

Result:

Thus the program has been executed successfully.


Ex. No: 12

DATABASE CONNECTIVITY

Aim:

To write a php program to connect to a mysql database, insert, view, update & delete the records
from the data base.

Algorithm:

Step 1: Start.

Step 2: Connect to student marks database.

Step 3: If not, generate error message and stop.

Step 4: Create webpage to display to options for inserting, viewing, editing, deleting the records
from the marksheet table.

Step 5: Write coding for inserting, viewing, editing & deleting records using mysqlite extension
commands in php.

Step 6: Stop.
//12. Students marksheet
// dashboard.php
<?php
//require('db.php');
//include("auth.php"); include("db.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dashboard - Secured Page</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome to Dashboard.</p>
<p><a href="index.php">Home</a><p>
<p><a href="insert.php">Insert New Record</a></p>
<p><a href="view.php">View Records</a><p>
<p><a href="logout.php">Logout</a></p>
</div>
</body>
</html>

// db.php
<?php
$servername = "localhost";
$username = "system";
$password = "tnc";
$db="studentmarks";

// Create connection
$con = new mysqli($servername, $username, $password,$db);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully to the database ---> ".$db;
?>
//insert.php

<?php require('db.php');
//include("auth.php");
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$trn_date = date("Y-m-d H:i:s");
$regno =$_REQUEST['regno'];
$name =$_REQUEST['name'];
$sem = $_REQUEST['sem'];
$web = $_REQUEST['web'];
$weblab= $_REQUEST['weblab'];
$physics = $_REQUEST['physics'];
$submittedby = $_SESSION["username"];
$ins_query="insert into marksheet (`regno`,`name`,`sem`,`web`,`weblab`,`physics`) values
('$regno','$name','$sem','$web','$weblab','$physics')"; mysqli_query($con,$ins_query) or
die(mysql_error());
$status = "New Record Inserted Successfully.
</br></br><a href='view.php'>View Inserted Record</a>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert New Record</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a>
| <a href="view.php">View Records</a>
| <a href="logout.php">Logout</a></p>
<div>
<h1>Insert New Record</h1>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="regno" placeholder="Enter regno" required /></p>
<p><input type="text" name="name" placeholder="Enter name" required
/></p>
<p><input type="text" name="sem" placeholder="Enter sem" required
/></p>
<p><input type="text" name="web" placeholder="Enter web" required
/></p>
<p><input type="text" name="weblab" placeholder="Enter weblab" required /></p>
<p><input type="text" name="physics" placeholder="Enter phy marks" required /></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#FF0000;"><?php echo $status; ?></p>
</div>
</div>
</body>
</html>

//view.php
<?php require('db.php');
//include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="index.php">Home</a>
| <a href="insert.php">Insert New Record</a>
| <a href="logout.php">Logout</a></p>
<h2>View Records</h2>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>Reg No</strong></th>
<th><strong>Name</strong></th>
<th><strong>Sem</strong></th>
<th><strong>Web</strong></th>

<th><strong>Web Lab</strong></th>
<th><strong>Physics</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
<tbody>
<?php
$count=1;
$sel_query="Select * from marksheet ORDER BY regno desc;";
$result = mysqli_query($con,$sel_query); while($row = mysqli_fetch_assoc($result)) { ?>

<td align="center"><?php echo $row["regno"]; ?></td>


<td align="center"><?php echo $row["name"]; ?></td>
<td align="center"><?php echo $row["sem"]; ?></td>
<td align="center"><?php echo $row["web"]; ?></td>
<td align="center"><?php echo $row["weblab"]; ?></td>
<td align="center"><?php echo $row["physics"]; ?></td>
<td align="center">
<a href="edit.php?id=<?php echo $row["regno"]; ?>">Edit</a>
</td>
<td align="center">
<a href="delete.php?regno=<?php echo $row["regno"]; ?>">Delete</a>
</td>
</tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>

//edit.php
<?php require('db.php');
//include("auth.php");
$regno=$_REQUEST['regno'];
$query = "SELECT * from marksheet where regno='".$regno."'";
$result = mysqli_query($con, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update Record</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p><a href="dashboard.php">Dashboard</a>
| <a href="insert.php">Insert New Record</a>
| <a href="logout.php">Logout</a></p>
<h1>Update Record</h1>
<?php
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$trn_date = date("Y-m-d H:i:s");
$regno=$_REQUEST['regno'];
$name =$_REQUEST['name'];
$sem =$_REQUEST['sem'];
$web =$_REQUEST['web'];
$weblab =$_REQUEST['weblab'];
$physics =$_REQUEST['physics'];
//$submittedby = $_SESSION["username"];
$update="update marksheet set regno='".$regno."',name='".$name."', sem='".$sem."', web='".$web."',
weblab='".$weblab."',physics='".$physics."' where regno='".$regno."'"; mysqli_query($con, $update) or
die(mysqli_error());
$status = "Record Updated Successfully. </br></br>
<a href='view.php'>View Updated Record</a>"; echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
?>
<div>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="regno" placeholder="Enter Regno" required value="<?php echo
$row['regno'];?>" /></p>
<p><input type="text" name="name" placeholder="Enter name" required value="<?php echo
$row['name'];?>" /></p>
<p><input type="text" name="sem" placeholder="Enter Sem" required value="<?php echo
$row['sem'];?>" /></p>

<p><input type="text" name="web" placeholder="Enter Web" required value="<?php echo


$row['web'];?>" /></p>
<p><input type="text" name="weblab" placeholder="Enter weblab" required value="<?php echo
$row['weblab'];?>" /></p>
<p><input type="text" name="physics" placeholder="EnterPhysics" required value="<?php echo
$row['physics'];?>" /></p>
<p><input name="submit" type="submit" value="Update" /></p>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
//delete.php
<?php require('db.php');
$regno=$_REQUEST['regno'];
$query = "DELETE FROM marksheet WHERE regno=$regno";
$result = mysqli_query($con,$query) or die ( mysqli_error());
$status = " Record deleted Successfully.
//</br></br><a href='view.php'>View deleted Record</a>"; header("Location: view.php");
?>

Output:
Result:

Thus the program has been executed successfully.


Ex. No: 13

COLLECTING EMAIL ADDRESSES FROM XML

Aim:

To write a php program to collect all e-mail address from the given xml file.

Algorithm:

Step 1: Start

Step 2: Create an xml file having employee details including email address of an organization.

Step 3: Local the xml file into php using simple xml_load_file function.

Step 4: If not, generate error message and stop called error_name and email address elements
from the loaded xml file into an array.

Step 5: Display the array elements one by one.

Step 6: Stop.
//13. From a XML document (email.xml), write a program to retrieve and print all the e-mail addresses
from the document using XML

//email.xml
<?xml version='1.0'?>
<employees>
<employee >
<empid>101</empid>
<name>John</name>
<email>john@example.com</email>
<address>
<street>3201 Glendale Avenue</street>
<city>Los Angeles</city>
<state>CA</state>
</address>
</employee>
<employee >
<empid>102</empid>
<name>Mike</name>
<email>mike@example.com</email>
<address>
<street>781 Stroop Hill Road</street>
<city>Duluth</city>
<state>GA</state>
</address>
</employee>
</employees>

//email.php
<?php
$xml=simplexml_load_file("email.xml") or die ("Unable to load XML"); echo "There are ".count ($xml-
>employee)." employees working in this company.";
echo "<br>Employee ID and their E-Mail addresses are:"; foreach ($xml->employee as $emp)
{
echo "<br>". $emp->empid; echo "-". $emp->email;
}
?>
output:

Result:

Thus the program has been executed successfully.


Ex. No: 14

DIFFERENT WAYS OF RETRIEVING THE GIVEN TEXT VALUE USING DOM

Aim:

To write a php program to retrieving the text value ‘john’ using the dom from the xml file
in 3 different methods.

Algorithm:

Step 1: Start.

Step 2: Initialise a new dom document object.

Step 3: Load the john xml file into the dom object.

Step 4: Using the tree navigation methods of node method collect the value of ‘john’ by
processing the node one by one and print it.

Step 5: Using the get elements by tag name method retrieve the ‘john’ value and print it.

Step 6: Using the “get elements by tag name” method, retrieve john value using it parent tag.

Step 7: Stop.
//14. From a XML document (tree.xml), suggest three different ways to retrieve the text value 'John'
using the DOM:

//tree.xml

<?xml version='1.0'?>
<tree>
<person type="grandpa" />
<person type="grandma" />
<children>
<person type="pa" />
<person type="ma" />
<children>
<person type="bro">
<name>John</name>
</person>
<person type="sis">
<name>Jane</name>
</person>
</children>
</children>
</tree>

//tree.php

<?php
// initialize new DOMDocument
$doc = new DOMDocument();
// disable whitespace-only text nodes
$doc->preserveWhiteSpace = false;
// read XML file
$doc->load('tree.xml');
// output: 'John'
echo $doc->firstChild->childNodes->item(2)->childNodes
->item(2)->childNodes->item(0)->childNodes->item(0)
->childNodes->item(0)->nodeValue;
// output: 'John'
echo $doc->getElementsByTagName('name')->item(0)->nodeValue;
// output: 'John'
echo $doc->getElementsByTagName('person')->item(4)
->childNodes->item(0)->nodeValue;
?>
Output:

Result:

Thus the program has been executed successfully.


Ex. No: 15

CONVERTING MYSQL TABLE RECORDS INTO XML FILE USING DOM

Aim:

To write a php program to connect to a mysql database of students and retrieve the
student records as xml file using dom.

Algorithm:

Step 1: Start

Step 2: Connect to student marks mysql db

Step 3: If not, generate error message and stop.

Step 4: Create a new dom document object.

Step 5: Create an empty xml file students.xml into dom object

Step 6: Retrieve the records into the connection object using the mysql_query function
necessary.

Step 7: Create root elements ‘students’.

Step 8: Start appending field in the records to student element by create element & append child
records.

Step 9: Write the students & values into student xml_files using method of dom object.

Step 10: Stop.


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

<?php
$con=mysqli_connect("localhost","system","tnc","studentmarks"); if (mysqli_connect_errno()) die ("Error
connecting db: ".mysqli_connect_error());
echo "connected to DB";
$domdoc=new DOMDocument();
$domdoc->encoding='utf-8';
$domdoc->xmlVersion='1.0';
$domdoc->formatOutput= true;
$xmlfilename ='students.xml';
$root=$domdoc->createElement('students');
$query="select * from student;";
$result =mysqli_query($con,$query); while ($row=mysqli_fetch_assoc($result))
{
echo "<br>".$row["regno"]." : ".$row["name"]." :".$row["age"]." : ".$row
["doorno"]." : ". $row["street"].": ".$row["city"];
$student=$domdoc->createElement('student');
$root->appendChild($student);

$regno= $domdoc->createElement('regno', $row["regno"]);


$student->appendChild($regno);

$name= $domdoc->createElement('name', $row["name"]);


$student->appendChild($name);
$age= $domdoc->createElement('age', $row["age"]);
$student->appendChild($age);
$doorno =$domdoc->createElement('doorno', $row["doorno"]);
$student->appendChild ($doorno);
$street=$domdoc->createElement('street', $row["street"]);
$student->appendChild($street);
$city= $domdoc->createElement('city', $row["city"]);
$student->appendChild($city);
}
$domdoc->appendChild($root);
$domdoc->save($xmlfilename);
echo "<br>$xmlfilename has been successfully created"; mysqli_close ($con);
?>
output:

Result:

Thus the program has been executed successfully.

You might also like