0% found this document useful (0 votes)
45 views36 pages

Open Source Technology

The document provides a comprehensive guide on installing XAMPP to use PHP and MySQL, including steps for downloading, installing, and configuring the software. It also includes practical programming exercises such as creating a student registration form, calculating electricity bills, and performing string operations in PHP. Each practical exercise is accompanied by code examples and instructions for running the programs within the XAMPP environment.

Uploaded by

hariom
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)
45 views36 pages

Open Source Technology

The document provides a comprehensive guide on installing XAMPP to use PHP and MySQL, including steps for downloading, installing, and configuring the software. It also includes practical programming exercises such as creating a student registration form, calculating electricity bills, and performing string operations in PHP. Each practical exercise is accompanied by code examples and instructions for running the programs within the XAMPP environment.

Uploaded by

hariom
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

Government Polytechnic,

Bachelikhal, Tehri Garhwal

Submitted By : - Harish patel


Submitted To : -
Date :-
HOW TO INSTALL XAMPP TO USE PHP AND MY SQL
1. Download XAMPP from [Link].

Click XAMPP for Windows. It's a grey button near the bottom of the page.

• Depending on your browser, you may first have to select a save location or
verify the download.[1]
• The file should start downloading automatically. If it does not, click where it
says Click here at the top. Then click one of the download links.
Select components of XAMPP to install and click Next. By default, all XAMPP programs are
included in the installation. Review the list of XAMPP attributes on the left side of the window; if
you see an attribute you don't want to install as part of XAMPP, uncheck its box. Click Next when
you are finished.

• The components include an Apache server, a MySQL database, FileZilla


FTP server, a Mercury Mail Server, Apache Tomcat, PHP, Perl,
PHPMyAdmin, Webalizer, and Fake Sendmail.
• Apache and PHP cannot be unchecked.

Select an installation location and click Next. Click the folder-shaped icon to the right of the
current installation destination, select a folder to install XAMPP in, and click Ok.

• If your computer has the UAC activated, avoid installing XAMPP in your hard drive's folder
(e.g., OS (C:)').
• You can select a folder (e.g., Desktop) and then click Make New Folder to create a new
folder and select it as the installation destination.
• The default installation location is "C:\XAMPP."
Select your language and click Next. Use the drop-down menu to select your language. Then
click Next in the lower-right corner.

Begin installing XAMPP. Click Next at the bottom of the window to do so. XAMPP will begin installing
its files into the folder that you selected.

Click Finish when prompted. It's at the bottom of the XAMPP window. Doing so will close the window
and open the XAMPP Control Panel, which is where you'll access your servers.

• XAMPP will launch on its own after you finish the installation.
1. Start the XAMPP Control Panel as an administrator. You may run into some errors when
trying to start certain programs that come with XAMPP. To avoid problems, you should run
XAMPP as an administrator. Make sure you are signed into a Windows account with
administrative privileges. Then, use the following steps to open the XAMPP Control Panel as an
administrator:

o Click the Windows Start button.

o Type "XAMPP".

o Right-click the XAMPP Control Panel.

o Click Run as Administrator.

o Click Yes when prompted.

2.
2

Click the checkbox next to any modules you want to install. You may see a red "X" in the
checkboxes next to Apache, MySQL, FileZilla, Mercury, and Tomcat. Click the checkbox next to any of
these programs you want to install, then click 'Yes when prompted. A green checkbox will appear next
to the program once it is installed.
3.
3

Click Start to start a module. Once you have installed the module you want to use, click Start next to
any of the programs you want to start running.

4.
4

Click one of the Admin buttons to open the programs. You'll see the Admin button next to all
installed programs in the XAMPP dashboard.

o Apache: Click Admin next to "Apache" to open the Apache dashboard. This will open a
web page in your web browser that contains information about Apache, including How-
to guides. Alternatively, you can type "localhost/dashboard/" into your web browser to
open this page.
o MySQL: Click Admin next to "MySQL" to open the phpMyAdmin page for your local
server. This is where you create and manage databases for your local server.
Alternatively, you can type "localhost/phpmyadmin/" into your web browser to open this
page.

5.
5

Locate your website build. After installing XAMPP, you'll need a place to save all your website build
files. You'll save your website build in the "htdocs" folder in the XAMPP installation folder. Use the
following steps to open it:

o Click Explorer in the XAMPP dashboard.

o Open the "htdocs" folder.

o Create a new folder for your website build.

6. Open your website build in a web browser. Once you have a website build started, you
can test your website build by entering "localhost/[path to website]" in your web browser.
For example, if you create a test website in the "htdocs" folder and save it to a called "test,"
you can open it by typing "localhost/test" into your web browser.[3]
7.

Click Stop to stop a module. If you want to shut down your local server, click Stop next to
the modules you are using. Once they are shut down, you will not be able to load your
website in a web browser.
Practical 1
Write a program to create Student registration form
Folder Structure in XAMPP:-
Place your files inside: C:\xampp\htdocs\student_registration
Your project directory (student_registration) will have:
student_registration/
|-- [Link] // Form page
|-- [Link] // Form processing script
|-- [Link] // Database connection

Database Creation (phpMyAdmin)


Create a Database:

• Open [Link] in your browser.


• Create a database called student_db.
• Inside student_db, create a table called students
[Link] - HTML Form
[Link] - Database Connection File

[Link] - Handle Form Data & Save to


Database
Steps to Run in XAMPP
1. Start Apache and MySQL in XAMPP Control Panel.
2. Visit: [Link]
3. Fill in the form and submit.
4. Data will be saved into students table in student_db database.
Practical 2
Write a program to perform EB bill calculation
Create a PHP File: Inside the EBillCalculator folder, create a new
file named calculate_ebill.php.
Open the File in a Text Editor: Open calculate_ebill.php in a text
editor or an IDE (Integrated Development Environment) like Visual
Studio Code, Sublime Text, or Notepad++.

Code(calculate_ebill.php):-
<?php
// Function to calculate electricity bill
function calculateEBill($units) {
$rate_per_unit = 5; // Set rate per unit in your currency
$bill = 0;

if ($units <= 100) {


$bill = $units * $rate_per_unit;
} elseif ($units <= 200) {
$bill = (100 * $rate_per_unit) + (($units - 100) * ($rate_per_unit * 1.5));
} else {
$bill = (100 * $rate_per_unit) + (100 * ($rate_per_unit * 1.5)) + (($units - 200)
* ($rate_per_unit * 2));
}

return $bill;
}

// Example usage
$units_consumed = 250;
echo "Electricity Bill for " . $units_consumed . " units is: " .
calculateEBill($units_consumed) . " currency units.";
?>

Output:-
Practical 3
Write a program to perform Student grade manipulation
Create a PHP File: Create a new file named student_grades.php.
Open the File in a Text Editor: Open student_grades.php in a text
editor or an IDE.
Code(student_grades.php):-
<?php
// Array to store student grades
$students = array();
// Function to add a student and their grade
function addStudent($name, $grade) {
global $students;
$students[$name] = $grade;
}
// Function to update a student's grade
function updateGrade($name, $new_grade) {
global $students;
if (isset($students[$name])) {
$students[$name] = $new_grade;
return "Grade updated for $name.";
} else {
return "$name not found.";
}
}

// Function to display all student grades


function displayGrades() {
global $students;
foreach ($students as $name => $grade) {
echo "Student: $name, Grade: $grade\n";
}
}
// Add students
addStudent("Alice", "A");
addStudent("Bob", "B");
addStudent("Charlie", "C");
// Update a student's grade
echo updateGrade("Bob", "A+") . "\n";
// Display all grades
displayGrades();
?>

Output:-
Practical 4
Write a program to perform String operations in PHP
Create a PHP File: Create a new file named string_operations.php.
Open the File in a Text Editor: Open string_operations.php in a text
editor or an IDE.
Code(string_operations.php): -
<?php
// Example string
$string = "Hello, World!";

// Concatenate strings
$greeting = "Hello, ";
$name = "Alice";
$concatenatedString = $greeting . $name;
echo "Concatenated String: " . $concatenatedString . "\n";
// Find the length of the string
$stringLength = strlen($string);
echo "Length of the String: " . $stringLength . "\n";
// Reverse the string
$reversedString = strrev($string);
echo "Reversed String: " . $reversedString . "\n";
// Change case of the string
$lowercaseString = strtolower($string);
$uppercaseString = strtoupper($string);
echo "Lowercase String: " . $lowercaseString . "\n";
echo "Uppercase String: " . $uppercaseString . "\n";
// Find a substring
$substring = substr($string, 7, 5);
echo "Substring: " . $substring . "\n";
// Replace a substring
$replacedString = str_replace("World", "PHP", $string);
echo "Replaced String: " . $replacedString . "\n";
?>

Output:-
Practical 5
Write a program to create Book master form
Create a Project Folder: Create a folder on your machine where
you want to store your PHP files. For example, you can create a
folder named BookMasterForm.
Create a PHP File: Inside the BookMasterForm folder, create a new
file named [Link].
Open the File in a Text Editor: Open [Link] in a text editor or an
IDE (Integrated Development Environment) like Visual Studio Code,
Sublime Text, or Notepad++.

Code([Link]):-

<!DOCTYPE html>
<html>
<head>
<title>Book Master Form</title>
</head>
<body>
<h1>Book Master Form</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="title">Book Title:</label><br>
<input type="text" id="title" name="title" required><br><br>
<label for="author">Author:</label><br>
<input type="text" id="author" name="author" required><br><br>
<label for="publisher">Publisher:</label><br>
<input type="text" id="publisher" name="publisher" required><br><br>
<label for="year">Year of Publication:</label><br>
<input type="number" id="year" name="year" required><br><br>
<input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Capture form data
$title = $_POST['title'];
$author = $_POST['author'];
$publisher = $_POST['publisher'];
$year = $_POST['year'];
// Display the captured data
echo "<h2>Book Details</h2>";
echo "Title: " . htmlspecialchars($title) . "<br>";
echo "Author: " . htmlspecialchars($author) . "<br>";
echo "Publisher: " . htmlspecialchars($publisher) . "<br>";
echo "Year of Publication: " . htmlspecialchars($year) . "<br>";
}
?>
</body>
</html>
Output:-
Practical 6
Write a program to perform Form validation – Railway ticket
reservation
Create a Project Folder: Create a folder on your machine where
you want to store your PHP files. For example, you can create a
folder named RailwayTicketReservation.
Create a PHP File: Inside the RailwayTicketReservation folder,
create a new file named [Link].
Open the File in a Text Editor: Open [Link] in a text editor or an
IDE (Integrated Development Environment) like Visual Studio Code,
Sublime Text, or Notepad++.

Code([Link]):-
<!DOCTYPE html>
<html>
<head>
<title>Railway Ticket Reservation</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h1>Railway Ticket Reservation Form</h1>
<?php
// Define variables and set to empty values
$nameErr = $ageErr = $emailErr = $dateErr = "";
$name = $age = $email = $travel_date = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = test_input($_POST["age"]);
if (!filter_var($age, FILTER_VALIDATE_INT)) {
$ageErr = "Invalid age format";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["travel_date"])) {
$dateErr = "Travel date is required";
} else {
$travel_date = test_input($_POST["travel_date"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">


<label for="name">Name:</label><br>
<input type="text" id="name" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span><br><br>
<label for="age">Age:</label><br>
<input type="text" id="age" name="age" value="<?php echo $age;?>">
<span class="error">* <?php echo $ageErr;?></span><br><br>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span><br><br>
<label for="travel_date">Travel Date:</label><br>
<input type="date" id="travel_date" name="travel_date" value="<?php echo
$travel_date;?>">
<span class="error">* <?php echo $dateErr;?></span><br><br>
<input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && empty($nameErr) && empty($ageErr) &&
empty($emailErr) && empty($dateErr)) {
echo "<h2>Your Input:</h2>";
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Email: " . $email . "<br>";
echo "Travel Date: " . $travel_date . "<br>";
}
?>
</body>
</html>

Output:-
Practical 7
Write a program to perform Date and time operations in PHP
Create a PHP File: Create a new file named
date_time_operations.php.
Open the File in a Text Editor: Open date_time_operations.php in a
text editor or an IDE.

Code(date_time_operations.php):-
<?php
// Get the current date and time
$currentDateTime = date("Y-m-d H:i:s");
echo "Current Date and Time: " . $currentDateTime . "\n";
// Format a specific date
$specifiedDate = "2025-03-01";
$formattedDate = date("l, F j, Y", strtotime($specifiedDate));
echo "Formatted Date: " . $formattedDate . "\n";
// Add time to the current date
$addedTime = date("Y-m-d H:i:s", strtotime("+2 days +3 hours"));
echo "Date and Time after Adding 2 days and 3 hours: " . $addedTime . "\n";
// Subtract time from the current date
$subtractedTime = date("Y-m-d H:i:s", strtotime("-1 week -5 minutes"));
echo "Date and Time after Subtracting 1 week and 5 minutes: " . $subtractedTime . "\n";
// Calculate the difference between two dates
$date1 = new DateTime("2025-03-01");
$date2 = new DateTime("2025-04-01");
$interval = $date1->diff($date2);
echo "Difference between dates: " . $interval->days . " days\n";
// Get the current timestamp
$currentTimestamp = time();
echo "Current Timestamp: " . $currentTimestamp . "\n";
// Convert timestamp to date
$timestampToDate = date("Y-m-d H:i:s", $currentTimestamp);
echo "Date from Timestamp: " . $timestampToDate . "\n";
?>

Output:-
Practical 8
Write a program to Identify the web browser
Create a PHP File: Create a new file named identify_browser.php.
Open the File in a Text Editor: Open identify_browser.php in a text
editor or an IDE.

Code(identify_browser.php):-
<?php
// Function to identify the web browser
function getBrowser() {
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$browser = "Unknown Browser";

if (strpos($userAgent, 'MSIE') !== false || strpos($userAgent, 'Trident') !== false) {


$browser = "Internet Explorer";
} elseif (strpos($userAgent, 'Edge') !== false) {
$browser = "Microsoft Edge";
} elseif (strpos($userAgent, 'Firefox') !== false) {
$browser = "Mozilla Firefox";
} elseif (strpos($userAgent, 'Chrome') !== false) {
$browser = "Google Chrome";
} elseif (strpos($userAgent, 'Safari') !== false && strpos($userAgent, 'Chrome') ===
false) {
$browser = "Apple Safari";
} elseif (strpos($userAgent, 'Opera') !== false || strpos($userAgent, 'OPR') !==
false) {
$browser = "Opera";
}

return $browser;
}

// Display the web browser


echo "You are using: " . getBrowser();
?>

Output:-
Practical 9
Demonstrate the Database – Insert operation
Create a Database: Open your MySQL client (such as phpMyAdmin
or MySQL Workbench) and create a database. For example, let's
create a database named testdb.

Create a Table: In the testdb database, create a table named users


with the following structure:
Writing the PHP Program
1. Create a Project Folder: Create a folder on your machine
where you want to store your PHP files. For example, you can
create a folder named InsertOperation.
2. Create a PHP File: Inside the InsertOperation folder, create a
new file named [Link].
3. Open the File in a Text Editor: Open [Link] in a text editor
or an IDE (Integrated Development Environment) like Visual
Studio Code, Sublime Text, or Notepad++.
Code([Link]):-
<!DOCTYPE html>
<html>
<head>
<title>Insert Data into MySQL</title>
</head>
<body>
<h1>Insert Data into MySQL Database</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="age">Age:</label><br>
<input type="number" id="age" name="age" required><br><br>
<input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Capture form data
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];

// Database connection settings


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Insert data into the database


$sql = "INSERT INTO users (name, email, age) VALUES ('$name', '$email', $age)";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the connection


$conn->close();
}
?>
</body>
</html>

OutPut:-
Practical 10
Demonstrate the Database – Delete operation
Create a Project Folder: Create a folder on your machine where
you want to store your PHP files. For example, you can create a
folder named DeleteOperation.
Create a PHP File: Inside the DeleteOperation folder, create a new
file named [Link].
Open the File in a Text Editor: Open [Link] in a text editor or
an IDE (Integrated Development Environment) like Visual Studio
Code, Sublime Text, or Notepad++.
Code([Link]):-
<!DOCTYPE html>
<html>
<head>
<title>Delete Data from MySQL</title>
</head>
<body>
<h1>Delete Data from MySQL Database</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="id">Enter the ID of the record to delete:</label><br>
<input type="number" id="id" name="id" required><br><br>
<input type="submit" value="Delete">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Capture form data
$id = $_POST['id'];

// Database connection settings


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Delete data from the database
$sql = "DELETE FROM users WHERE id=$id";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the connection


$conn->close();
}
?>
</body>
</html>

Output:-
Practical 11
Demonstrate the Database - Update operation
Create a Project Folder: Create a folder on your machine where
you want to store your PHP files. For example, you can create a
folder named UpdateOperation.
Create a PHP File: Inside the UpdateOperation folder, create a new
file named [Link].
Open the File in a Text Editor: Open [Link] in a text editor or
an IDE (Integrated Development Environment) like Visual Studio
Code, Sublime Text, or Notepad++.

Code([Link]):-
<!DOCTYPE html>

<html>
<head>
<title>Update Data in MySQL</title>
</head>
<body>
<h1>Update Data in MySQL Database</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="id">Enter the ID of the record to update:</label><br>
<input type="number" id="id" name="id" required><br><br>
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<label for="age">Age:</label><br>
<input type="number" id="age" name="age"><br><br>
<input type="submit" value="Update">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Capture form data
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];

// Database connection settings


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Prepare the update SQL statement


$updateFields = [];
if (!empty($name)) {
$updateFields[] = "name='$name'";
}
if (!empty($email)) {
$updateFields[] = "email='$email'";
}
if (!empty($age)) {
$updateFields[] = "age=$age";
}

if (!empty($updateFields)) {
$sql = "UPDATE users SET " . implode(", ", $updateFields) . " WHERE id=$id";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "No fields to update";
}

// Close the connection


$conn->close();
}
?>
</body>
</html>
Output:-
Practical 12
Demonstrate the Queries Record selection operation
Basic SELECT Query:

This query selects column1 and column2 from the specified table_name.

Selecting All Columns:

This query selects records where the specified condition is met. For
example:

This query selects the name and age of users who are older than 25.
Using ORDER BY to Sort Results:

This query selects records and sorts them in ascending order by column1.
You can also use DESC for descending order.
Selecting with LIMIT:

This query selects the first 10 records from the specified table.
Combining WHERE and ORDER BY:

This query selects records that meet the condition and sorts them
in ascending order by column1.
Using Aliases:

This query selects column1 and column2, but renames them to


alias1 and alias2 in the result set.
Joining Tables:

This query selects records from two tables (table1 and table2)
based on a common column.
Practical 13
Write the queries to demonstrate the working with date and time
functions
Current Date and Time:

This query returns the current date and time.

Extracting Date Parts:

This query extracts various parts of the current date and time.
Date Arithmetic:

This query demonstrates how to add and subtract intervals to/from


the current date and time.
Date Formatting:

This query formats the current date and time in the specified format
(%Y-%m-%d %H:%i:%s).
Difference Between Dates:

This query calculates the number of days between two dates.


Extracting Day of the Week:

This query returns the day of the week for the current date (1 =
Sunday, 2 = Monday, ..., 7 = Saturday).
Finding the Last Day of the Month:

This query returns the last day of the current month.


Adding or Subtracting Time:

This query demonstrates how to add and subtract time intervals.


Practical 14
Demonstrate the Simple Programming and File handling
operation

Simple Programming: Here is a simple example of a Python


program that takes user input and performs basic arithmetic
operations:

This program prompts the user to input two numbers and then
performs addition, subtraction, multiplication, and division on
those numbers.
File Handling: Here are some basic file handling operations,
including reading from and writing to a file:

The write_to_file function opens a file in write mode ('w') and writes
the provided content to the file. The read_from_file function opens a
file in read mode ('r') and reads its content.

Appending to a File: If you want to append content to an existing


file, you can use the append mode ('a'):

The append_to_file function opens a file in append mode ('a') and


appends the provided content to the file.

You might also like