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

php_practical_solution

The document contains various PHP code snippets demonstrating basic programming concepts such as arithmetic operations, area calculation of a circle, date and time formatting, user input handling, and conditional statements. It includes examples of using arrays, loops, and functions to perform tasks like generating Fibonacci series, checking odd/even numbers, and calculating factorials. Additionally, it covers database creation and manipulation for storing student marks.

Uploaded by

darjikushal60
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)
14 views

php_practical_solution

The document contains various PHP code snippets demonstrating basic programming concepts such as arithmetic operations, area calculation of a circle, date and time formatting, user input handling, and conditional statements. It includes examples of using arrays, loops, and functions to perform tasks like generating Fibonacci series, checking odd/even numbers, and calculating factorials. Additionally, it covers database creation and manipulation for storing student marks.

Uploaded by

darjikushal60
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/ 41

1.

Perform arithmetic operations on two pre-define number values

<?php

// Pre-defined numbers
$num1 = 15;
$num2 = 5;

// Addition
$sum = $num1 + $num2;
echo "Addition: " . $sum . "<br>";

// Subtraction
$difference = $num1 - $num2;
echo "Subtraction: " . $difference . "<br>";

// Multiplication
$product = $num1 * $num2;
echo "Multiplication: " . $product . "<br>";

// Division
$quotient = $num1 / $num2;
echo "Division: " . $quotient . "<br>";

// Modulus
$remainder = $num1 % $num2;
echo "Modulus (Remainder): " . $remainder . "<br>";

?>
2. Find area of circle using define (), where Area of circle C=pi*r*r

<?php

// Define the constant for pi


define("PI", 3.14159);

// Pre-defined radius
$r = 5;

// Calculate the area of the circle


$C = PI * $r * $r;

// Display the result


echo "The radius of the circle is: " . $r . "<br>";
echo "The area of the circle is: " . $C;

?>

OR

<?php

// Define the constant PI


define("PI", 3.14);

// Get the radius from user input (POST request)


$radius = $_POST['radius'] ?? 0;

// Calculate the area of the circle


$area = PI * $radius * $radius;

// Display the result


echo "The area of the circle with radius $radius is: $area";

?>
<html>
<body>
<form method="POST">
Enter the radius of the circle : <input type="text" name="radius">
<button type="submit">Calculate</button>
</form>
</body>
</html>

3. Print current date and time using date () function

<?php

// Print current date and time in the specified format


echo "Current date and time: " .date("d/m/y h:i:s a");

?>

4. Display current date in different formats. in following format :


 dd/mm/yy
 dd/mm/yyyy
 dd MON yyyy
 Day, dd MON yyyy
 Day, dd MONTH yyyy

<?php
// Current date in dd/mm/yy format
echo "dd/mm/yy: " . date("d/m/y") . "<br>";

// Current date in dd/mm/yyyy format


echo "dd/mm/yyyy: " . date("d/m/Y") . "<br>";
// Current date in dd MON yyyy format
echo "dd MON yyyy: " . date("d M Y") . "<br>";

// Current date in Day, dd MON yyyy format


echo "Day, dd MON yyyy: " . date("l, d M Y") . "<br>";

// Current date in Day, dd MONTH yyyy format


echo "Day, dd MONTH yyyy: " . date("l, d F Y") . "<br>";
?>

5. Write a program to check whether Today’s date is match with system’s


current date or not. (using if statement).

<?php
// Get today's date
$todayDate = date("d-m-y");

// Get system's current date


$currentDate = date("d-m-y");
// Check if they match
if ($todayDate === $currentDate) {
echo "Today's date matches the system's current date.";
} else {
echo "Today's date does not match the system's current date.";
}
?>

OR
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Get the user input from the form
$userInput = $_POST["date"];
$currentDate = date("Y-m-d");

if ($userInput === $currentDate) {


echo "The entered date matches the system's current date.";
} else {
echo "The entered date does not match the system's current date.";
}
}
?>
<html>
<body>
<form method="post" action="">
Enter today's date:<input type="date" id="date" name="date"
required>
<button type="submit">Submit</button>
</form>
</body>
</html>
6. Read a number from the user and check whether the entered number is
odd or even

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

//divide entered number by 2


//if the reminder is 0 then the number is even otherwise the number is
odd
if(($number % 2) == 0)
{
echo "$number is an Even number";
}
else
{
echo "$number is Odd number";
}
}
?>

<html>
<body>
<form method="post">
Enter a number:
<input type="number" name="number">
<input type="submit" value="Submit">
</form>
</body>
</html>

7. Find maximum number among three numbers (use if..else statement)

<?php

$n1 = 12;
$n2 = 7;
$n3 = 15;

if ($n1 > $n2 && $n1 > $n3)


{
echo "The largest number is: $n1\n";
}
elseif ($n2 > $n1 && $n2 > $n3)
{
echo "The largest number is: $n2\n";
}
else
{
echo "The largest number is: $n3\n";
}

?>
8. Read two numbers and choice as an operator (+,-,*,/) from the user and
perform an arithmetic operation based on user choice (use Switch case
and passing the parameter between two pages).

 File : tybca.php

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get values from the form
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operator = $_POST['operator'];

// Perform operation based on the operator


$result = null;
switch ($operator) {
case '+':
$result = $num1 + $num2;
break;
case '-':
$result = $num1 - $num2;
break;
case '*':
$result = $num1 * $num2;
break;
case '/':
$result = ($num2 != 0) ? $num1 / $num2 : "Cannot divide
by zero";
break;
default:
$result = "Invalid operator.";
}
}
// Display the result
echo "<h1>Result</h1>";
echo "First Number: $num1<br>";
echo "Second Number: $num2<br>";
echo "Operator: $operator<br>";
echo "Result: $result<br>";
?>

 File : tyhtml.html

<html>
<body>
<form action="tybca.php" method="POST">
Enter no1 : <input type="number" name="number1"><br><br>
Enter no2 : <input type="number" name="number2"><br><br>
Select operator : <select name="operator">
<option value="+">Add</option>
<option value="-">sub</option>
<option value="*">mul</option>
<option value="/">div</option>
</select>
<button type="submit">calculate</button>
</form>
</body>
</html>

9. Use $_POST[], $_GET[], $_SERVER[‘PHP_SELF’] or isSet()


appropriately and create,
i. Create Fibonacci series for given number.
ii. Design simple calculator.
iii. Find factorial of given number.
iv. Find sum of factorial for given number.

 Create Fibonacci series for given number.

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


Enter a number: <input type="number" name="fib_number" required>
<button type="submit" name="fibonacci">Generate Fibonacci</button>
</form>

<?php
if (isset($_POST['fibonacci'])) {
$n = $_POST['fib_number'];
$a = 0;
$b = 1;
echo "<p>Fibonacci series for $n terms:</p>";
echo "$a, $b";
for ($i = 2; $i < $n; $i++) {
$c = $a + $b;
echo ", $c";
$a = $b;
$b = $c;
}
echo "<br>";
}
?>

 Design simple calculator.

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


Enter Number1: <input type="number" name="calc_num1" required><br>
Enter Number2: <input type="number" name="calc_num2" required><br>
Select Operator:
<select name="operator" required>
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br>
<button type="submit" name="calculate">Calculate</button>
</form>

<?php
if (isset($_POST['calculate'])) {
$num1 = $_POST['calc_num1'];
$num2 = $_POST['calc_num2'];
$operator = $_POST['operator'];

$result = "Invalid operation";

switch ($operator) {
case '+':
$result = $num1 + $num2;
break;

case '-':
$result = $num1 - $num2;
break;

case '*':
$result = $num1 * $num2;
break;

case '/':
$result = ($num2 != 0) ? $num1 / $num2 : "Cannot divide by zero";
break;
}
echo "<p>Result: $result</p>";
}
?>

 Find factorial of given number.

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


Enter number: <input type="number" name="factorial_number" required>
<button type="submit" name="find_factorial">Find Factorial</button>
</form>

<?php
if (isset($_POST['find_factorial'])) {
$n = $_POST['factorial_number'];
$factorial = 1;
for ($i = 1; $i <= $n; $i++) {
$factorial *= $i;
}
echo "<p>Factorial of $n is: $factorial</p>";
}
?>
 Find sum of factorial for given number

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


Enter number:<input type="number" name="sum_factorial_number" required>
<button type="submit" name="sum_factorials">Sum of Factorials</button>
</form>
<?php
if (isset($_POST['sum_factorials'])) {
$n = $_POST['sum_factorial_number'];
$sum = 0;

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


$factorial = 1;
for ($j = 1; $j <= $i; $j++) {
$factorial *= $j;
}
$sum += $factorial;
}
echo "<p>Sum of factorials up to $n is: $sum</p>";
}
?>
</body>
</html>
10. Create an array of type Numeric and an Associative and display its
elements on screen.

<?php
// Numeric Array
$numericArray = array(10, 20, 30, 40, 50);

// Associative Array
$associativeArray = array(
"name" => "John Doe",
"age" => 25,
"city" => "New York"
);

// Displaying Numeric Array Elements


echo "<h3>Numeric Array Elements:</h3>";
foreach ($numericArray as $index) {
echo $index."<br>";
}

// Displaying Associative Array Elements


echo "<h3>Associative Array Elements:</h3>";
foreach ($associativeArray as $key => $value) {
echo "$key: $value<br>";
}
?>
11. Create an array with Ten elements, find maximum and minimum
elements from it (Use foreach() statement). Also arrange array elements
in Ascending and Descending order.

<?php
// Create an array with ten elements
$numbers = array(23, 45, 12, 67, 34, 89, 10, 56, 78, 5);

echo "Original Array: ";


foreach ($numbers as $num) {
echo $num . " ";
}
echo "<br>";

// Initialize max and min with the first element


$max = $numbers[0];
$min = $numbers[0];

// Find maximum and minimum using foreach()


foreach ($numbers as $number) {
if ($number > $max) $max = $number;
if ($number < $min) $min = $number;
}

echo "Maximum: $max<br>";


echo "Minimum: $min<br>";

// Sort the array in ascending and descending order


$ascending = $numbers;
sort($ascending);

$descending = $numbers;
rsort($descending);

echo "Ascending Order: ";


foreach ($ascending as $num) {
echo $num . " ";
}
echo "<br>";

echo "Descending Order: ";


foreach ($descending as $num) {
echo $num . " ";
}
?>

12. Find occurrence of character within a given string. (Use for loop)

<form method="POST">
Enter string : <input type="text" name="sring1"><br>
Enter any char : <input type="text" name="char1">
<input type="submit" value="submit">
</form>

<?php
$str1=$_POST["sring1"];
$chr1=$_POST["char1"];

$c=0;
for($i=0;$i<strlen($str1);$i++)
{
if($str1[$i]==$chr1)
{
$c++;
}
}

echo "character '$chr1' occurs $c times in the string : $str1";


?>

13. Write a program to Read number from the user and generate a series of
odd and even number up to given number. i.e. No=10 then series of Odd
number : 1,3,5,7,9 and Even number is : 2,4,6,8,10

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number =$_POST["number"];

if ($number > 0) {
echo "Series of Odd Numbers: ";
for ($i = 1; $i <= $number; $i++) {
if ($i % 2 != 0) {
echo $i . (($i + 2 <= $number) ? ", " : "");
}
}

echo "<br>Series of Even Numbers: ";


for ($i = 1; $i <= $number; $i++) {
if ($i % 2 == 0) {
echo $i . (($i + 2 <= $number) ? ", " : "");
}
}
} else {
echo "Please enter a positive number.";
}
}
?>

<form method="post">
Enter a Number:<input type="number" name="number" id="number"
required>
<button type="submit">Generate Series</button>
</form>

14. Create mark sheet of 3 subject's marks for sem-6 and calculate total with
percentage. Insert data into database and display all the records. Where,
Database: Marksheet
Table: Marks.

 Create database and table

CREATE DATABASE Marksheet;

USE Marksheet;

CREATE TABLE Marks (


Roll_no INT(3),
name VARCHAR(10),
m1 INT(3),
m2 INT(3),
m3 INT(3),
Total INT(3),
Per DOUBLE(5, 2)
);

 Marks.html

<html>
<body>
<h1><center>Student's Marksheet<center></h1>
<form action="process_marks.php" method="post">
<table border="1" cellpadding="10" cellspacing="0"
align="center">
<tr>
<td>Roll No:</td>
<td><input type="number" id="roll_no" name="roll_no"
required></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" id="name" name="name"
required></td>
</tr>
<tr>
<td>Marks for Subject 1:</td>
<td><input type="number" id="m1" name="m1"
required></td>

</tr>
<tr>
<td>Marks for Subject 2:</td>
<td><input type="number" id="m2" name="m2"
required></td>

</tr>
<tr>
<td>Marks for Subject 3:</td>
<td><input type="number" id="m3" name="m3"
required></td>

</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>
</body>
</html>
 process_marks.php

<?php
// Connection to MySQL Database
$conn = new mysqli("localhost", "root", "", "Marksheet");

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

// Check if form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$roll_no = $_POST["roll_no"];
$name = $_POST["name"];
$m1 = $_POST["m1"];
$m2 = $_POST["m2"];
$m3 = $_POST["m3"];

// Calculate total and percentage


$total = $m1 + $m2 + $m3;
$percentage = ($total / 300) * 100;

// Insert data into table


$sql = "INSERT INTO Marks (Roll_no, name, m1, m2, m3, Total,
Per)
VALUES ($roll_no, '$name', $m1, $m2, $m3, $total,
$percentage)";
$conn->query($sql);

// Fetch and display all records


$result = $conn->query("SELECT * FROM Marks");

echo "<h1><center>Student's Marksheet<center></h1>";


echo "<table border='1' align='center'>
<tr>
<th>Roll No</th>
<th>Name</th>
<th>Subject 1</th>
<th>Subject 2</th>
<th>Subject 3</th>
<th>Total</th>
<th>Percentage</th>
</tr>";

// Fetch all rows at once


$rows = $result->fetch_all(MYSQLI_ASSOC);

// Use foreach loop to iterate through rows


foreach ($rows as $row) {
echo "<tr>
<td>{$row['Roll_no']}</td>
<td>{$row['name']}</td>
<td>{$row['m1']}</td>
<td>{$row['m2']}</td>
<td>{$row['m3']}</td>
<td>{$row['Total']}</td>
<td>{$row['Per']}%</td>
</tr>";
}

echo "</table>";

// Close connection
$conn->close();
?>
15. Design a login form and validate to username=”ADMIN” and
password=”XXX”. Display appropriate message on submitting form.

<?php
// Database connection settings
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tybca";

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

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

// Initialize variables
$message = "";
$loggedInUser = isset($_GET['username']) ?
htmlspecialchars($_GET['username']) : null;

// Handle login
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];

// Validate user credentials


$sql = "SELECT * FROM login WHERE u_name = '$username' AND
u_password = '$password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// Redirect with username in query string
header("Location: ?username=" . urlencode($username));
exit;
} else {
$message = "Invalid username or password.";
}
}

// Handle logout
if (isset($_GET['logout'])) {
header("Location: ?");
exit;
}

$conn->close();
?>
<html>
<head>
<title>Login Page</title>
<style>
table {
border-collapse: collapse;
width: 30%;
margin: auto;
}
td {
padding: 10px;
}
.center {
text-align: center;
}
</style>
</head>
<body>
<?php if ($loggedInUser): ?>
<h2 class="center">Welcome, <?php echo $loggedInUser; ?>!</h2>
<p class="center"><a href="?logout=true">Sign out</a></p>
<?php else: ?>
<h2 class="center">Login</h2>
<form method="post">
<table border="1">
<tr>
<td><label>Username:</label></td>
<td><input type="text" name="username" required></td>
</tr>
<tr>
<td><label>Password:</label></td>
<td><input type="password" name="password" required></td>
</tr>
<tr>
<td colspan="2" class="center">
<button type="submit" name="login">Login</button>
</td>
</tr>
</table>
</form>
<?php if ($message): ?>
<p class="center" style="color:red;"><?php echo $message; ?></p>
<?php endif; ?>
<?php endif; ?>
</body>
</html>
16. Delete multiple records from the database based on given ID. (For
Database and Table refer definition no-14)

Marks.html
<!DOCTYPE html>
<html>
<head>
<title>Student's Marksheet</title>
</head>
<body>
<h1><center>Student's Marksheet</center></h1>
<form action="process_marks.php" method="post">
<table border="1" cellpadding="10" cellspacing="0" align="center">
<tr>
<td>Roll No:</td>
<td><input type="number" id="roll_no" name="roll_no"
required></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" id="name" name="name" required></td>
</tr>
<tr>
<td>Marks for Subject 1:</td>
<td><input type="number" id="m1" name="m1" required></td>
</tr>
<tr>
<td>Marks for Subject 2:</td>
<td><input type="number" id="m2" name="m2" required></td>
</tr>
<tr>
<td>Marks for Subject 3:</td>
<td><input type="number" id="m3" name="m3" required></td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">Submit</button>
</td>
</tr>
</table>
</form>

<br><br>

<?php
// Check if form has been submitted (to display records)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Include the process_marks.php to fetch and display records
include 'process_marks.php';
}
?>

</body>
</html>

Process_marks.php

<?php
// Connection to MySQL Database
$conn = new mysqli("localhost", "root", "", "Marksheet");

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

// Check if form is submitted for deletion


if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_POST['delete'])) {
// Get the list of selected records to delete
if (isset($_POST['delete_records'])) {
$delete_ids = $_POST['delete_records'];

// Delete selected records


foreach ($delete_ids as $id) {
$conn->query("DELETE FROM Marks WHERE Roll_no = $id");
}
}
}

// Check if form is submitted for adding new marks


if ($_SERVER["REQUEST_METHOD"] == "POST" &&
!isset($_POST['delete'])) {
// Get form data
if (isset($_POST["roll_no"]) && isset($_POST["name"]) &&
isset($_POST["m1"]) && isset($_POST["m2"]) && isset($_POST["m3"])) {
$roll_no = $_POST["roll_no"];
$name = $_POST["name"];
$m1 = $_POST["m1"];
$m2 = $_POST["m2"];
$m3 = $_POST["m3"];

// Calculate total and percentage


$total = $m1 + $m2 + $m3;
$percentage = ($total / 300) * 100;

// Insert data into table


$sql = "INSERT INTO Marks (Roll_no, name, m1, m2, m3, Total, Per)
VALUES ($roll_no, '$name', $m1, $m2, $m3, $total,
$percentage)";
$conn->query($sql);
}
}
// Fetch and display all records after form submission
$result = $conn->query("SELECT * FROM Marks");

if ($result->num_rows > 0) {
echo "<h1><center>View Student Records</center></h1>";
echo "<form method='POST' action='process_marks.php'>";
echo "<table border='1' align='center'>
<tr>

<th>Select</th>
<th>Roll No</th>
<th>Name</th>
<th>Subject 1</th>
<th>Subject 2</th>
<th>Subject 3</th>
<th>Total</th>
<th>Percentage</th>
</tr>";

// Use while loop to iterate through rows


while ($row = $result->fetch_assoc()) {
echo "<tr>
<td><input type='checkbox' name='delete_records[]'
value='{$row['Roll_no']}'></td>
<td>{$row['Roll_no']}</td>
<td>{$row['name']}</td>
<td>{$row['m1']}</td>
<td>{$row['m2']}</td>
<td>{$row['m3']}</td>
<td>{$row['Total']}</td>
<td>{$row['Per']}%</td>

</tr>";
}
echo "</table><br>";

echo "<div style='text-align: center;'>";


echo "<button type='submit' name='delete'>Delete Selected</button> ";
echo "<button type='reset' value='Clear'
onclick='clearSelections()'>Clear</button>";
echo "</div>";
echo "</form>";
} else {
echo "<h2>No records found.</h2>";
}

// Close connection
$conn->close();
?>

17. Create menu driven program which display, insert, update and delete
records from the database “Birthdays”, from table bdate.mdf having
fields ID-int(3)(auto increment), fname-varchar(10), Lname-
varchar(10), and bdate-DATE.

 Create database and table


CREATE DATABASE Birthdays;
USE Birthdays;
CREATE TABLE bdate
(
ID INT AUTO_INCREMENT PRIMARY KEY,
fname VARCHAR(50) NOT NULL,
lname VARCHAR(50) NOT NULL,
bdate DATE NOT NULL
);
menu.php

<html>
<center>
<body>
<h2>CRUD Operations Menu</h2><br>

<a href="insert.php"><button>Insert Record</button></a><br><br>


<a href="update.php"><button>Update Record</button></a><br><br>
<a href="delete.php"><button>Delete Record</button></a><br><br>
<a href="select.php"><button>View Records</button></a><br><br>

</body>
</center>
</html>

insert.php

<?php
// Database Connection
$servername = "localhost";
$username = "root"; // Change if needed
$password = "";
$dbname = "Birthdays";

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


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

if (isset($_POST['add'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$bdate = $_POST['bdate'];

$query = "INSERT INTO bdate (fname, lname, bdate) VALUES ('$fname', '$lname', '$bdate')";
if ($conn->query($query) === TRUE) {
echo "Record added successfully.";
} else {
echo "Error: " . $conn->error;
}
}
?>

<html>
<body>
<h2>Insert New Record</h2>
<form method="post">
<input type="text" name="fname" placeholder="First Name" required>
<input type="text" name="lname" placeholder="Last Name" required>
<input type="date" name="bdate" required>
<input type="submit" name="add" value="Add Record">
<button type='reset' value='Clear' onclick='clearSelections()'>Clear</button>
</form><br>
<a href="menu.php">Back to Menu</a>
</body>
</html>

update.php

<?php
// Database Connection
$servername = "localhost";
$username = "root"; // Change if needed
$password = "";
$dbname = "Birthdays";

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


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

if (isset($_POST['update'])) {
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$bdate = $_POST['bdate'];

$query = "UPDATE bdate SET fname='$fname', lname='$lname', bdate='$bdate'


WHERE ID=$id";
if ($conn->query($query) === TRUE) {
echo "Record updated successfully.";
} else {
echo "Error: " . $conn->error;
}
}
?>

<html>
<body>
<h2>Update Record</h2>
<form method="post">
<input type="text" name="id" placeholder="ID to Update" required>
<input type="text" name="fname" placeholder="New First Name" required>
<input type="text" name="lname" placeholder="New Last Name" required>
<input type="date" name="bdate" required>
<input type="submit" name="update" value="Update Record">
<button type='reset' value='Clear' onclick='clearSelections()'>Clear</button>
</form>
<a href="menu.php">Back to Menu</a>
</body>
</html>

delete.php

<?php
// Database Connection
$servername = "localhost";
$username = "root"; // Change if needed
$password = "";
$dbname = "Birthdays";

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


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

if (isset($_POST['delete'])) {
$id = $_POST['id'];
$query = "DELETE FROM bdate WHERE ID=$id";

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


echo "Record deleted successfully.";
} else {
echo "Error: " . $conn->error;
}
}
?>
<html>
<body>
<h2>Delete Record</h2>
<form method="post">
<input type="text" name="id" placeholder="ID to Delete" required>
<input type="submit" name="delete" value="Delete Record">
</form>
<a href="menu.php">Back to Menu</a>
</body>
</html>

select.php

<?php
// Database Connection
$servername = "localhost";
$username = "root"; // Change if needed
$password = "";
$dbname = "Birthdays";

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


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

$result = $conn->query("SELECT * FROM bdate");


?>

<html>
<body>
<h2>Records in Database</h2>
<table border="1">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Birth Date</th>
</tr>
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?= $row['ID'] ?></td>
<td><?= $row['fname'] ?></td>
<td><?= $row['lname'] ?></td>
<td><?= $row['bdate'] ?></td>
</tr>
<?php } ?>
</table>
<a href="menu.php">Back to Menu</a>
</body>
</html>

18. Write a script which store the password of the user using cookies and
retrieve it using appropriate table.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
$remember = isset($_POST["remember"]);

if ($remember) {
setcookie("username", $username, time() + (86400 * 30), "/");
setcookie("password", $password, time() + (86400 * 30), "/");
} else {
setcookie("username", "", time() - 3600, "/");
setcookie("password", "", time() - 3600, "/");
}
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Login with Remember Me</title>
</head>
<body>
<form method="POST">
<label>Username:</label>
<input type="text" name="username" value="<?php echo
isset($_COOKIE["username"]) ? $_COOKIE["username"] : ''; ?>"
required><br>
<label>Password:</label>
<input type="password" name="password" value="<?php echo
isset($_COOKIE["password"]) ? $_COOKIE["password"] : ''; ?>"
required><br>

<input type="checkbox" name="remember" <?php echo


isset($_COOKIE["username"]) ? 'checked' : ''; ?>>Remember Me<br>

<button type="submit">Save</button>
</form>
</body>
</html>

19. Count the number of page hit using session variable

<?php

session_start();

if (isset($_SESSION['page_hits'])) {
$_SESSION['page_hits']++;
} else {

$_SESSION['page_hits'] = 1;
}

echo "You have visited this page " . $_SESSION['page_hits'] . " times.";
?>
21. Write a function to validate email (using Regular Expression).
<?php
// Define variables and set to empty values
$name = $email = $website = $comment = $gender = "";
$nameErr = $emailErr = $genderErr = "";
$websiteErr = "";

// Handle form submission


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Name Validation
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = trim($_POST["name"]); // Remove extra spaces
$name = stripslashes($name); // Remove backslashes
$name = htmlspecialchars($name); // Convert special characters
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed, no numbers";
}
}

// Email Validation
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = trim($_POST["email"]);
$email = stripslashes($email);
$email = htmlspecialchars($email);
if (!preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email))
{
$emailErr = "Invalid email format";
}
}

// Website Validation (if provided)


if (!empty($_POST["website"])) {
$website = trim($_POST["website"]);
$website = stripslashes($website);
$website = htmlspecialchars($website);
if (!filter_var($website, FILTER_VALIDATE_URL)) {
$websiteErr = "Invalid URL format";
}
}

// Comment Sanitization (optional)


$comment=!empty($_POST["comment"])?
htmlspecialchars(stripslashes(trim($_POST["comment"]))) : "";

// Gender Validation
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = trim($_POST["gender"]);
$gender = stripslashes($gender);
$gender = htmlspecialchars($gender);
}
}
?>
<html>
<head>
<title>PHP Form Validation</title>
<style>
.error { color: red; }
</style>
</head>
<body>

<h2>PHP Form Validation Example</h2>

<?php if ($_SERVER["REQUEST_METHOD"] == "POST" && !$nameErr && !$emailErr &&


!$genderErr && !$websiteErr): ?>
<h3>Form Submitted Successfully!</h3>
<h2>Your Input:</h2>
<p><strong>Name:</strong> <?= $name; ?></p>
<p><strong>Email:</strong> <?= $email; ?></p>
<p><strong>Website:</strong> <?= $website ?: "N/A"; ?></p>
<p><strong>Comment:</strong> <?= nl2br($comment); ?></p>
<p><strong>Gender:</strong> <?= $gender; ?></p>
<?php else: ?>
<!-- Show form with required fields if there are errors or form hasn't been submitted -->
<p><span class="error">* required field</span></p>

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


Name: <input type="text" name="name" value="<?= $name; ?>">
<span class="error">* <?= $nameErr; ?></span>

<br><br>
E-mail: <input type="text" name="email" value="<?= $email; ?>">
<span class="error">* <?= $emailErr; ?></span>
<br><br>

<br><br>

Website: <input type="text" name="website" value="<?= $website; ?>">


<span class="error"><?= $websiteErr; ?></span>
<br><br>

Comment: <textarea name="comment" rows="5" cols="40"><?= $comment; ?></textarea>


<br><br>

Gender:
<input type="radio" name="gender" value="Female" <?= ($gender == "Female") ?
"checked" : ""; ?>> Female
<input type="radio" name="gender" value="Male" <?= ($gender == "Male") ? "checked" :
""; ?>> Male
<input type="radio" name="gender" value="Other" <?= ($gender == "Other") ? "checked" :
""; ?>> Other
<?php if (empty($gender) && $genderErr != ""): ?>
<span class="error">* <?= $genderErr; ?></span>
<?php endif; ?>
<br><br>

<input type="submit" value="Submit">


</form>
<?php endif; ?>
</body>
</html>
22. Create PHP program to upload image / document file and store it in
separate folder on local machine
<html>
<body>
<form action="program22.php" method="post" enctype="multipart/form-data">
select image:
<input type="file" name="image"><br>
<input type="submit" name="submit" value="Upload">
</form>
</body>

</html>

<?php
$ae = ['jpg', 'jpeg', 'png'];
if (isset($_POST['submit'])) {
$file = $_FILES["image"];
$imgname = $_FILES["image"]["name"];
$tmpn = $_FILES['image']["tmp_name"];

$f = "image/" . $imgname;
if (move_uploaded_file($tmpn, $f) === true) { ?>
<html>

<body>
<img src="<?php echo $f; ?>" alt="hii">
</body>
</html>
<?php }
}
?>

You might also like