0% found this document useful (0 votes)
30 views65 pages

Master of Php Record 2025doc NEW (1)

Uploaded by

rajamagesh84
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)
30 views65 pages

Master of Php Record 2025doc NEW (1)

Uploaded by

rajamagesh84
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/ 65

RVS COLLEGE OF ARTS AND SCIENCE(AUTONOMOUS)

SULUR-COIMBATORE-641402

Reg. No
Name
Class III-BCOM(CA)-

Subject Master PHP &MySQL


RVS COLLEGE OF ARTS AND
SCIENCE (AUTONOMOUS)

SULUR, COIMBATORE-641 402

SCHOOL OF COMMERCE

B. Com (CA) Degree Examinations March-2025


REGISTER NO. _______________________

Certified that it is a Bonafide record of Master of PHP&MySQL


Programming Practical Report done and submitted by _______________________
of _______________ for the Practical Examination / Viva – Voce held at RVS
College of Arts and Science (Autonomous), Sulur, Coimbatore.

________________________ ____________________

Staff – in – charge Director/ HoD

Submitted for the practical Examination / Viva – Voce held on _______________.

---------------------------- -----------------------------
Internal Examiner External Examiner
CONTENTS

S.NO. PARTICULARS DATE SIGN

Get Input and Display Output


1
using forms
Future Value Calculation using
2
Drop-Down List
Invoice total application using if,
3
else statements
Score application using switch case
4
statements
5 String tester

6 Number tester

7 Date tester
Array of Task list manager
8
application
Task list manager application using
9
sessions
Product list manager application
10
using objects and methods
Product list manager application
11
using validation
12 Guitor shop application using PDO

SELECT,INSERT,UPDATE,DELETE in
13
mysqli Database

14 Product and Category model in mysqli

15 Method of mysqli class


1. Get Input and Display Output using forms
AIM:

Create a PHP program for Get input and Display output using forms control

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <HTML>.

STEP 5 : Create the form action and finish the embed php code with save as file.php extension.

STEP 6 : Use text boxes, password boxes, radio buttons, check boxes, drop-down lists, list
boxes, and text areas to get input from the user.
STEP 7 : Use hidden fields to pass data to the web application when a form is submitted.
STEP 8 : Use the htmlspecialchars and nl2br functions to display user entries the way you want
them displayed.
STEP 9 : Use echo statements to display data in a web page.
STEP 10 : Finish the Coding Function.

STEP 11 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 12 : Stop The APACHE & MYSQL And Close The XAMPP.
1.Get Input and Display Output Using Forms
<html>
<head>
<title>Account Sign Up</title>
<link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body>
<div id="content">
<h1>Account Sign Up</h1>
<form action="new.php" method="post">

<fieldset>
<legend>Account Information</legend>
<label>E-Mail:</label>
<input type="text" name="email" value="" class="textbox"/>
<br />

<label>Password:</label>
<input type="password" name="password" value="" class="textbox"/>
<br />
<label>Phone Number:</label>
<input type="text" name="phone" value="" class="textbox"/>
</fieldset>

<fieldset>
<legend>Settings</legend>
<p>How did you hear about us?</p>
<input type="radio" name="heard_from" value="Search Engine" />
Search engine<br />
<input type="radio" name="heard_from" value="Friend" />
Word of mouth<br />
<input type=radio name="heard_from" value="Other" />
Other<br />
<p>Would you like to receive announcements about new products
and special offers?</p>
<input type="checkbox" name="wants_updates"/>YES, I'd like to receive
information about new products and special offers.<br />

<p>Contact via:</p>
<select name="contact_via">
<option value="email">Email</option>
<option value="text">Text Message</option>
<option value="phone">Phone</option>
</select>
<p>Comments:</p>
<textarea name="comments" rows="4" cols="50"></textarea>
</fieldset>
<input type="submit" value="Submit" />
</form>
<br />
</div>
</body>
</html>

new.php file

<?php

// get the data from the form

$email = $_POST['email'];
$password = $_POST['password'];
$phone = $_POST['phone'];
if (isset($_POST['heard_from'])) {
$heard_from = $_POST['heard_from'];
} else {
$heard_from = 'Unknown';
}
if (isset($_POST['wants_updates'])) {
$wants_updates = 'Yes';
} else {
$wants_updates = 'No';
}
$contact_via = $_POST['contact_via'];
$comments = $_POST['comments'];
$comments = htmlspecialchars($comments);
$comments = nl2br($comments, false);
?>
<html>
<head>
<title>Account Information</title>
<link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body>
<div id="content">
<h1>Account Information</h1>
<label>Email Address:</label>
<span><?php echo htmlspecialchars($email); ?></span><br />

<label>Password:</label>
<span><?php echo htmlspecialchars($password); ?></span><br />

<label>Phone Number:</label>
<span><?php echo htmlspecialchars($phone); ?></span><br />

<label>Heard From:</label>
<span><?php echo $heard_from; ?></span><br />

<label>Send Updates:</label>
<span><?php echo $wants_updates; ?></span><br />

<label>Contact Via:</label>
<span><?php echo $contact_via; ?></span><br /><br />

<span>Comments:</span><br />
<span><?php echo $comments; ?></span><br />

<p>&nbsp;</p>
</div>
</body>
</html>
Output:

Result:
2. Future Value Calculation using Drop-Down List
AIM:

Develop a PHP program for Enhance the Future value application using drop-down list.

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <HTML>.

STEP 5 : Create the form action and finish the embed php code with save as file.php extension.

STEP 6 : Use text boxes, drop-down lists to get input from the user.
STEP 7 : create a form with fields for investment amount, annual interest rate, number of years,
and a drop-down list for compounding frequency.
STEP 8: The compounding frequency is used to calculate the future value using the formula for
compound interest
STEP 8 : Use echo statements to display data in a web page.
STEP 9 : Finish the Coding Function.

STEP 10 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 11 : Stop The APACHE & MYSQL And Close The XAMPP.
2. Future value Calculation using Drop-Down List
<html>
<head>
<title>Future Value Calculator</title>
</head>
<body>
<h2>Future Value Calculator</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="investment">Investment Amount:</label>
<input type="text" name="investment" required><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" name="rate" required><br>
<label for="years">Number of Years:</label>
<input type="text" name="years" required><br>
<label for="compounding">Compounding Frequency:</label>
<select name="compounding">
<option value="1">Annually</option>
<option value="2">Semi-annually</option>
<option value="4">Quarterly</option>
<option value="12">Monthly</option>
</select><br>
<input type="submit" value="Calculate">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$investment = $_POST["investment"];
$rate = $_POST["rate"] / 100; // convert percentage to decimal
$years = $_POST["years"];
$compounding = $_POST["compounding"];
// Calculate future value
$futureValue = $investment * pow((1 + $rate / $compounding), $years * $compounding);
// Display the result
echo "<h3>Future Value:</h3>";
echo "<p>The future value of your investment is $" . number_format($futureValue, 2) . "</p>";
}
?>
</body>
</html>
Output:
Result:
3. Invoice Total Application using if, else statement
AIM:

Create a PHP program for invoice total application using if, Else statement.

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <?php.

STEP 5 : Create the form action and finish the php code with save as file.php extension.

STEP 6 : The calculateTotal function computes the total amount based on the given
quantity and price.
STEP 7 : The applyDiscount function checks if the total amount exceeds a certain threshold
and applies a discount accordingly.
STEP 8 : The sample data includes the quantity and price per item, and the program calculates
the total amount without discount and the final amount after applying any applicable
discount.
STEP 9 : Use echo statements to display data in a web page.
STEP 10 : Finish The Coding Function.

STEP 11 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The
File To View An Output In Parent Directory.

STEP 12 : Stop The APACHE & MYSQL And Close The XAMPP.
3. Invoice total Application using if, else statements
<?php
// Function to calculate total amount
function calculateTotal($quantity, $price)
{
return $quantity * $price;
}

// Function to apply discount


function applyDiscount($total)
{
$discountThreshold = 1000;
$discountRate = 0.1; // 10% discount
if ($total > $discountThreshold)
{
return $total - ($total * $discountRate);
}
else
{
return $total;
}
}

// Sample data
$itemQuantity = 5;
$itemPrice = 250;

// Calculate total without discount


$totalAmount = calculateTotal($itemQuantity, $itemPrice);

// Apply discount if applicable


$finalAmount = applyDiscount($totalAmount);

// Display results
echo "Quantity: $itemQuantity\n";
echo "Price per item: $itemPrice\n";
echo "Total amount without discount: $totalAmount\n";
echo "Final amount after discount: $finalAmount\n";
?>
Output:

Result:
4. Score application using switch case statement
AIM:

Construct a PHP program for score application using switch statement.

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <?php.

STEP 5 : Create the form action and finish the php code with save as file.php extension.

STEP 6 : The calculateGrade function takes a numeric score as an argument and uses a switch
statement to determine the corresponding grade.
STEP 7 : Each case in the switch statement checks if the score falls within a specific range and
returns the corresponding grade.
STEP 8 : The default case is used to handle situations where the input score is not within any of
the specified ranges.
STEP 9 : Use echo statements to display data in a web page.
STEP 10 : Finish The Coding Function.

STEP 11 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 12 : Stop The APACHE & MYSQL And Close The XAMPP.
4. Score application using switch case statement

<?php
function calculateGrade($score)
{
switch (true)
{
case ($score >= 90 && $score <= 100):
return 'A';
case ($score >= 80 && $score < 90):
return 'B';
case ($score >= 70 && $score < 80):
return 'C';
case ($score >= 60 && $score < 70):
return 'D';
case ($score >= 0 && $score < 60):
return 'F';
default:
return 'Invalid Score';
}
}
// Example usage
$score = 85;
$grade = calculateGrade($score);
echo "Score: $score\n";
echo "Grade: $grade\n";
?>
Output:

Result:
5. String tester
AIM:

Create a PHP program for string tester application

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <HTML>.

STEP 5 : Create the form action and finish the embed php code with save as file.php extension.

STEP 6 : Create three functions (isPalindrome, reverseString, and hasSubstring) to


check if a string is a palindrome, get the reversed string, and check if it contains a
specific substring, respectively.
STEP 7 : Use the way PHP escape sequences can be used to insert special characters into
strings and the html entities function can be used to display special characters
correctly in a browser.
STEP 8 : Use echo statements to display data in a web page.
STEP 9 : Finish The Coding Function.

STEP 10 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 11 : Stop The APACHE & MYSQL And Close The XAMPP.
5. String tester
<html>
<head>
<title>String Tester</title>
</head>
<body>
<?php
function isPalindrome($str)
{
$str = strtolower(str_replace(' ', '', $str));
return $str == strrev($str);
}
function reverseString($str)
{
return strrev($str);
}
function hasSubstring($str, $substring)
{
return strpos($str, $substring) !== false;
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$inputString = $_POST["inputString"];
$substring = $_POST["substring"];
echo "<h2>Results:</h2>";
echo "<p>Input String: $inputString</p>";
if (isPalindrome($inputString))
{
echo "<p>The string is a palindrome.</p>";
}
else
{
echo "<p>The string is not a palindrome.</p>";
}
echo "<p>Reversed String: " . reverseString($inputString) . "</p>";
if (hasSubstring($inputString, $substring))
{
echo "<p>The string contains the substring '$substring'.</p>";
}
else
{
echo "<p>The string does not contain the substring '$substring'.</p>";
}
}
?>

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


<label for="inputString">Enter a String:</label>
<input type="text" id="inputString" name="inputString" required>
<br>

<label for="substring">Substring to Check:</label>


<input type="text" id="substring" name="substring" required>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Output:
Result:
6. Number tester
AIM:

Develop a PHP program for number tester application using Numbers.

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <HTML>.

STEP 5 : Create the form action and finish the embed php code with save as file.php extension.

STEP 6 : Use any of the functions and techniques that are presented in this program to work
with numbers.
STEP 7 : Get the number from the form and Validate if the input is a number
STEP 8 : Check if the number is even or odd
STEP 9 : Finish The Coding Function.

STEP 10 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 11 : Stop The APACHE & MYSQL And Close The XAMPP.
6. Number Tester
<html>
<head>
<title>Number Tester</title>
</head>
<body>
<h2>Number Tester</h2>
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Get the number from the form
$number = $_POST["number"];
// Validate if the input is a number
if (is_numeric($number))
{
// Check if the number is even or odd
$result = ($number % 2 == 0) ? "Even" : "Odd";
echo "<p>The number $number is $result.</p>";
} else
{
echo "<p>Please enter a valid number.</p>";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter a number: <input type="text" name="number">
<input type="submit" value="Test">
</form>
</body>
</html>
Output:
Result:
7. Date tester
AIM:

Create a PHP program for Date tester application

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <?php.

STEP 5 : Create the form action and finish the php code with save as file.php extension.

STEP 6 : Use a function isValidDate to check if a given date is in the 'YYYY-MM-DD' format
and is a valid date.
STEP 7 : The HTML part includes a form with an input field for entering the date. the PHP code
processes the input, validates the date.
STEP 8 : Use echo statements to display data in a web page.
STEP 9 : Finish The Coding Function.

STEP 10 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 11 : Stop The APACHE & MYSQL And Close The XAMPP.
7. Date tester
<?php
function isValidDate($date)
{
$dateObj = DateTime::createFromFormat('Y-m-d', $date);
return $dateObj && $dateObj->format('Y-m-d') === $date;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$inputDate = $_POST['input_date'];
if (!empty($inputDate))
{
if (isValidDate($inputDate))
{
$result = "The date '$inputDate' is valid.";
}
else
{
$result = "Invalid date format. Please use 'YYYY-MM-DD'.";
}
}
else
{
$result = "Please enter a date.";
}
}
?>
<html>
<head>
<title>Date Tester</title>
</head>
<body>
<h2>Date Tester</h2>

<form method="post" action="">


<label for="input_date">Enter a date (YYYY-MM-DD): </label>
<input type="text" id="input_date" name="input_date" required>
<button type="submit">Test Date</button>
</form>
<?php if (isset($result)): ?>
<p><?php echo $result; ?></p>
<?php endif; ?>
</body>
</html>

Output:
Result:
8. Array of task list manager application
AIM:

Construct a PHP program using array of the Task List Manager Application.

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <?php.

STEP 5 : Create the form action and finish the php code with save as file.php extension.

STEP 6 : Use an array $tasks to store tasks, and functions addTask, viewTasks, and
markTaskCompleted to perform different actions on the task list.
STEP 7 : Use echo statements to display data in a web page.
STEP 8 : Finish The Coding Function.

STEP 9 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 10 : Stop The APACHE & MYSQL And Close The XAMPP.
8. Array of task list manager application
<?php
$tasks = []; // Array to store tasks
// Function to add a task to the array
function addTask($task)
{
global $tasks;
$tasks[] = $task;
}
// Function to view tasks
function viewTasks()
{
global $tasks;
echo "Tasks:\n";
foreach ($tasks as $index => $task)
{
$status = $task['completed'] ? 'Completed' : 'Incomplete';
echo ($index + 1) . ". {$task['title']} - $status\n";
}
echo "\n";
}
// Function to mark a task as completed
function markTaskCompleted($index)
{
global $tasks;
if (isset($tasks[$index]))
{
$tasks[$index]['completed'] = true;
echo "Task marked as completed.\n\n";
}
else
{
echo "Invalid task index.\n\n";
}
}
// Example usage:
// Add tasks
addTask(['title' => 'Task 1', 'completed' => false]);
addTask(['title' => 'Task 2', 'completed' => false]);
// View tasks
viewTasks();

// Mark a task as completed


markTaskCompleted(1);

// View tasks after marking as completed


viewTasks();
?>
Output:

Result:
9. Task list manager application using sessions
AIM:

Develop a PHP program for Task List Manager Application using sessions.

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <?php.

STEP 5 : Create the form action and finish the php code with save as file.php extension.

STEP 6 : The tasks are stored in the session variable $_SESSION['tasks'], and you can add
or remove tasks using the provided form.
STEP 7 : The tasks are displayed in an unordered list, and each task has a delete button
associated with it. When you click the delete button, the corresponding task is
removed from the list.
STEP 8 : Use echo statements to display data in a web page.
STEP 9 : Finish The Coding Function.

STEP 10 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 11 : Stop The APACHE & MYSQL And Close The XAMPP.
9. Task list manager application using session
<?php
// Start the session
session_start();
// Check if the tasks array is already set in the session, if not, initialize it
if (!isset($_SESSION['tasks']))
{
$_SESSION['tasks'] = array();
}
// Function to add a task to the task list
function addTask($task)
{
$_SESSION['tasks'][] = $task;
}
// Function to remove a task from the task list
function removeTask($index)
{
if (isset($_SESSION['tasks'][$index]))
{
unset($_SESSION['tasks'][$index]);
}
}
// Check if the form is submitted to add a new task
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (isset($_POST['task']) && !empty($_POST['task']))
{
$newTask = htmlspecialchars($_POST['task']);
addTask($newTask);
}
elseif (isset($_POST['delete']) && !empty($_POST['delete']))
{
$indexToDelete = (int)$_POST['delete'];
removeTask($indexToDelete);
}
}
?>
<html>
<head>
<title>Task List Manager</title>
</head>
<body>
<h2>Task List</h2>
<ul>
<?php
// Display the list of tasks
foreach ($_SESSION['tasks'] as $index => $task)
{
echo "<li>{$task} <form method='post'><input type='hidden' name='delete'
value='{$index}'><button type='submit'>Delete</button></form></li>";
}
?>
</ul>
<h2>Add a Task</h2>
<form method="post">
<label for="task">Task:</label>
<input type="text" id="task" name="task" required>
<button type="submit">Add Task</button>
</form>
</body>
</html>
Output:
Result:
10.Product list manager application using objects and methods
AIM:

Create a PHP program modifies the Product Manager Application using objects and methods.

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <?php.

STEP 5 : Create the form action and finish the php code with save as file.php extension.

STEP 6 : The Product class represents a product with properties like id, name, and price. The
ProductManager class is responsible for managing products, including adding,
viewing, and removing products.
STEP 7 : The example usage section demonstrates creating product instances, adding them to
the product manager, viewing products, removing a product, and viewing the updated
product list.
STEP 8 : Use echo statements to display data in a web page.
STEP 9 : Finish The Coding Function.

STEP 10 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 11 : Stop The APACHE & MYSQL And Close The XAMPP.
10. Product Manager Application Using Objects and methods
<?php
// Product class representing a product with properties and methods
class Product
{
private $name;
private $price;
public function __construct($name, $price)
{
$this->name = $name;
$this->price = $price;
}
public function getName()
{
return $this->name;
}
public function getPrice()
{
return $this->price;
}
}
// ProductManager class for managing products
class ProductManager
{
private $products = [];
public function addProduct(Product $product)
{
$this->products[] = $product;
}
public function displayProducts()
{
echo "Product List:\n";
foreach ($this->products as $product)
{
echo "Name: " . $product->getName() . ", Price: $" . $product->getPrice() . "\n";
}
}
}
// Creating product objects
$product1 = new Product("Laptop", 999.99);
$product2 = new Product("Smartphone", 499.99);

// Creating a product manager object


$productManager = new ProductManager();

// Adding products to the manager


$productManager->addProduct($product1);
$productManager->addProduct($product2);

// Displaying the list of products


$productManager->displayProducts();
?>
Output:

Result:
11.Product list manager application using validation
AIM:

Develop a PHP program modify the Product Manager Application using validation

techniques.

ALGORITHM:

STEP 1 : Turn On The PC.

STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.

STEP 3 : Open Notepad to code the Function.

STEP 4 : Start the code with <?php.

STEP 5 : Create the form action and finish the php code with save as file.php extension.

STEP 6 : The addProduct method checks if the input parameters are valid before adding a
product to the list.
STEP 7 : The validation includes checking if the name is not empty and if both the price and
quantity are numeric.
STEP 8 : If the validation fails, an exception is thrown, and an error message is displayed.
STEP 9 : Use echo statements to display data in a web page.
STEP 10 : Finish The Coding Function.

STEP 11 : To Run a Program Open Chrome and Type localhost/Folder Name. And Select The

File To View An Output In Parent Directory.

STEP 12 : Stop The APACHE & MYSQL And Close The XAMPP.
11. Product manager application using validation
<?php
class ProductManager
{
private $products = [];
public function addProduct($name, $price, $quantity)
{
// Validate input
if (empty($name) || !is_numeric($price) || !is_numeric($quantity))
{
throw new Exception("Invalid input. Please provide valid information.");
}
// Add the product
$product = [
'name' => $name,
'price' => $price,
'quantity' => $quantity,
];
$this->products[] = $product;
echo "Product added successfully!\n";
}
public function listProducts()
{
echo "Product List:\n";
foreach ($this->products as $product)
{
echo "Name: {$product['name']}, Price: {$product['price']}, Quantity: {$product['quantity']}\n";
}
}
}
// Example usage
$productManager = new ProductManager();
try
{
$productManager->addProduct("Product 1", 25.99, 10);
$productManager->addProduct("Product 2", "InvalidPrice", 5); // This will throw an exception
$productManager->addProduct("", 19.99, 8); // This will throw an exception
$productManager->listProducts();
}
catch (Exception $e)
{
echo "Error: " . $e->getMessage() . "\n";
}
?>
Output:

Result:
12.Guitar Shop Application Using PDO
AIM:

Create a PHP program using guitar shop application using PDO

ALGORITHM:

STEP 1 : Turn On The PC.


STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.
STEP 3 : Create the database guitar_shop and guitars table using the provided SQL
commands
STEP 4 : Open notepad, create the code for dp.php,
add_guitar.php,search_guitar.php,index.phpfiles
STEP 5 : All the files names are included in index.php file using include function.
STEP 6 : Save all the php file---local Disc(c) /xampp/htdocs/create any folder to save
STEP 7 : Open the guitar_shop database from mysql database of myadmin and import the
index.php file and click the Go button,,
STEP 8 : Finish the coding function.Place the php files in your web server's root directory.
STEP 9 : Access the application via a web browser(e.g., http://localhost/guitar_shop/index.php).
STEP 10 :To run a program open chrome and type localhost/folder name and select the
file to view an output in parent directory.
STEP 11: Stop The APACHE & MYSQL And Close The XAMPP.
12.Guitar Shop Application Using PDO

Php my admin sql queries:


CREATE DATABASE guitar_shop;

USE guitar_shop;

CREATE TABLE guitars (


id INT AUTO_INCREMENT PRIMARY KEY,
brand VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
type VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL
);
db.php
<?php
$host = 'localhost';
$db = 'guitar_shop';
$user = 'root';
$pass = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Index.php
<?php
require 'db.php';
$query = $pdo->query("SELECT * FROM guitars");
$guitars = $query->fetchAll(PDO::FETCH_ASSOC);
?>
<html>
<head>
<title>Guitar Shop</title>
</head>
<body>
<h1>Guitar Shop</h1>
<h2>Available Guitars</h2>
<ul>
<?php foreach ($guitars as $guitar): ?>
<li>
<?php echo htmlspecialchars($guitar['brand']) . ' ' . htmlspecialchars($guitar['model']) . ' - $' .
htmlspecialchars($guitar['price']); ?>
</li>
<?php endforeach; ?>
</ul>
<a href="add_guitar.php">Add a New Guitar</a>
<a href="search_guitar.php">Search Guitars</a>
</body>
</html>
Add_guitar.php
<?php
require 'db.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$brand = $_POST['brand'];
$model = $_POST['model'];
$type = $_POST['type'];
$price = $_POST['price'];
$stmt = $pdo->prepare("INSERT INTO guitars (brand, model, type, price) VALUES (?, ?,
?,?)");
$stmt->execute([$brand, $model, $type, $price]);
header("Location: index.php");
exit;
}
?>
<html>
<head>
<title>Add Guitar</title>
</head>
<body>
<h1>Add New Guitar</h1>
<form method="POST">
<label>Brand:</label><br>
<input type="text" name="brand" required><br>
<label>Model:</label><br>
<input type="text" name="model" required><br>
<label>Type:</label><br>
<input type="text" name="type" required><br>
<label>Price:</label><br>
<input type="text" name="price" required><br><br>
<input type="submit" value="Add Guitar">
</form>
<a href="index.php">Back to Home</a>
</body>
</html>
Search_guitar.php
<?php
require 'db.php';
$guitars = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$searchTerm = '%' . $_POST['search'] . '%';
$stmt = $pdo->prepare("SELECT * FROM guitars WHERE brand LIKE ? OR model LIKE ?");
$stmt->execute([$searchTerm, $searchTerm]);
$guitars = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<html>
<head>
<title>Search Guitars</title>
</head>
<body>
<h1>Search for Guitars</h1>
<form method="POST">
<input type="text" name="search" required>
<input type="submit" value="Search">
</form>
<h2>Search Results:</h2>
<ul>
<?php foreach ($guitars as $guitar): ?>
<li>
<?php echo htmlspecialchars($guitar['brand']) . ' ' . htmlspecialchars($guitar['model']) . ' - $' .
htmlspecialchars($guitar['price']); ?>
</li>
<?php endforeach; ?>
</ul>
<a href="index.php">Back to Home</a>
</body>
</html>
Output:
1.Guitar Shop
Available Guitar
Add a New Guitar Search Guitars

2.Add New Guitar


Brand:

Model:

Type:

Price:

Back to Home

3.Guitar Shop
Available Guitars
 reabock 24 - $2000.00

Add a New Guitar Search Guitars

4.Search for Guitars

5.Search Results:
Back to Home

Guitar Shop
Available Guitars
 reabock 24 - $2000.00
 royal 23-$1500.00

Add a New Guitar Search Guitars


13.Queries in a Mysqli database
AIM:

Create a PHP program using SELECT,INSERT,UPDATE,DELETE Data in a mysqli


database

ALGORITHM:

STEP 1 : Turn On The PC.


STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.
STEP 3 : Create the database mydatabase and table using the provided SQL commands
STEP 4 : Open notepad, create the code for
dp.php,Select.php,Insert.php,Insert1.php,Update.php,Delete.php,Index.php files.
STEP 5 : All the files names are included in index.php file using include function.
STEP 6 : Save all the php file---local Disc(c) /xampp/htdocs/create any folder to save
STEP 7 : Open the mydatabase from mysql database and import the index.php file
and click the Go button,,
STEP 8 : Finish the coding function.Place the php files in your web server's root directory.
STEP 9 : Access the application via a web
browser(e.g., http://localhost/mydatabase/index.php).
STEP 10 :To run a program open chrome and type localhost/folder name and select the
file to view an output in parent directory.
STEP 11: Stop The APACHE & MYSQL And Close The XAMPP.
13.Queries in a Mysqli database

Php my admin sql queries:


CREATE DATABASE mydatabase;
USE mydatabase;

CREATE TABLE users (


id INT(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
age INT(3) NOT NULL
);
db.php
<?php
$servername = "localhost";
$username = "root"; // Change if you have a different username
$password = ""; // Change if you have a password
$database = "mydatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Select.php
<?php
include 'db.php'; // Include the database connection file
// SQL query to select all records
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
// Check if there are any records
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. " - Age: " .
$row["age"]. "<br>";
}
} else {
echo "0 results";
}$conn->close();?>
Insert.php
include 'db.php'; // Include the database connection file
// Get data from POST request (example)
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];

// SQL query to insert data


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

// Check if the query is successful


if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Insert1.php
<html>
<body>
<form action="insert.php" method="POST">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
Age: <input type="number" name="age" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
// Example of using prepared statement for insert
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?,?)");
$stmt->bind_param("ss", $name, $email);
$name = "John Doe";
$email = "[email protected]";
$stmt->execute();
echo "New record created successfully";
$stmt->close();?>
Update.php
<?php
include 'db.php'; // Include the database connection file
// Get data from POST request
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
// SQL query to update data
$sql = "UPDATE users SET name='$name', email='$email', age=$age WHERE id=$id";
// Check if the query is successful
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Delete.php
<?php
include 'db.php'; // Include the database connection file
// Get data from POST request
$id = $_POST['id'];
// SQL query to delete data
$sql = "DELETE FROM users WHERE id=$id";
// Check if the query is successful
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Output:

Name:
Email:
Age:

Name:
Email: [email protected]
Age: 33

New record created successfully

Result:
14.Product and Category model in Mysqli
AIM:

Develop a PHP program for Product and Category model in Mysqli

ALGORITHM:

STEP 1 : Turn On The PC.


STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.
STEP 3 : Create the database test db and categories and products table using the provided
SQL commands
STEP 4 : Open notepad, create the code for db.php,category.php,product.php,index.php files
STEP 5 : All the files names are included in index.php file using include function.
STEP 6 : Save all the php file---local Disc(c) /xampp/htdocs/create any folder to save
STEP 7 : Open the test db from mysql database and import the index.php file
and click the Go button,,
STEP 8 : Finish the coding function.Place the php files in your web server's root directory.
STEP 9 : Access the application via a web browser(e.g., http://localhost/test db/index.php).
STEP 10 :To run a program open chrome and type localhost/folder name and select the
file to view an output in parent directory.
STEP 11: Stop The APACHE & MYSQL And Close The XAMPP.
14.Product and Category model in Mysqli

Php my admin sql queries:


CREATE DATABASE test db;

USE test db;

-- Create 'categories' table


CREATE TABLE categories (
category_id INT AUTO_INCREMENT PRIMARY KEY,
category_name VARCHAR(255) NOT NULL,
description TEXT
);
-- Create 'products' table
CREATE TABLE products (
product_id INT AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
category_id INT,
FOREIGN KEY (category_id) REFERENCES categories(category_id)
);
db.php
<?php
$host = "localhost"; // MySQL host
$user = "root"; // MySQL username
$pass = ""; // MySQL password
$dbname = "test db"; // Database name
// Create connection
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Category.php
<?php
include_once('db.php');
class Category {
// Create a new category
public static function create($category_name, $description) {
global $conn;
$stmt = $conn->prepare("INSERT INTO categories (category_name, description) VALUES (?,
?)");
$stmt->bind_param("ss", $category_name, $description);
return $stmt->execute();
}
// Get all categories
public static function getAll() {
global $conn;
$result = $conn->query("SELECT * FROM categories");
return $result->fetch_all(MYSQLI_ASSOC);
}
// Get a category by ID
public static function getById($id) {
global $conn;
$stmt = $conn->prepare("SELECT * FROM categories WHERE category_id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
// Update a category
public static function update($id, $category_name, $description) {
global $conn;
$stmt = $conn->prepare("UPDATE categories SET category_name = ?, description = ? WHERE
category_id = ?");
$stmt->bind_param("ssi", $category_name, $description, $id);
return $stmt->execute();
}
// Delete a category
public static function delete($id) {
global $conn;
$stmt = $conn->prepare("DELETE FROM categories WHERE category_id = ?");
$stmt->bind_param("i", $id);
return $stmt->execute();
}
}
?>
Product.php
<?php
include_once('db.php');
class Product {
// Create a new product
public static function create($product_name, $description, $price, $category_id) {
global $conn;
$stmt = $conn->prepare("INSERT INTO products (product_name, description, price,
category_id) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssdi", $product_name, $description, $price, $category_id);
return $stmt->execute();
}
// Get all products
public static function getAll() {
global $conn;
$result = $conn->query("SELECT * FROM products");
return $result->fetch_all(MYSQLI_ASSOC);
}
// Get products by category ID
public static function getByCategory($category_id) {
global $conn;
$stmt = $conn->prepare("SELECT * FROM products WHERE category_id = ?");
$stmt->bind_param("i", $category_id);
$stmt->execute();
return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}
// Get product by ID
public static function getById($id) {
global $conn;
$stmt = $conn->prepare("SELECT * FROM products WHERE product_id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
// Update a product
public static function update($id, $product_name, $description, $price, $category_id) {
global $conn;
$stmt = $conn->prepare("UPDATE products SET product_name = ?, description = ?, price = ?,
category_id = ? WHERE product_id = ?");
$stmt->bind_param("ssdii", $product_name, $description, $price, $category_id, $id);
return $stmt->execute();
}
// Delete a product
public static function delete($id) {
global $conn;
$stmt = $conn->prepare("DELETE FROM products WHERE product_id = ?");
$stmt->bind_param("i", $id);
return $stmt->execute();
}
}
?>
Index.php
<?php
include_once('Category.php');
include_once('Product.php');
// Add a category
Category::create("Electronics", "Devices and gadgets");
// Add a product
$category = Category::getAll()[0]; // Get the first category
Product::create("Smartphone", "Latest model", 699.99, $category['category_id']);
// Display all categories and products
echo "Categories: <br>";
$categories = Category::getAll();
foreach ($categories as $category) {
echo $category['category_name'] . "<br>";
}
echo "Products: <br>";
$products = Product::getAll();
foreach ($products as $product) {
echo $product['product_name'] . " - " . $product['price'] . "<br>";
}
?>
Output:

Result:
15.Php program using method of Mysqli Class
AIM:

Create a PHP program using method of Mysqli Class

ALGORITHM:

STEP 1 : Turn On The PC.


STEP 2 : Open The XAMPP, And Start APACHE & MYSQL.
STEP 3 : Create the model db database and table using the provided SQL commands
STEP 4 : Open notepad, create the code for dp.php file
STEP 5 : All the opertions are included in db.php file using include function.
STEP 6 : Save all the php file---local Disc(c) /xampp/htdocs/create any folder to save
STEP 7 : Open the model db from mysql database and import the db.php file
and click the Go button,,
STEP 8 : Finish the coding function.Place the php files in your web server's root directory.
STEP 9 : Access the application via a web browser(e.g., http://localhost/model db/db.php).
STEP 10 :To run a program open chrome and type localhost/folder name and select the
file to view an output in parent directory.
STEP 11: Stop The APACHE & MYSQL And Close The XAMPP.
15.Php program using method of Mysqli Class

Php my admin sql queries:


CREATE DATABASE model db;

USE model db;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

email VARCHAR(100)

db.php
<?php
// Database connection parameters
$servername = "localhost";
$username = "root"; // Change to your database username
$password = ""; // Change to your database password
$dbname = "model db"; // Change to your database name
// Create a new instance of the mysqli class
$conn = new mysqli($servername, $username, $password, $dbname);

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

// SELECT Operation: Retrieve all users


function getUsers($conn) {
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql); // Using query() method to execute the SELECT query

if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
}

// INSERT Operation: Add a new user


function insertUser($conn, $name, $email) {
// Using prepare() method to prepare an SQL statement and bind_param() to bind parameters
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email); // 'ss' means the parameters are both strings
if ($stmt->execute()) {
echo "New record created successfully.<br>";
} else {
echo "Error: " . $stmt->error . "<br>";
}
$stmt->close(); // Close the prepared statement
}

// UPDATE Operation: Update user details


function updateUser($conn, $id, $newName, $newEmail) {
// Using prepare() method to prepare an UPDATE statement and bind_param() to bind
parameters
$stmt = $conn->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");
$stmt->bind_param("ssi", $newName, $newEmail, $id); // 'ssi' means (string, string, integer)
if ($stmt->execute()) {
echo "Record updated successfully.<br>";
} else {
echo "Error: " . $stmt->error . "<br>";
}
$stmt->close(); // Close the prepared statement
}

// DELETE Operation: Delete a user


function deleteUser($conn, $id) {
// Using prepare() method to prepare a DELETE statement and bind_param() to bind
parameters
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id); // 'i' means the parameter is an integer
if ($stmt->execute()) {
echo "Record deleted successfully.<br>";
} else {
echo "Error: " . $stmt->error . "<br>";
}
$stmt->close(); // Close the prepared statement
}

// Example Usage of Functions

// Display the current users


echo "<h3>Current Users:</h3>";
getUsers($conn); // Select all users

// Insert a new user


echo "<h3>Inserting a New User:</h3>";
insertUser($conn, "Jane Doe", "[email protected]"); // Insert a new user

// Display updated list of users after insertion


echo "<h3>Updated Users:</h3>";
getUsers($conn); // Select all users again to see the update

// Update user with ID 1


echo "<h3>Updating User with ID 1:</h3>";
updateUser($conn, 1, "John Updated", "[email protected]"); // Update user with id 1
// Display users after update
echo "<h3>Updated Users After Update:</h3>";
getUsers($conn); // Select all users after update
// Delete user with ID 1
echo "<h3>Deleting User with ID 1:</h3>";
deleteUser($conn, 1); // Delete user with id 1
// Display users after deletion
echo "<h3>Final Users After Deletion:</h3>";
getUsers($conn); // Select all users after deletion
// Close the database connection
$conn->close();
?>
Output:

Current Users:

ID: 2 - Name: Jane Doe - Email: [email protected]

Inserting a New User:

New record created successfully.

Updated Users:

ID: 2 - Name: Jane Doe - Email: [email protected]


ID: 3 - Name: Jane Doe - Email: [email protected]

Updating User with ID 1:

Record updated successfully.

Updated Users After Update:

ID: 2 - Name: Jane Doe - Email: [email protected]


ID: 3 - Name: Jane Doe - Email: [email protected]

Deleting User with ID 1:

Record deleted successfully.

Final Users After Deletion:

ID: 2 - Name: Jane Doe - Email: [email protected]


ID: 3 - Name: Jane Doe - Email: [email protected]

RESULT:

You might also like