php_practical_solution
php_practical_solution
<?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
// Pre-defined radius
$r = 5;
?>
OR
<?php
?>
<html>
<body>
<form method="POST">
Enter the radius of the circle : <input type="text" name="radius">
<button type="submit">Calculate</button>
</form>
</body>
</html>
<?php
?>
<?php
// Current date in dd/mm/yy format
echo "dd/mm/yy: " . date("d/m/y") . "<br>";
<?php
// Get today's date
$todayDate = date("d-m-y");
OR
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Get the user input from the form
$userInput = $_POST["date"];
$currentDate = date("Y-m-d");
<?php
if($_POST){
$number = $_POST['number'];
<html>
<body>
<form method="post">
Enter a number:
<input type="number" name="number">
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$n1 = 12;
$n2 = 7;
$n3 = 15;
?>
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'];
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>
<?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>";
}
?>
<?php
if (isset($_POST['calculate'])) {
$num1 = $_POST['calc_num1'];
$num2 = $_POST['calc_num2'];
$operator = $_POST['operator'];
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>";
}
?>
<?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
<?php
// Numeric Array
$numericArray = array(10, 20, 30, 40, 50);
// Associative Array
$associativeArray = array(
"name" => "John Doe",
"age" => 25,
"city" => "New York"
);
<?php
// Create an array with ten elements
$numbers = array(23, 45, 12, 67, 34, 89, 10, 56, 78, 5);
$descending = $numbers;
rsort($descending);
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++;
}
}
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) ? ", " : "");
}
}
<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.
USE Marksheet;
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);
}
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'];
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);
}
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>";
</tr>";
}
echo "</table><br>";
// 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.
<html>
<center>
<body>
<h2>CRUD Operations Menu</h2><br>
</body>
</center>
</html>
insert.php
<?php
// Database Connection
$servername = "localhost";
$username = "root"; // Change if needed
$password = "";
$dbname = "Birthdays";
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";
if (isset($_POST['update'])) {
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$bdate = $_POST['bdate'];
<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";
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$query = "DELETE FROM bdate WHERE ID=$id";
select.php
<?php
// Database Connection
$servername = "localhost";
$username = "root"; // Change if needed
$password = "";
$dbname = "Birthdays";
<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>
<button type="submit">Save</button>
</form>
</body>
</html>
<?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 = "";
// 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";
}
}
// 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>
<br><br>
E-mail: <input type="text" name="email" value="<?= $email; ?>">
<span class="error">* <?= $emailErr; ?></span>
<br><br>
<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>
</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 }
}
?>