0% found this document useful (0 votes)
50 views31 pages

PHP Scripts for Calculator and XML Handling

The document describes a PHP program that creates a student table in a database and uses AJAX to select and print details of a student based on their standard. It connects to the database, gets the standard parameter from a GET request, queries the student table for that standard, and returns the results.

Uploaded by

Jaid Bagwan
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)
50 views31 pages

PHP Scripts for Calculator and XML Handling

The document describes a PHP program that creates a student table in a database and uses AJAX to select and print details of a student based on their standard. It connects to the database, gets the standard parameter from a GET request, queries the student table for that standard, and returns the results.

Uploaded by

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

Name: Pachangare Rushikesh Haribhau Roll No: 4334

Exam Seat No: Date:06/01/2024

[Link] a PHP script to create a simple calculator that can accept two numbers and
perform operations like, subtract, multiplication. (Use the concept of class)
PROGRAM:
<?php
class Calculator
{
private $a, $b;
public function __construct( $a1, $b1 )
{
$this->a = $a1;
$this->b = $b1;
}
public function add()
{
$c= $this->a + $this->b;
echo "the addition is ".$c;
echo "<br>";
}
public function sub()
{
$c= $this->a-$this->b;
echo "the substraction is ".$c;
echo "<br>";
}
public function mul()
{
$c=$this->a*$this->b;
echo "the multiplication is ".$c;
echo "<br>";
}
public function div()
{
$c=$this->a/$this->b;
echo "the division is ".$c;
echo "<br>";
}
}
$calc = new calculator(12, 6);
$calc->add();
$calc->sub();
$calc->mul();
$calc->div();
?>

OUTPUT:

--------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau Roll No: 4334
Exam Seat No: Date:10/01/2024

[Link] a PHP script to create [Link] file which contains student roll no, address,
college and course. Print student details of specific a course in tabular format after
accepting course as input.
PROGRAM:
<?php
function createStudentXML($students) {
$xml = new SimpleXMLElement('<students/>');
foreach ($students as $student) {
$studentNode = $xml->addChild('student');
$studentNode->addChild('rollno', $student['rollno']);
$studentNode->addChild('name', $student['name']);
$studentNode->addChild('address', $student['address']);
$studentNode->addChild('college', $student['college']);
$studentNode->addChild('course', $student['course']);
}
$xml->asXML('[Link]');
}
function printStudentsByCourse($course) {
if (file_exists('[Link]')) {
$xml = simplexml_load_file('[Link]');
$students = $xml->xpath("//student[course='$course']");
echo "<table border='1'>";
echo "<tr><th>Roll
No</th><th>Name</th><th>Address</th><th>College</th><th>Course</th></tr>";
foreach ($students as $student) {
echo "<tr>";
echo "<td>{$student->rollno}</td>";
echo "<td>{$student->name}</td>";
echo "<td>{$student->address}</td>";
echo "<td>{$student->college}</td>";
echo "<td>{$student->course}</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "The file [Link] does not exist.";
}
}
$students = [
['rollno' => '105', 'name' => 'Rushikesh Pachangare', 'address' => 'Indapur', 'college' =>
'ASC College', 'course' => 'Computer Science'],
// ... Add more students here
];
createStudentXML($students);
$course = 'Computer Science'; // This should be replaced with the actual user input
printStudentsByCourse($course);
?>

OUTPUT:

----------------------------------------------------------------------------------------------------------
Remark: Sign:
Name: Pachangare Rushikesh Haribhau Roll No: 4334
Exam Seat No: Date:17/01/2024

Q3. Write a PHP script to determine the introspection for examining classes and object.
(Use function get_declared_classes(),get_class_methods () and get_class_vars()).
PROGRAM:
<?php
class myclass
{
public $a;
public $b = 10;
public $c = 'ABC';

function myfun1()
{
}
function myfun2()
{
}
}
$class = get_declared_classes();
foreach ($class as $cname) {
if ($cname == 'myclass') { // Check if the class is 'myclass'
echo "$cname<br>";

echo "<br>class methods are:<br>";


$m = get_class_methods('myclass');
foreach ($m as $mname) {
echo "$mname<br>";
}
echo "<br>class variables are:<br>";
$cp = get_class_vars('myclass');
foreach ($cp as $cpname => $v) {
echo "$cpname:$v<br>";
}
}
}
?>

OUTPUT:

-----------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau
Roll No: 4334
Exam Seat No: Date:28/01/2024

Q4. Write a script t solve following questions (Use “[Link]” file)


I. Create a Dom Document object and load this XML file.
II. Get the outputof this Document to the Browser.
III. Save this [.XML] document in another format .e . in[.doc]
Write a XML script to print the names of the student present in “[Link]” file.
PROGRAM:
[Link]
<?xml version='1.0' encoding ='UTF-8' ?>
<students>
<student>
<rollno>1</rollno>
<name>rushikesh</name>
<class>fy</class>
</student>
<student>
<rollno>2</rollno>
<name>arif</name>
<class>sy</class>
</student>
<student>
<rollno>3</rollno>
<name>vijay</name>
<class>Ty</class>
</student>
</students>

[Link]
<?php
$doc=new DOMDocument();
$doc->load("[Link]");
$name=$doc->getElementsByTagName("name");
echo "Students Names are:";
foreach($name as $val)
{
echo "<br>".$val->textContent;
}
?>

OUTPUT:

------------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau Roll No: 4334
Exam Seat No: Date:01/02/2024

Q5. Write a script to create “[Link]” file with multiple elements as shown below:
<CricketTeam>
<Team country= “Australia”>
<player>_________</player>
<runs>___________</runs>
<wicket>__________</wicket>
</Team>
</CricketTeam>
Write a script to add multiple elements in “[Link]” file of category, country=
“India”.
PROGRAM:
[Link]
<?xml version="1.0" encoding="utf-8" ?>
<cricketTeam>
<team country="Australia">
<player>rushikesh</player>
<runs>1500</runs>
<wicket>15</wicket>
</team>
<team country="India">
<player>sachin</player>
<runs>500</runs>
<wicket>5</wicket>
</team>
<team country="India">
<player>Kolhi</player>
<runs>1500</runs>
<wicket>55</wicket>
</team>
</cricketTeam>
[Link]
<?php
$xml = simplexml_load_file('[Link]');
echo '<h2> Information</h2>';
$list = $xml->team;
for ($i = 0; $i < count($list); $i++)
{
echo '<b>country is:</b> ' . $list[$i]->attributes()->country ;
echo "<br>";
echo ' player Name: ' . $list[$i]->player;
echo "<br>";
echo 'runs: ' . $list[$i]->runs ;
echo "<br>";
echo 'wickets are : ' . $list[$i]->wicket ;
echo "<br>";
echo "<br>";
}
?>
OUTPUT:

---------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau Roll No: 4334
Exam Seat No: Date:05/02/2024

Q6. Define a class Employee having private members – id, name, department, salary.
Define parameterized constructor. Create a subclass called “Manager” with private
member bonus. Create 3 objects f the Manager class and display the details of the
manager having the maximum total salary (salary + bonus).
PROGRAM:
<?php
class Employee
{
private $eid,$ename,$edept,$sal;
function __construct($a,$b,$c,$d)
{
$this->eid=$a;
$this->ename=$b;
$this->edept=$c;
$this->sal=$d;
}
public function getdata()
{
return $this->sal;
}
public function display()
{
echo $this->eid."</br>";
echo $this->ename."</br>";
echo $this->edept."</br>";
}
}
class Manager extends Employee
{
private $bonus;
public static $total1=0;
function __construct($a,$b,$c,$d,$e)
{
parent::__construct($a,$b,$c,$d);
$this->bonus=$e;
}
public function max($ob)
{
$sal=$this->getdata();
$total=$sal+$this->bonus;
if($total>self::$total1)
{
self::$total1=$total;
return $this;
}
else
{
return $ob;
}
}
public function display()
{
parent::display();
echo self::$total1;
}
}
$ob=new Manager(0,"ABC","",0,0);
$ob1=new Manager(1,"raj","computer",20000,2000);
$ob=$ob1->max($ob);
$ob2=new Manager(2,"yash","computer",32000,2500);
$ob=$ob2->max($ob);
$ob3=new Manager(3,"rushi","computer",40000,3000);
$ob=$ob3->max($ob);
$ob4=new Manager(4,"ajay","computer",28000,4000);
$ob=$ob4->max($ob);
$ob5=new Manager(5,"vijay","computer",28000,5000);
$ob=$ob5->max($ob);
$ob->display();
?>

OUTPUT:

---------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau
Roll No: 4334
Exam Seat No: Date:12/02/2024

Q7. Create student table as follows:


Student(sno , sname , standard, Marks, per).
Write AJAX script to select the student name and print the student’s details of
particular standard.
PROGRAM:
get_student_details.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stud";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['standard']) && !empty($_GET['standard'])) {
$standard = $_GET['standard'];
$sql = "SELECT * FROM Students WHERE standard = $standard";
$result = $conn->query($sql);
if ($result !== false && $result->num_rows > 0) {
echo "<table border='1'>";
echo "<tr><th>Student Name</th><th>Marks</th><th>Percentage</th></tr>";
while($row = $result->fetch_assoc()) {
echo
"<tr><td>".$row['sname']."</td><td>".$row['Marks']."</td><td>".$row['per']."</td></tr>";
}
echo "</table>";
} else {
echo "No students found for standard $standard";
}
} else {
echo "Standard parameter is missing or empty";
}

$conn->close();
?>
student_details.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Details</title>
<script>
function getStudentDetails() {
var standard = [Link]("standard").value;
var xmlhttp = new XMLHttpRequest();
[Link] = function() {
if ([Link] == 4 && [Link] == 200) {
[Link]("student_details").innerHTML = [Link];
}
};
[Link]("GET", "get_student_details.php?standard=" + standard, true);
[Link]();
}
</script>
</head>
<body>
<h2>Select Student Details by Standard</h2>
<label for="standard">Select Standard:</label>
<select name="standard" id="standard">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<!-- Add more options as needed -->
</select>
<button onclick="getStudentDetails()">Get Details</button>
<div id="student_details"></div>
</body>
</html>

OUTPUT:

-----------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau Roll No: 4334
Exam Seat No: Date:22/02/2024

Q8. Consider the following entities and their relationships


Movie(movie no, movie_name, release_year)
Actor(actor no, name)
Create a RDB in 3 NF. With using three radio buttons (accept, insert, update)
Write an AJAX script to accept actor name and display names of movies nwhich he has
acted.
PROGRAM:
[Link]
<?php
// [Link]
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "movies_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve actor name from GET request
if(isset($_GET['actorName'])) {
$actorName = $_GET['actorName'];
// Prepare SQL statement to retrieve movies by actor name
$sql = "SELECT m.movie_name
FROM Movie m
INNER JOIN Cast c ON m.movie_no = c.movie_no
INNER JOIN Actor a ON c.actor_no = a.actor_no
WHERE [Link] = '$actorName'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo $row["movie_name"] . "<br>";
}
} else {
echo "0 results";
}
} else {
echo "Actor name not provided.";
}

$conn->close();
?>
[Link]
<!-- [Link] -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Movies by Actor</title>
</head>
<body>
<form action="[Link]" method="GET">
<label for="actor-name">Actor Name:</label>
<input type="text" id="actor-name" name="actorName">
<input type="submit" value="Submit">
</form>
<div id="movie-list">
<!-- Movies will be displayed here -->
</div>
</body>
</html>

OUTPUT:

Remark: Sign:
-----------------------------------------------------------------------------------------------------------
Name: Pachangare Rushikesh Haribhau
Roll No: 4334
Exam Seat No: Date:04/02/2024

Q9. Write an AJAX code to print the content of “[Link]” on clicking in fetch button.
The data fetch from the server using AJAX Technique.
PROGRAM:
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch File Content</title>
</head>
<body>
<form action="[Link]" method="GET">
<input type="submit" value="Fetch File Content">
</form>
<div id="file-content">
<?php include '[Link]'; ?>
</div>
</body>
</html>
[Link]
<?php
$file = "[Link]";
if(file_exists($file)) {
$fileContent = file_get_contents($file);
echo nl2br($fileContent); // Display file content with line breaks
} else {
echo "File not found.";
}
?>
OUTPUT:

--------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau
Roll No: 4334
Exam Seat No: Date:15/03/2024

Q10. Write AJAX program to carry out validation for a username entered in textbox . If
the textbox is blank,
Print ‘Enter username’. If the number of characters is less than three, print ‘Username
is to sort’. If value entered is appropriate the print ‘Valid username’.
PROGRAM:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Username Validation</title>
<script>
function validateUsername() {
var username = [Link]("username").value;
var outputMsg = [Link]("outputMsg");
// Check if the username is blank
if ([Link]() === "") {
[Link] = "Enter username";
return;
}
// Check if the username is too short
if ([Link] < 3) {
[Link] = "Username is too short";
return;
} // If the username passes both checks, show "Valid username"
[Link] = "Valid username";
}

function clearMessage() {
// Clear the output message when the user starts typing again
[Link]("outputMsg").innerHTML = "";}
</script>
</head>
<body>
<h2>Username Validation</h2>
<input type="text" id="username" oninput="clearMessage()">
<button onclick="validateUsername()">Validate</button>
<p id="outputMsg"></p>
</body>
</html>
OUTPUT:

----------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau
Roll No: 4334
Exam Seat No: Date:18/03/2024

Q11. Create a XML file which gies details of books available in “Pragati Bookstore ”
from following categeories.
1. Yoga.
2. Story.
3. Echnical.
And elements in each categeory are in the following format
<Book_title>-------------</Book_title>
<Book_author>---------</Book_author>
<Book_price>-----------</Book_price>
</Book>
Save the file s “[Link]”
PROGRAM:
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<bookstore name="Pragati Bookstore">
<category name="Yoga">
<book>
<title>The Heart of Yoga</title>
<author>T.K.V. Desikachar</author>
<price>15.99</price>
</book>
<book>
<title>Light on Yoga</title>
<author>B.K.S. Iyengar</author>
<price>12.50</price>
</book>
</category>
<category name="Story">
<book>
<title>The Alchemist</title>
<author>Paulo Coelho</author>
<price>10.99</price>
</book>
<book>
<title>Harry Potter and the Philosopher's Stone</title>
<author>J.K. Rowling</author>
<price>14.99</price>
</book>
</category>
<category name="Technical">
<book>
<title>Clean Code: A Handbook of Agile Software Craftsmanship</title>
<author>Robert C. Martin</author>
<price>25.00</price>
</book>
<book>
<title>Design Patterns: Elements of Reusable Object-Oriented Software</title>
<author>Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides</author>
<price>30.00</price>
</book>
</category>
</bookstore>

[Link]
<?php
// Function to fetch books by title
function getBooksByTitle($xml, $title) {
$foundBooks = [];
foreach ($xml->category as $category) {
foreach ($category->book as $book) {
if (strcasecmp($book->title, $title) == 0) {
$foundBooks[] = [
'title' => (string)$book->title,
'author' => (string)$book->author,
'price' => (float)$book->price
];
}
}
}
return $foundBooks;}
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Load the XML file
$xml = simplexml_load_file('[Link]');
// Check if XML file is loaded successfully
if ($xml === false) {
die('Error loading XML file.');
}
// Get the book title from the form input
$searchTitle = $_POST['search'];
// Search for books by title
$foundBooks = getBooksByTitle($xml, $searchTitle);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Search</title>
</head>
<body>
<h2>Search for Books</h2>
<form method="post">
<input type="text" name="search" placeholder="Enter book title">
<button type="submit">Search</button>
</form>

<?php
// Display search results
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($foundBooks)) {
echo "<h3>Books found with title '$searchTitle':</h3>";
foreach ($foundBooks as $book) {
echo "<p>Title: {$book['title']}</p>";
echo "<p>Author: {$book['author']}</p>";
echo "<p>Price: {$book['price']}</p>";
echo "<hr>";
}
} else {
echo "<p>No books found with title '$searchTitle'.</p>";
}
}
?>
</body>
</html>
OUTPUT:

----------------------------------------------------------------------------------------------------------

Remark: Sign:
Name: Pachangare Rushikesh Haribhau
Roll No: 4334
Exam Seat No: Date:21/03/2024

Q12. Create an application that reads “[Link]” file into simple XML object .
Display attributes and elements.
(Hint: Use simple_xml_load_fle() function)
PROGRAM:
create_xml.php
<?php
// Create a new XML document
$xml = new DOMDocument('1.0', 'utf-8');
// Create the root element
$sports = $xml->createElement('sports');
$xml->appendChild($sports);
// Create some sample sports and their attributes
$sport1 = $xml->createElement('sport');
$sport1->setAttribute('name', 'Football');
$sport1->setAttribute('type', 'Team');
$sport2 = $xml->createElement('sport');
$sport2->setAttribute('name', 'Tennis');
$sport2->setAttribute('type', 'Individual');
$sport3 = $xml->createElement('sport');
$sport3->setAttribute('name', 'Basketball');
$sport3->setAttribute('type', 'Team');

// Append sports to the root element


$sports->appendChild($sport1);
$sports->appendChild($sport2);
$sports->appendChild($sport3);

// Save the XML document


$xml->formatOutput = true;
$xml->save('[Link]');
echo "XML file created successfully.";
?>
[Link]
<?xml version="1.0" encoding="utf-8"?>
<sports>
<sport name="Football" type="Team"/>
<sport name="Tennis" type="Individual"/>
<sport name="Basketball" type="Team"/>
</sports>

OUTPUT:

------------------------------------------------------------------------------------------------------------

Remark: Sign:

Common questions

Powered by AI

The DOMDocument class provides a comprehensive suite of methods for XML manipulation, including the ability to traverse the full XML tree, modify the structure, and apply complex operations. This makes it suitable for tasks that require detailed control over the document structure. On the other hand, SimpleXML offers a more straightforward and efficient interface for parsing and querying XML documents when complex modifications aren't needed, offering simplicity and ease of use for common tasks .

Subclasses in PHP, achieved through inheritance, allow new classes to extend existing functionality of parent classes, thus promoting code reusability. By inheriting properties and methods, subclasses can implement or override functions, reducing redundancy and enhancing flexibility in code changes. This modular approach simplifies maintenance, as changes to common functionality only need to be made in the superclass, and the subclasses automatically inherit the updated behavior .

AJAX improves user experience by enabling the retrieval of student data dynamically without the need to reload the entire webpage. When users select a standard, an AJAX request fetches and displays the relevant student information quickly, providing a seamless and interactive experience. This reduces waiting time and server load, resulting in a more responsive application .

The function get_class_vars() in PHP returns the default properties of a class, allowing developers to perform introspection by examining the class's internal content without knowing its implementation details. This function supports encapsulation by keeping the class properties private while still providing a controlled means of inspecting them, thus maintaining the integrity of the class's encapsulated data .

The DOMDocument object in PHP represents an XML document and offers a set of methods to manipulate its structure and content programmatically. By using the XPath query mechanism, developers can traverse the XML document and locate specific data efficiently. XPath allows selection of nodes by complex queries, which can execute operations like searching for specific nodes based on attributes, thus providing flexible and efficient XML data handling .

XML offers a flexible and platform-independent way to store and share data. It allows easy data interchange between different systems, and modifications to the XML file structure do not affect existing data applications as significantly as changes in database schemas might. Furthermore, XML files are easily readable by humans and can be used across various programming environments. However, unlike databases, XML lacks inbuilt query optimization and complex transaction handling capabilities .

Using classes in a PHP script for a calculator application organizes the code into a modular structure. The calculator class encapsulates the arithmetic operations and the operands as object members, providing clear organization and reusability of code. Constructors initialize operands, and methods within the class define operations like addition, subtraction, multiplication, and division, promoting encapsulation and abstraction .

Attributes in XML are used to store metadata about elements, providing additional context without altering the data structure. For a sports data XML file, attributes can specify properties of the elements, such as a 'type' attribute to classify each sport as 'Team' or 'Individual'. This allows for structured data representation and query specificity when manipulating or querying the XML content using functions like simple_xml_load_file().

Using XML files for maintaining bookstore inventory allows easy data management and transferability across different platforms. XML provides a human-readable format which simplifies updates and integration with web technologies via languages like PHP. For dynamic searching, PHP scripts can query XML files using functions like simplexml_load_file() and XPath to extract and display specific book details, enhancing search functionality and user accessibility on web interfaces .

AJAX can be integrated with PHP by sending asynchronous HTTP requests from the client-side to fetch specific data from a server-side file like 'Myfile.dat'. Using JavaScript's XMLHttpRequest object, the content is requested and returned without requiring a full page reload. The server processes the request with PHP, retrieves the contents of 'Myfile.dat', and sends it back to the client, which then dynamically updates the webpage content with the retrieved data .

You might also like