0% found this document useful (0 votes)
5 views24 pages

Web Practical

The document contains a series of practical PHP exercises demonstrating various programming concepts, including HTML forms, arithmetic and comparison operators, matrix addition, factorial calculation, string and date functions, cookie handling, exception handling, and database operations. Each practical includes code snippets and explanations for tasks such as displaying user input, calculating grades, and managing customer records in a MySQL database. The exercises are designed to provide hands-on experience with PHP and web development techniques.

Uploaded by

Harshita Patel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views24 pages

Web Practical

The document contains a series of practical PHP exercises demonstrating various programming concepts, including HTML forms, arithmetic and comparison operators, matrix addition, factorial calculation, string and date functions, cookie handling, exception handling, and database operations. Each practical includes code snippets and explanations for tasks such as displaying user input, calculating grades, and managing customer records in a MySQL database. The exercises are designed to provide hands-on experience with PHP and web development techniques.

Uploaded by

Harshita Patel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Practical 1

To create an HTML form that accepts a user name and displays it using PHP echo.

✅ Code:

HTML

<!DOCTYPE html>

<html>

<head>

<title>Display Name</title>

</head>

<body>

<form method="post">

Enter your name:

<input type="text" name="username">

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

</form>

<?php

if(isset($_POST['submit']))

$name = $_POST['username'];

echo "Your Name is: " . $name;

?>

</body>

</html>
Practical 2 write a PHP script to demonstrate arithmetic operator, comparison operator,
logical operator.

<?php

// Arithmetic Operators

$a = 10;

$b = 3;

echo "<h3>Arithmetic Operators</h3>";

echo "a = $a, b = $b <br>";

echo "Addition (a + b): " . ($a + $b) . "<br>";

echo "Subtraction (a - b): " . ($a - $b) . "<br>";

echo "Multiplication (a * b): " . ($a * $b) . "<br>";

echo "Division (a / b): " . ($a / $b) . "<br>";

echo "Modulus (a % b): " . ($a % $b) . "<br>";

echo "Increment (++a): " . (++$a) . "<br>";

echo "Decrement (--b): " . (--$b) . "<br>";

// Comparison Operators

$x = 5;

$y = "5";

echo "<h3>Comparison Operators</h3>";

echo "x = $x, y = '$y' <br>";

echo "Equal (x == y): " . var_export($x == $y, true) . "<br>";

echo "Identical (x === y): " . var_export($x === $y, true) . "<br>";

echo "Not Equal (x != y): " . var_export($x != $y, true) . "<br>";

echo "Greater than (x > y): " . var_export($x > $y, true) . "<br>";

echo "Less than (x < y): " . var_export($x < $y, true) . "<br>";
// Logical Operators

$p = true;

$q = false;

echo "<h3>Logical Operators</h3>";

echo "p = true, q = false <br>";

echo "AND (p && q): " . var_export($p && $q, true) . "<br>";

echo "OR (p || q): " . var_export($p || $q, true) . "<br>";

echo "NOT (!p): " . var_export(!$p, true) . "<br>";

echo "XOR (p xor q): " . var_export($p xor $q, true) . "<br>";

?>
Practical 3 write PHP Script to input marks, generate result and display grade.

<!DOCTYPE html>

<html>

<head>

<title>Student Result</title>

</head>

<body>

<h2>Enter Your Marks</h2>

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

<label for="marks">Marks (out of 100):</label>

<input type="number" id="marks" name="marks" min="0" max="100" required>

<input type="submit" value="Generate Result">

</form>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$marks = $_POST['marks'];

echo "<h3>Your Marks: $marks</h3>";

// Generate grade based on marks

if ($marks >= 90) {

$grade = "A+";

} elseif ($marks >= 80) {

$grade = "A";

} elseif ($marks >= 70) {

$grade = "B";

} elseif ($marks >= 60) {


$grade = "C";

} elseif ($marks >= 50) {

$grade = "D";

} else {

$grade = "F (Fail)";

echo "<h3>Your Grade: $grade</h3>";

?>

</body>

</html>
Practical 4- Write PHP Script of addition of two 2*2 matrices.

<?php

// Define two 2x2 matrices

$matrix1 = array(

array(1, 2),

array(3, 4)

);

$matrix2 = array(

array(5, 6),

array(7, 8)

);

// Initialize result matrix

$result = array();

// Perform addition

for ($i = 0; $i < 2; $i++) {

for ($j = 0; $j < 2; $j++) {

$result[$i][$j] = $matrix1[$i][$j] + $matrix2[$i][$j];

// Display matrices and result

echo "<h3>Matrix 1:</h3>";

for ($i = 0; $i < 2; $i++) {

for ($j = 0; $j < 2; $j++) {

echo $matrix1[$i][$j] . " ";


}

echo "<br>";

echo "<h3>Matrix 2:</h3>";

for ($i = 0; $i < 2; $i++) {

for ($j = 0; $j < 2; $j++) {

echo $matrix2[$i][$j] . " ";

echo "<br>";

echo "<h3>Result (Matrix1 + Matrix2):</h3>";

for ($i = 0; $i < 2; $i++) {

for ($j = 0; $j < 2; $j++) {

echo $result[$i][$j] . " ";

echo "<br>";

?>

Output

If you run this script, you’ll see:

Matrix 1:

12

34

Matrix 2:
56

78

Result (Matrix1 + Matrix2):

68

10 12
Practical 5- write PHP Script to obtain factorial of number using function.

<!DOCTYPE html>

<html>

<head>

<title>Factorial Calculator</title>

</head>

<body>

<h2>Factorial of a Number</h2>

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

<label for="num">Enter a number:</label>

<input type="number" id="num" name="num" min="0" required>

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

</form>

<?php

// Function to calculate factorial

function factorial($n) {

if ($n == 0 || $n == 1) {

return 1;

} else {

return $n * factorial($n - 1);

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$number = $_POST['num'];

$result = factorial($number);
echo "<h3>Factorial of $number is: $result</h3>";

?>

</body>

</html>
Practical 6- write PHP script to demonstrate string, date and math function.

<?php

echo "<h2>PHP Functions Demonstration</h2>";

// STRING FUNCTIONS

echo "<h3>String Functions</h3>";

$str = "Hello Harshita!";

echo "Original String: $str <br>";

echo "String Length (strlen): " . strlen($str) . "<br>";

echo "Word Count (str_word_count): " . str_word_count($str) . "<br>";

echo "Reverse String (strrev): " . strrev($str) . "<br>";

echo "Uppercase (strtoupper): " . strtoupper($str) . "<br>";

echo "Lowercase (strtolower): " . strtolower($str) . "<br>";

echo "Replace (str_replace): " . str_replace("Harshita", "World", $str) . "<br>";

// DATE FUNCTIONS

echo "<h3>Date Functions</h3>";

echo "Current Date (d-m-Y): " . date("d-m-Y") . "<br>";

echo "Current Time (H:i:s): " . date("H:i:s") . "<br>";

echo "Day of Week: " . date("l") . "<br>";

echo "Month Name: " . date("F") . "<br>";

echo "Timestamp (time): " . time() . "<br>";

// MATH FUNCTIONS

echo "<h3>Math Functions</h3>";

$num = -25.7;

echo "Number: $num <br>";

echo "Absolute Value (abs): " . abs($num) . "<br>";


echo "Round (round): " . round($num) . "<br>";

echo "Ceil (ceil): " . ceil($num) . "<br>";

echo "Floor (floor): " . floor($num) . "<br>";

echo "Square Root (sqrt): " . sqrt(81) . "<br>";

echo "Power (pow): " . pow(2, 5) . "<br>";

echo "Random Number (rand): " . rand(1, 100) . "<br>";

?>
Practical 7- Write PHP script to demonstrate passing variables with cookies.

<?php

// Check if the form is submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$username = $_POST['username'];

// Set cookie (valid for 1 hour)

setcookie("user", $username, time() + 3600, "/");

echo "<h3>Cookie has been set! Reload the page to see the stored value.</h3>";

?>

<!DOCTYPE html>

<html>

<head>

<title>Cookie Demo</title>

</head>

<body>

<h2>Passing Variables with Cookies</h2>

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

<label for="username">Enter your name:</label>

<input type="text" id="username" name="username" required>

<input type="submit" value="Set Cookie">

</form>

<?php

// Display cookie value if it exists


if (isset($_COOKIE["user"])) {

echo "<h3>Welcome back, " . htmlspecialchars($_COOKIE["user"]) . "!</h3>";

} else {

echo "<h3>No cookie found yet. Please enter your name above.</h3>";

?>

</body>

</html>
Practical 8- Write PHP script to demonstrate exceptional handling.

<!DOCTYPE html>

<html>

<head>

<title>Exception Handling Demo</title>

</head>

<body>

<h2>PHP Exception Handling</h2>

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

<label for="num">Enter a number:</label>

<input type="number" id="num" name="num" required>

<input type="submit" value="Divide 100 by Number">

</form>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$num = $_POST['num'];

try {

if ($num == 0) {

// Throw an exception if division by zero

throw new Exception("Division by zero is not allowed!");

$result = 100 / $num;

echo "<h3>Result: 100 / $num = $result</h3>";

} catch (Exception $e) {

// Handle the exception


echo "<h3>Error: " . $e->getMessage() . "</h3>";

} finally {

// Code that always runs

echo "<h3>Execution completed.</h3>";

?>

</body>

</html>
Practical- 9 Design a "delete" web form to delete record with cust_no=3.

<!DOCTYPE html>

<html>

<head>

<title>Delete Record</title>

</head>

<body>

<h2>Delete Customer Record</h2>

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

<input type="submit" name="delete" value="Delete Record with cust_no = 3">

</form>

<?php

if (isset($_POST['delete'])) {

// Database connection

$servername = "localhost";

$username = "root"; // change if needed

$password = ""; // change if needed

$dbname = "testdb"; // your database name

// Create connection

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

// Check connection

if ($conn->connect_error) {

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

}
// SQL query to delete record with cust_no = 3

$sql = "DELETE FROM customer WHERE cust_no = 3";

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

echo "<h3>Record with cust_no = 3 deleted successfully!</h3>";

} else {

echo "<h3>Error deleting record: " . $conn->error . "</h3>";

$conn->close();

?>

</body>

</html>
Practical- 10 Create a dynamic web site using PHP and MySQL.

Step 1: Create the Database and Table

Run this SQL in your MySQL server (e.g., phpMyAdmin or MySQL CLI):

CREATE DATABASE mysite;

USE mysite;

CREATE TABLE customers (

cust_no INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(50) NOT NULL,

email VARCHAR(100) NOT NULL

);

Step 2: Database Connection (db_connect.php)

<?php

$servername = "localhost";

$username = "root"; // change if needed

$password = ""; // change if needed

$dbname = "mysite";

// Create connection

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

// Check connection

if ($conn->connect_error) {

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

?>

Step 3: Insert Data Form ([Link])


<!DOCTYPE html>

<html>

<head>

<title>Dynamic Website - Customers</title>

</head>

<body>

<h2>Add Customer</h2>

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

<label>Name:</label>

<input type="text" name="name" required><br><br>

<label>Email:</label>

<input type="email" name="email" required><br><br>

<input type="submit" name="submit" value="Add Customer">

</form>

<?php

include("db_connect.php");

if (isset($_POST['submit'])) {

$name = $_POST['name'];

$email = $_POST['email'];

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

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

echo "<p>New customer added successfully!</p>";

} else {

echo "<p>Error: " . $conn->error . "</p>";

}
}

?>

</body>

</html>

Step 4: Display Records ([Link])

<!DOCTYPE html>

<html>

<head>

<title>Customer List</title>

</head>

<body>

<h2>Customer Records</h2>

<?php

include("db_connect.php");

$sql = "SELECT * FROM customers";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

echo "<table border='1' cellpadding='10'>";

echo "<tr><th>Customer No</th><th>Name</th><th>Email</th></tr>";

while ($row = $result->fetch_assoc()) {

echo "<tr><td>".$row['cust_no']."</td><td>".$row['name']."</td><td>".
$row['email']."</td></tr>";

echo "</table>";

} else {

echo "<p>No records found.</p>";


}

$conn->close();

?>

</body>

</html>

You might also like