0% found this document useful (0 votes)
11 views62 pages

Avdhoot 22202C0059-1

The document outlines a practical lab exercise for a web-based application development course, focusing on PHP programming. It includes instructions for installing a local server environment, executing PHP programs, and examples of various operators and control structures in PHP. Additionally, it provides exercises related to decision-making control structures using if statements, if-else statements, and switch statements.

Uploaded by

raghavjadhav2003
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)
11 views62 pages

Avdhoot 22202C0059-1

The document outlines a practical lab exercise for a web-based application development course, focusing on PHP programming. It includes instructions for installing a local server environment, executing PHP programs, and examples of various operators and control structures in PHP. Additionally, it provides exercises related to decision-making control structures using if statements, if-else statements, and switch statements.

Uploaded by

raghavjadhav2003
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
You are on page 1/ 62

Name: Avdhoot Nikam Lab no: L0001A

Roll no: 22202C0059 Subject Code: 22619


Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 1
Title: a. Install and configure PHP, web server, MYSQL
b. Write a program to print “Welcome to PHP”
c. Write a simple PHP program using expressions and operators.

 Practical Related Question

1. How to execute PHP program.( Steps)

Ans:

i. Install a Local Server Environment:

You need a server that can interpret PHP. Common options include:
- XAMPP: A free and open-source cross-platform web server solution stack package
containing Apache, MySQL, and PHP.
- MAMP: A free, local server environment that can be installed under macOS and
Windows.
- WAMP: A Windows-only option that includes Apache, MySQL, and PHP.
ii. Set Up the Server:

- Download and install one of the server environments mentioned above.


- After installation, start the server (usually involves starting Apache and MySQL).
iii. Place Your PHP Files:

Move your PHP files into the server's document root directory:
For XAMPP, it’s usually C:\xampp\htdocs\.
For MAMP, it’s typically Applications/MAMP/htdocs/.
For WAMP, it’s usually C:\wamp\www\.
iv. Access the PHP File through the Browser:

- Open your web browser.


- Type the URL corresponding to your PHP file. For example, if you placed your file
named example.php in the document root:
For XAMPP: http://localhost/example.php
For MAMP: http://localhost:8888/example.php (default port for MAMP is 8888)
For WAMP: http://localhost/example.php
v. View the Output:

- The browser will send a request to the server, which will process the PHP code and
return the output (HTML, JSON, etc.) to the browser for display

2. What are the different operators supported by PHP with example? (any TWO
types)

Ans: PHP supports various types of operators, and two of the most commonly used ones are
Arithmetic Operators and Comparison Operators. Below are explanations with examples for
each:

Arithmetic Operators: Arithmetic operators are used to perform basic mathematical


operations.

 + (Addition): Adds two operands.


 - (Subtraction): Subtracts the second operand from the first.
 * (Multiplication): Multiplies two operands.
 / (Division): Divides the first operand by the second.
 % (Modulus): Returns the remainder when the first operand is divided by the second.

Example:
<?php
$a = 10;
$b = 5;

echo $a + $b; // Output: 15


$a - $b; // Output: 5
echo $a * $b; // Output: 50
echo $a / $b; // Output: 2
echo $a % $b; // Output: 0
$a ** $b; // Output: 100000
?>

Comparison Operators: Comparison operators are used to compare two values and return a
boolean value (true or false).

 == (Equal): Returns true if the operands are equal.


 != (Not equal): Returns true if the operands are not equal.
 (Greater than): Returns true if the left operand is greater than the right operand.
 < (Less than): Returns true if the left operand is less than the right operand.
 >= (Greater than or equal to): Returns true if the left operand is greater than or equal to
the right operand.
 <= (Less than or equal to): Returns true if the left operand is less than or equal to the right
operand.
Example:

<?php
$a = 10;
$b = 5;
var_dump($a == $b); // Output: bool(false)
var_dump($a != $b); // Output: bool(true)
var_dump($a > $b); // Output: bool(true)
var_dump($a < $b); // Output: bool(false)
var_dump($a >= $b); // Output: bool(true)
var_dump($a <= $b); // Output: bool(false)
?>

Exercise:

1. Write a various comparison operators in PHP with example.

Ans:

 Equal (==): Checks if two values are equal.


 Identical (===): Checks if two values are identical, meaning both value and type must
match.
 Not Equal (!=): Checks if two values are not equal.
 Not Identical (!==): Checks if two values are not identical (either value or type does
not match).
 Greater Than (>): Checks if the left operand is greater than the right.
 Less Than (<): Checks if the left operand is less than the right.
 Greater Than or Equal (>=): Checks if the left operand is greater than or equal to the
right.
 Less Than or Equal (<=): Checks if the left operand is less than or equal to the right.
 Spaceship Operator (<=>): Compares two values and returns 1 if the left is greater, -1
if the left is less, or 0 if they are equal.

EXAMPLE:

<?php
$a = 10;
$b = 5;
$c = 10;
$d = "10";
$e = null;
$f = 15;
echo "Equal (==): ";
if ($a == $c) {
echo "$a is equal to $c\n"; // Output: 10 is equal to 10
} else {
echo "$a is not equal to $c\n";
}
echo "Identical (===): ";
if ($a === $d) {
echo "$a is identical to $d\n";
} else {
echo "$a is not identical to $d\n"; // Output: 10 is not identical to 10
}
(!=)echo "Not Equal (!=): ";
if ($a != $b) {
echo "$a is not equal to $b\n"; // Output: 10 is not equal to 5
} else {
echo "$a is equal to $b\n";
}
echo "Not Identical (!==): ";
if ($a !== $d) {
echo "$a is not identical to $d\n"; // Output: 10 is not identical to 10
} else {
echo "$a is identical to $d\n";
}
echo "Greater Than (>): ";
if ($a > $b) {
echo "$a is greater than $b\n"; // Output: 10 is greater than 5
} else {
echo "$a is not greater than $b\n";
}

// Using Less Than (<)


echo "Less Than (<): ";
if ($b < $a) {
echo "$b is less than $a\n"; // Output: 5 is less than 10
} else {
echo "$b is not less than $a\n";
}

// Using Greater Than or Equal (>=)


echo "Greater Than or Equal (>=): ";
if ($a >= $c) {
echo "$a is greater than or equal to $c\n"; // Output: 10 is greater than or equal to 10
} else {
echo "$a is not greater than or equal to $c\n";
}
// Using Less Than or Equal (<=)
echo "Less Than or Equal (<=): ";
if ($b <= $a) {
echo "$b is less than or equal to $a\n"; // Output: 5 is less than or equal to 10
} else {
echo "$b is not less than or equal to $a\n";
}

// Using Spaceship Operator (<=>)


echo "Spaceship Operator (<=>): ";
echo "$a <=> $b = " . ($a <=> $b) . "\n"; // Output: 1 (because 10 > 5)
echo "$a <=> $c = " . ($a <=> $c) . "\n"; // Output: 0 (because 10 == 10)
echo "$b <=> $a = " . ($b <=> $a) . "\n"; // Output: -1 (because 5 < 10)

// Using Null Coalescing Operator (??)


echo "Null Coalescing Operator (??): ";
$greeting = $e ?? "Hello, World!";
echo $greeting . "\n"; // Output: Hello, World!

$greeting = $f ?? "Hello, World!";


echo $greeting . "\n"; // Output: 15 (because $f is not null)
?>

2. Write a various Logical operators in PHP with example.

ANS:

 AND (&&): Both $a and $c are true, so the condition evaluates to true.
 OR (||): $a is true, so the condition evaluates to true even though $b is false.
 XOR (xor): Exactly one of $a or $b is true (not both), so it outputs "Exactly one of
$a or $b is true".
 NOT (!): $d is false, so !$d evaluates to true.
 Combined: In the final condition, the expression combines AND, OR, and NOT
operators. Since the left side of the OR is true ($a && $c), the entire condition
evaluates to true.

Example:
<?php
// Sample variables
$a = true; // This is true
$b = false; // This is false
$c = true; // This is true
$d = false; // This is false
// AND (&&) Operator
echo "AND (&&): ";
if ($a && $c) {
echo "\$a and \$c are both true.\n"; // Output: $a and $c are both true.
} else {
echo "One or both are false.\n";
}
// OR (||) Operator
echo "OR (||): ";
if ($a || $b) {
echo "At least one of \$a or \$b is true.\n"; // Output: At least one of $a or $b is true.
} else {
echo "Both \$a and \$b are false.\n";
}
// XOR (xor) Operator
echo "XOR (xor): ";
if ($a xor $b) {
echo "Exactly one of \$a or \$b is true.\n"; // Output: Exactly one of $a or $b is true.
} else {
echo "Either both are true or both are false.\n";
}
// NOT (!) Operator
echo "NOT (!): ";
if (!$d) {
echo "\$d is false, so NOT \$d is true.\n"; // Output: $d is false, so NOT $d is true.
} else {
echo "\$d is true.\n";
}
// Combined Logical Operators using AND, OR, and NOT
echo "Combined Logical Operators: ";
if (($a && $c) || (!$b && $d)) {
echo "The condition is true (Both \$a and \$c are true OR \$b is false and \$d is false).\n";
// Output: The condition is true (Both $a and $c are true OR $b is false and $d is false).
} else {
echo "The condition is false.\n";
}
// Another Complex Condition: Combining multiple logical operators
echo "Another Complex Condition: ";
if (($a && $b) || ($c && !$d) || $b) {
echo "Condition is true.\n";
} else {
echo "Condition is false.\n";
}
?>
Problem Statements:
B. Write a program to print “Welcome to PHP”

Code:

<?php
// Displaying strings
echo "Hello, Welcome to PHP Programming";
echo "<br/>";
//Displaying Strings as Multiple arguments
echo "Hello", " Welcome", " PHP";
echo "<br/>";
//Displaying variables
$s="Hello, PHP";
$x=10;
$y=20;
echo "$s <br/>";
echo $x."+".$y."=";
echo $x + $y;
?>

Output:

C. Write a simple PHP program using expressions and operators.

Code:

Arithmetic
<?php
$a = 20;
$b = 10;
echo "First number:$a <br/>";
echo "Second number:$b <br/>";
echo "<br/>";
$c = $a + $b;
echo "Addtion: $c <br/>";
$c = $a - $b;
echo "Substraction: $c <br/>";
$c = $a * $b;
echo "Multiplication: $c <br/>";
$c = $a / $b;
echo "Division: $c <br/>";
$c = $a % $b;
echo "Modulus: $c <br/>";
?>
Output:
Name: Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 2
Title: Write a PHP program to demonstrate the use of Decision making control
structures using
a. If statement
b. If-else statement
c. Switch statement.

 Practical Related Question

1. List operators used in if conditional statement.


Ans:

Comparison Operator

 == (Equal): Checks if two values are equal.


 != (Not equal): Checks if two values are not equal.
 > (Greater than): Checks if the left value is greater than the right.
 < (Less than): Checks if the left value is less than the right.
 >= (Greater than or equal to): Checks if the left value is greater than or equal to the
right.
 <= (Less than or equal to): Checks if the left value is less than or equal to the right.
 === (Identical): Checks if two values are equal and of the same type.

Logical Operators

 && (AND): Returns true if both conditions are true.


 || (OR): Returns true if at least one of the conditions is true.
 ! (NOT): Reverses the boolean value of a condition.
 ? : (Ternary): Used to evaluate a condition and return a value depending on whether
it's true or false.
 & (AND)
 | (OR)
 ^ (XOR)
 ~ (NOT)
 << (Left shift)
 >> (Right shift)

2. In if-else construct which part will be executed if condition is true.

Ans: The code block inside the if statement is executed and The code inside the else block
will be skipped.
3. State the condition when the else part will be executed with example.

Ans: The else block will only run when the condition inside the if statement evaluates to
false. If the condition is true, the code inside the if block will run, and the else block will be
skipped.

Example:

<?php
$a = 3;
$b = 7;
if ($a > $b) {
echo "\$a is greater than \$b"; // This will NOT run because 3 is not greater than 7
} else {
echo "\$a is not greater than \$b"; // This will run because the condition $a > $b is false
}
?>

 Exercise:
1. Write a program to make the use of logical operator
Ans:
<?php
// Sample variables
$a = true; // This is true
$b = false; // This is false
$c = true; // This is true
$d = false; // This is false

// AND (&&) Operator


echo "AND (&&): ";
if ($a && $c) {
echo "\$a and \$c are both true.\n"; // Output: $a and $c are both true.
} else {
echo "One or both are false.\n";
}

// OR (||) Operator
echo "OR (||): ";
if ($a || $b) {
echo "At least one of \$a or \$b is true.\n"; // Output: At least one of $a or $b is true.
} else {
echo "Both \$a and \$b are false.\n";
}
// XOR (xor) Operator
echo "XOR (xor): ";
if ($a xor $b) {
echo "Exactly one of \$a or \$b is true.\n"; // Output: Exactly one of $a or $b is true.
} else {
echo "Either both are true or both are false.\n";
}

// NOT (!) Operator


echo "NOT (!): ";
if (!$d) {
echo "\$d is false, so NOT \$d is true.\n"; // Output: $d is false, so NOT $d is true.
} else {
echo "\$d is true.\n";
}

// Combined Logical Operators using AND, OR, and NOT


echo "Combined Logical Operators: ";
if (($a && $c) || (!$b && $d)) {
echo "The condition is true (Both \$a and \$c are true OR \$b is false and \$d is false).\
n";
// Output: The condition is true (Both $a and $c are true OR $b is false and $d is false).
} else {
echo "The condition is false.\n";
}

// Another Complex Condition: Combining multiple logical operators


echo "Another Complex Condition: ";
if (($a && $b) || ($c && !$d) || $b) {
echo "Condition is true.\n";
} else {
echo "Condition is false.\n";
}
?>

2. Write a program to check no is positive or negative


Ans:
<?php
// Function to check if the number is positive, negative, or zero
function checkNumber($num) {
if ($num > 0) {
echo "$num is a positive number.";
} elseif ($num < 0) {
echo "$num is a negative number.";
} else {
echo "The number is zero.";
}
}

// Input from user


if (isset($_POST['submit'])) {
$number = $_POST['number'];
if (is_numeric($number)) {
checkNumber($number);
} else {
echo "Please enter a valid number.";
}
}
?>

<!-- HTML form to take user input -->


<form method="post" action="">
<label for="number">Enter a number:</label>
<input type="text" name="number" id="number" required>
<input type="submit" name="submit" value="Check Number">
</form>

3. Write a calendar program using switch statement


Ans:
<?php
// Function to display the month name based on the month number
function getMonthName($month) {
switch ($month) {
case 1:
return "January";
case 2:
return "February";
case 3:
return "March";
case 4:
return "April";
case 5:
return "May";
case 6:
return "June";
case 7:
return "July";
case 8:
return "August";
case 9:
return "September";
case 10:
return "October";
case 11:
return "November";
case 12:
return "December";
default:
return "Invalid month number. Please enter a number between 1 and 12.";
}
}
// Input from user
if (isset($_POST['submit'])) {
$monthNumber = $_POST['monthNumber'];

// Check if input is numeric and valid


if (is_numeric($monthNumber) && $monthNumber >= 1 && $monthNumber <= 12)
{
$monthName = getMonthName($monthNumber);
echo "The month corresponding to number $monthNumber is $monthName.";
} else {
echo "Please enter a valid month number (1 to 12).";
}
}
?>

<!-- HTML form to take user input -->


<form method="post" action="">
<label for="monthNumber">Enter month number (1-12):</label>
<input type="number" name="monthNumber" id="monthNumber" min="1" max="12"
required>
<input type="submit" name="submit" value="Get Month Name">
</form>

 Problem Statements:
1. Write a PHP program to demonstrate the use of Decision making control structures
using

Codes:

a. If statement

<?php
$a=10;
if ($a > 0)
{
echo "The number is positive";
}
?>
Output:
b. If-else
<?php
$a=-10;
if ($a > 0)
{
echo "The number is positive";
}
else
{
echo "The number is negative";
}
?>
Output:

c. Switch statement.
<?php
$ch=1;
$a=20;
$b=10;
switch ($ch)
{
case 1:
$c=$a + $b;
echo "Addition=".$c;
break;
case 2:
$c=$a - $b;
echo "Subtraction=".$c;
break;
case 3:
$c=$a * $b;
echo "Multiplication=". $c;
break;
case 4:
$c=$a / $b;
echo "Division=". $c;
break;
default:
echo "Wrong Choice";
}
?>
Output:
Name: Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 3
Title: Write a PHP program to demonstrate the use of Decision making control
structures using
a. While statement
b. Do-while statement
c. For statement.
d. Foreach Statement

 Practical Related Question

1.When for loop will be terminated?


Ans: A for loop in PHP (and in most programming languages) will be terminated (or stop
iterating) when the loop condition evaluates to false. The condition is evaluated at the
beginning of each iteration. If the condition is false at any point, the loop terminates, and the
program moves to the next part of the code.

2. Difference between for and for-each loop

Ans:

Feature for loop foreach loop


Use case General-purpose, can be used for Specifically designed for iterating
arrays, lists, or counters. over arrays or objects.
Iteration Manual control over Automatically iterates over each
control counter/index. element.
Syntax Requires initialization, condition, Requires only the array or object
and increment. to iterate over.
Accessing Requires manual index access Direct access to elements ($value,
elements ($arr[$i]). or $key => $value).
Performance Slightly less efficient when More efficient for iterating over
iterating over arrays. arrays or objects.
Modifying Modify elements manually Can modify elements by reference
elements ($arr[$i]). (&$value).
Flexibility More flexible, can be used in Limited to arrays/objects.
various scenarios.
Looping Needs manual termination Automatically handles iteration
structure condition ($i++, etc.). over all elements.
 Exercise:
1. Write any program using if condition with for loop.
<?php
// Loop from 1 to 10
for ($i = 1; $i <= 10; $i++) {
// Check if the current number is even or odd
if ($i % 2 == 0) {
echo $i . " is even\n";
} else {
echo $i . " is odd\n";
}
}
?>

 Problem Statements:
Write a PHP program to demonstrate the use of Decision making control structures
using

Codes:

a. While statement

<?php
//while loop to print even numbers
$i=0;
while ($i<= 10)
{
echo "$i<br/>";
$i+=2;
}
?>

Output:
b. Do-while statement

<?php
//do-while loop to print odd numbers
$i=1;
do
{
echo "$i<br/>";
$i+=2;
}while ($i< 10);
?>

Output:

c. for statement

<?php
//for loop to print even numbers and sum of them
$sum=0;
for($i=0; $i<=10;$i+=2)
{
echo "$i<br/>";
$sum+=$i;
}
echo "Sum=$sum";
?>

Output:
d. foreach statement

<?php
$arr = array (10, 20, 30, 40, 50);
foreach ($arr as $i)
{
echo "$i<br/>";
}
?>

Output:
Name: Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 4
Title: Write a PHP program for creating and manipulating
a) Indexed array
b) Associative array
c) Multidimensional array

 Practical Related Question

1. How to create an array in PHP with syntax and small example.


Syntax:
$array = array(1, 2, 3, 4, 5);

Code:
<?php
$colors = ["Red", "Green", "Blue"];
echo $colors[0];
$person = ["name" => "student", "age" => 20];
echo $person["name"];
?>
Output:

2. List the types of array used in PHP.

Ans:
1.Indexed Arrays (Numeric Arrays):
• These arrays use numeric indexes (0, 1, 2, 3, etc.) by default.
• Eg:
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple

2.Associative Arrays:
• These arrays use named keys (strings or any valid type) to store values, allowing you to
access elements using custom keys.
• Eg:
$person = ["name" => "John", "age" => 30, "city" => "New York"];
echo $person["name"]; // Output: John

3.Multidimensional Arrays:
• These are arrays that contain other arrays as their elements, allowing you to create more
complex structures like tables, matrices, or a combination of indexed and associative arrays.
• Eg:
$students = [
["name" => "Alice", "age" => 20],
["name" => "Bob", "age" => 22],
["name" => "Charlie", "age" => 23]
];
echo $students[0]["name"];

 Exercise:
1. Develop a program to using Associative array.

Codes:
<?php
$ages = array(
"John" => 25,
"Alice" => 30,
"Bob" => 22,
"Eve" => 28
);
function addPerson(&$array, $name, $age) {
$array[$name] = $age;
echo "$name's age has been added.\n";
}
function getAge($array, $name) {
if (array_key_exists($name, $array)) {
return $array[$name];
} else {
return "Person not found.";
}
}
addPerson($ages, "Charlie", 35);
echo "John's age is: " . getAge($ages, "John") . "\n";
echo "Alice's age is: " . getAge($ages, "Alice") . "\n";
echo "Charlie's age is: " . getAge($ages, "Charlie") . "\n";
echo "David's age is: " . getAge($ages, "David") . "\n";
?>

Output:

2. Develop a program to using Multidimensional array.

Codes:
<?php
$matrix = array(
array(1, 2, 3), // First row
array(4, 5, 6), // Second row
array(7, 8, 9) // Third row
);
function printMatrix($matrix) {
foreach ($matrix as $row) {
foreach ($row as $value) {
echo $value . " ";
}
echo "<br>";
}
}
function sumOfMatrix($matrix) {
$totalSum = 0;
foreach ($matrix as $row) {
$totalSum += array_sum($row); // Sum of each row
}
return $totalSum;
}
function accessElements($matrix) {
echo "Accessing some specific elements:<br>";
echo "Element at (0, 0): " . $matrix[0][0] . "<br>"; // First element (1)
echo "Element at (2, 2): " . $matrix[2][2] . "<br>"; // Last element (9)
}
function modifyMatrix(&$matrix) {
echo "Modifying the matrix:<br>";
$matrix[1][1] = 55; // Change element at (1, 1) from 5 to 55
echo "Modified matrix:<br>";
printMatrix($matrix);
}
echo "Original Matrix:<br>";
printMatrix($matrix);
echo "<br>Sum of all elements in the matrix: " . sumOfMatrix($matrix) . "<br>";
accessElements($matrix);
modifyMatrix($matrix);
?>

 Problem Statements:
Write a PHP program for creating and manipulating

Codes:

a) Indexed array

<html>
<head>
<title>
array
</title>
</head>
<body>
<h1> Creating an array </h1>
<?php
$course[0]="Computer Engg.";
$course[1]="Information Tech.";
$course[2]="Electronics and Telecomm.";
echo $course[2], "<BR>";
echo $course[0], "<BR>";
echo $course[1], "<BR>";
?>
</body>
</html>
Output:

b. Associative array
<html>
<head>
<title>
array
</title>
</head>
<body>
<h1> Creating an array </h1>
<?php
$course = array(1 => "Computer Engg.",
5 => "Information Tech.",
3 => "Electronics and Telecomm.");
echo $course [5];
?>
</body>
</html>
Output:

c. Multidimensional array
<?php
// Defining a multidimensional array
$person = array(
array(
"name" => "Yogita K",
"mob" => "5689741523",
"email" => "yogi_k@gmail.com",
),
array(
"name" => "Manisha P.",
"mob" => "2584369721",
"email" => "manisha_p@gmail.com",
),
array(
"name" => "Vijay Patil",
"mob" => "9875147536",
"email" => "Vijay_p@gmail.com",
)
);
// Accessing elements
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];
?>
Output:
Name:Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 5
Title: A. Write a PHP program to
• Calculate length of string.
• Count the number of words in string without using string functions.
B. Write a simple PHP program to demonstrate use of various built-in
string functions.

 Practical Related Question


1. List string functions with syntax and small example.

Ans:
1. strlen() : Returns the length of the string.
Syntax: strlen(string)
Example:
$str = "Hello";
echo strlen($str);

2. strtoupper(): Converts all characters in a string to uppercase.


Syntax: strtoupper(string)
Example:
$str = "hello";
echo strtoupper($str);

3. strtolower(): Converts all characters in a string to lowercase.


Syntax: strtolower(string)
Example:
$str = "HELLO";
echo strtolower($str);

4. substr(): Returns a part of the string.


Syntax: substr(string, start, length)
Example:
$str = "Hello, world!";
echo substr($str, 7, 5);
 Exercise:
1.Write a program to demonstrate PHP maths function

Code:
<?php
$number = -45;
echo "Absolute value of $number: " . abs($number) . "\n";
$number = 16;
echo "Square root of $number: " . sqrt($number) . "\n";
$base = 3;
$exponent = 4;
echo "$base raised to the power of $exponent: " . pow($base, $exponent) . "\n";
echo "Random number between 1 and 100: " . rand(1, 100) . "\n";
$floatNumber = 3.14159;
echo "Rounded value of $floatNumber: " . round($floatNumber) . "\n";
$values = array(10, 20, 30, 40, 50);
echo "Maximum value in the array: " . max($values) . "\n";
echo "Minimum value in the array: " . min($values) . "\n";
$angleInRadians = pi() / 4; // 45 degrees in radians
echo "Sine of $angleInRadians radians: " . sin($angleInRadians) . "\n";
$number = 100;
echo "Logarithm (base 10) of $number: " . log10($number) . "\n";
echo "Exponential of 2: " . exp(2) . "\n";
?>

 Problem Statements:
A. Write a PHP program to

• Calculate length of string.


<?php
echo strlen("Welcome to PHP");
?>

Output:

• Count the number of words in string without using string functions.

<?php
echo str_word_count("Welcome to PHP world!");
?>

Output:

B. Write a simple PHP program to demonstrate use of various built-in string functions.

<?php
$course[0]="Computer Engg.";
$course[1]="Information Tech.";
$course[2]="Electronics and Telecomm.";
$text=implode(",",$course);
echo $text;
?>

Output:

Name: Avdhoot Nikam Lab no: L0001A


Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 6
Title: Write a simple PHP program to demonstrate use of simple function and
parameterized function

 Practical Related Question

1.Define anonymous function.

Ans:

In PHP, an anonymous function (also known as a closure) is a function that is defined


without a name. It can be assigned to a variable, passed as an argument to other functions, or
returned from functions. These functions are commonly used for short-lived operations or
callbacks.

2.Write a syntax of anonymous function.

Ans:

$variable_name = function(parameters) {

// function body

return $value;

};

 Exercise:
1. Write a program to demonstrate parameterized function.
<?php
function greet($name, $age) {
echo "Hello, $name! You are $age years old.\n";
}
greet("Alice", 25); // Passing "Alice" as name and 25 as age
greet("Bob", 30); // Passing "Bob" as name and 30 as age
?>
 Problem Statements:
Write a simple PHP program to demonstrate use of simple function and parameterized
function

Codes:

Simple Function:

<?php
/* Defining a PHP Function */
function writeMessage(){
echo "Welcome to PHP world!";
}
/* Calling a PHP Function */
writeMessage();
?>

Output:

Parameterized Function:

<?php
function addfunc($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addfunc(50, 20);
?>

Output;
Name: Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 7
Title: Write a simple PHP program to create PDF document buy using
graphics concepts.

 Practical Related Question


1. Write use of various graphics function.
Ans:- HP GD is a powerful graphics library that allows developers to create and manipulate
images on the fly. This library is widely used for generating dynamic images, resizing
images, adding watermarks, creating thumbnails, and much more.

 Problem Statements:
Write a simple PHP program to create PDF document buy using graphics concepts.

<?php
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Output:
Name: Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 8
Title: Write a PHP program to
a) Inherit members of super class in subclass.
b) Create constructor to initialize object of class by using object oriented
concepts.

 Practical Related Question


1. How to create a sub class.
Ans:- The way that you define a subclass in PHP is by first defining the parent class, just like
you normally would and then you define the subclass in the same way, except that you add
another keyword after the class name, which is extends and then the name of the parent class
that you want to inherit it from.

2) Define inheritance and its type with diagram.


Ans:- Inheritance is a way of extending the existing class functionality in the newly created
class. We can also add functionality to the newly created class apart from extending the base
class functionalities. When we inherit one class, we say an inherited class is a child class
(sub-class), which is called the parent class from which we inherit it. The parent class is also
known as the base class. This is the way that enables better management of the programming
code and code reusability. The idea behind using inheritance is all about better management
of the code and the code reusability. In this topic, we are going to learn about Inheritance in
PHP.
Types:-
1) Single inhertiance
PHP supports Single inheritance. Single inhertiance is a concept in PHP in which only one
class can be inherited by a single class. We need to have two classes in between this process.
One is the base (parent) class, and the other is the child class. Let’s understand the same with
an example. It is popularly known as simple inheritance. This type of inheritance in Php
remains the same as Java, etc.
2) Multilevel Inheritance
PHP supports Multilevel Inheritance In this type of inheritance, we will have more than 2
classes. In this type of inheritance, a parent class will be inherited by a child class then that
child class will be inherited by the child class. This type of inheritance in PHP language
remains the same as in C++ etc.

3) Hierachical Inheritance
PHP supports Hierachical Inheritance. Hierarchical inheritance is the type of inheritance in
which a program consists of a single parent and more than one child class. Let’s understand
the same with this example. This type of inheritance in PHP language remains the same as
JAVA, C++, etc.

 Exercise:
1. Write a program to demonstrate parameterized constructor.

Ans:

<?php
//PHP program to demonstrate the parameterized constructor.
class Sample
{
private $num1;
private $num2;

public function Sample($n1, $n2)


{
$this->num1=$n1;
$this->num2=$n2;
}
public function PrintValues()
{
echo "Num1: ".$this->num1."<br>";
echo "Num2: ".$this->num2."<br>";
}
}
$S = new Sample(10,20);
$S->PrintValues();
?>

2. Write a program to demonstrate default constructor.


Ans:- <?php
//PHP program to implement the default or no argument
//constructor using __contruct().
class Sample
{
public function __construct()
{
echo "Default constructor called<br>";
}
public function Method1()
{
echo "Method1 called<br>";
}
}
$S = new Sample();
$S->Method1();
?>

 Problem Statements:
Write a PHP program to :

a. Inherit members of super class in subclass.

Code:

<?php
class a
{
function dis1()
{
echo "Hello PHP <br>";
}
}
class b extends a
{
function dis2()
{
echo "PHP Programming <br>";
}
}
$obj= new b();
$obj->dis1();
$obj->dis2();
?>

Output:

b) Create constructor to initialize object of class by using object oriented concepts.

Code:

<?php
class MyClass
{
function __construct()
{
echo "Welcome to PHP constructor. <br />";
}
}
$obj = new MyClass; // This will display “Welcome to PHP constructor.”
?>

Output:
Name: Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment no.: 9
Title: Write a simple PHP program on Introspection and Serialization

 Practical Related Question


1. Explain the concept of introspection in PHP.

Ans:- Introspection is the ability of a program to examine an object’s characteristics, such as


its name, parent class (if any), properties, and methods. With introspection, you can write
code that operates on any class or object. You don’t need to know which methods or
properties are defined when you write your code; instead, you can discover that information
at runtime, which makes it possible for you to write generic debuggers, serializers, profilers,
etc. In this section, we look at the introspective functions provided by PHP.

2) Explain serialization in PHP?

Ans:- The serialization format in PHP is fairly simple. The serialized string consists of a
series of data types and values, each separated by a colon. For example, the serialized string
for an integer would be i:123, while the serialized string for a string would be s:5:”Hello”.

 Exercise:
1) Develop a PHP code for serialization.
Ans:-

<?php
$var = array( 'Welcome', 568, array(1, 'two'), 'VP'); // a complex array
$string = serialize($var); // serialize the above data
print_r($string ."<br>"); // unserializing the data in $string
$newvar = unserialize($string); // printing the unserialized data
print_r($newvar);
?>
2)Develop a PHP code for introspection.

Ans:

<?php
class Rectangle
{
var $dim1 = 2;
var $dim2 = 10;
function Rectangle($dim1,$dim2)
{
$this->dim1 = $dim1;
$this->dim2 = $dim2;
}
function area()
{
return $this->dim1*$this->dim2;
}
function display()
{
// any code to display info
}
}
$S = new Rectangle(4,2);
//get the class varibale i.e properties
$class_properties = get_class_vars("Rectangle");
//get object properties
$object_properties = get_object_vars($S);
//get class methods
$class_methods = get_class_methods("Rectangle");
//get class corresponding to an object
$object_class = get_class($S);
print_r($class_properties);
print_r($object_properties);
print_r($class_methods);
print_r($object_class);
?>
 Problem Statements:
Write a simple PHP program on Introspection and Serialization

Codes:

Introspection:

<?php
if (class_exists('Demo'))
{
$demo = new Demo();
echo "This is Demo class.";
}
else
{
echo "Class does not exist";
}
?>

Output:

Serialization:

<?php
$s_data= serialize(array('Welcome', 'to', 'PHP'));
print_r($s_data . "<br>");
$us_data=unserialize($s_data);
print_r($us_data);
?>

Output:
Name: Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment No: 10
Title of Design a web page using following form controls: a.Text box, b. Radio
Experiment button, c. Check box, d. Buttons
Exercise:

A.

Write a program to design a registration form using textbox, radio button, checkbox
and button.

B.

Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
</head>
<body>

<h2>Registration Form</h2>

<!-- Form for collecting data -->


<form action="test.php" method="POST">
<!-- Full Name Textbox -->
<label for="fullname">Full Name:</label>
<input type="text" id="fullname" name="fullname" required><br><br>

<!-- Email Textbox -->


<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>

<!-- Gender Radio Buttons -->


<label>Gender:</label>
<input type="radio" id="male" name="gender" value="Male" required> Male
<input type="radio" id="female" name="gender" value="Female" required> Female
<input type="radio" id="other" name="gender" value="Other" required> Other
<br><br>

<!-- Hobbies Checkbox -->


<label>Hobbies:</label>
<input type="checkbox" id="hobby1" name="hobbies[]" value="Reading"> Reading
<input type="checkbox" id="hobby2" name="hobbies[]" value="Traveling"> Traveling
<input type="checkbox" id="hobby3" name="hobbies[]" value="Cooking"> Cooking
<br><br>

<!-- Submit Button -->


<button type="submit">Submit</button>
</form>

</body>
</html>
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get form data
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$hobbies = isset($_POST['hobbies']) ? $_POST['hobbies'] : [];

// Process the data (for example, you can store it in a database or simply display it)
echo "<h2>Registration Successful!</h2>";
echo "<strong>Full Name:</strong> " . htmlspecialchars($fullname) . "<br>";
echo "<strong>Email:</strong> " . htmlspecialchars($email) . "<br>";
echo "<strong>Gender:</strong> " . htmlspecialchars($gender) . "<br>";

echo "<strong>Hobbies:</strong><br>";
if (count($hobbies) > 0) {
foreach ($hobbies as $hobby) {
echo "- " . htmlspecialchars($hobby) . "<br>";
}
} else {
echo "No hobbies selected.<br>";
}
} else {
// Redirect to the registration form if accessed directly
header("Location: exp10.html");
exit();
}
?>

Output:
Practical Related Questions:

A.

Write a use and syntax of following controls:

B.

a.

Textbox

b.
c.

Radio button

d.
e.
Check box

f.
g.

Buttons

h.

Ans:
Here's a brief explanation of each form control, along with their syntax and usage:

a.

Textbox

b.

(<input type="text">)

Use: A textbox is used to collect a single-line text input from the user, like a name, email, or
search query.
Syntax:
<input type="text" id="textbox" name="textbox" value="default value" placeholder="Enter
text">
Attributes:
type="text": Specifies that the input is a text field.
id: The unique identifier for the input field (for CSS or JavaScript targeting).
name: The name of the input field, which will be used to send the data when the form is
submitted.
value: The default value (optional).
placeholder: Provides a hint to the user about what to enter in the textbox (optional).
Example:
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter your username">
b. Radio Button (<input type="radio">)

Use: A radio button allows the user to select one option from a predefined set of choices
(usually part of a group of radio buttons). Only one option can be selected at a time.
Syntax:
<input type="radio" id="option1" name="group" value="Option 1">
<label for="option1">Option 1</label>=
Attributes:
type="radio": Specifies that the input is a radio button.
name: Specifies a name for the radio button group (all radio buttons with the same name will
belong to the same group).
value: Specifies the value that will be sent when the form is submitted.
id: A unique identifier for the radio button (for labeling purposes).
checked: If present, it indicates that the radio button is selected by default.
Example:
<p>Choose your gender:</p>
<input type="radio" id="male" name="gender" value="Male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label>

c. Checkbox (<input type="checkbox">)


Use: A checkbox is used when you want to give users the ability to select one or more
options. Unlike radio buttons, multiple checkboxes can be selected at the same time.
Syntax:
<input type="checkbox" id="agree" name="agreement" value="Yes">
<label for="agree">I agree to the terms and conditions</label>

Attributes:
type="checkbox": Specifies that the input is a checkbox.
name: Specifies the name of the checkbox, which is sent with the form data when submitted.
value: Specifies the value to send if the checkbox is checked.
id: A unique identifier for the checkbox (for labeling purposes).
checked: If present, it indicates that the checkbox is checked by default.
Example:
<label for="subscribe">Subscribe to newsletter:</label>
<input type="checkbox" id="subscribe" name="subscribe" value="Yes">

d. Button (<button> or <input type="button">)

Use: A button is used to trigger a form submission or to perform other actions like resetting
the form or executing a JavaScript function when clicked.
Syntax:
<button type="submit">Submit</button>
or
<input type="button" value="Click Me">
Attributes:
type: Specifies the type of the button. Common types are:
submit: Submits the form.
reset: Resets the form to its initial state.
button: A generic button that can trigger JavaScript events.
value: The text displayed on the button (for <input type="button">).
onclick: A JavaScript event handler that specifies a function to be executed when the button
is clicked (for <button> and <input>).
Example:
<form action="/submit">
<input type="text" name="username" placeholder="Enter username">
<button type="submit">Submit</button>
</form>

Name: Avdhoot Nikam Lab no: L0001A


Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment No: 11
Title of Design a web page using following form controls: a. List
Experiment box, b. Combo box, c. Hidden field box
Write a program to design a form using list box, combo box
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Form with List Box and Combo Box</title>

</head>

<body>

<h2>Form with List Box and Combo Box</h2>

<form action="test.php" method="POST">

<label for="fruit">Choose your favorite fruit:</label>

<select id="fruit" name="fruit">

<option value="apple">Apple</option>

<option value="banana">Banana</option>

<option value="cherry">Cherry</option>

<option value="grapes">Grapes</option>

<option value="orange">Orange</option>

</select>

<br><br>

<label for="colors">Select your favorite colors:</label>

<select id="colors" name="colors[]" multiple size="5">


<option value="red">Red</option>

<option value="blue">Blue</option>

<option value="green">Green</option>

<option value="yellow">Yellow</option>

<option value="purple">Purple</option>

<option value="orange">Orange</option>

</select>

<br><br>

<button type="submit">Submit</button>

</form>

</body>

</html>

<?php

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

$fruit = $_POST['fruit'];

$colors = isset($_POST['colors']) ? $_POST['colors'] : [];

echo "<h2>Form Submission Successful!</h2>";

echo "<strong>Favorite Fruit:</strong> " . htmlspecialchars($fruit) . "<br>";

echo "<strong>Favorite Colors:</strong><br>";

if (count($colors) > 0) {

foreach ($colors as $color) {

echo "- " . htmlspecialchars($color) . "<br>";

}
} else {

echo "No colors selected.<br>";

} else {

header("Location: exp10.html");

exit();

?>

Here’s an explanation of each control and its syntax:

a. List Box

A List Box allows users to select one or multiple options from a predefined list of options. It
is implemented using the <select> element with the multiple attribute for multi-selection.
Use:

 It is typically used when you want to allow users to select one or multiple options from a list
of choices, such as selecting multiple interests or favorite items.

Syntax:
<label for="listbox">Choose your favorite colors:</label>
<select id="listbox" name="colors[]" multiple size="5">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="purple">Purple</option>
</select>

 multiple: Allows for multiple selections.


 size: Specifies how many options should be displayed at a time.

b. Hidden Field

A Hidden Field is an HTML element that allows you to store data in a form that the user
cannot see or modify. It's useful for storing information that needs to be sent with the form
but is not directly visible or editable by the user.

Use:

 Hidden fields are often used for maintaining state information (like session IDs, form
identifiers, etc.) when the form is submitted.

Syntax:
<input type="hidden" name="user_id" value="12345">

 type="hidden": Specifies that the input field is hidden.


 name: The name of the hidden field (used to access the data in PHP or JavaScript).
 value: The value to be sent with the form when submitted.

c. Combo Box

A Combo Box is a drop-down list that allows the user to select one option from a list. It is
implemented using the <select> element. By default, it only allows a single option to be
selected, but it can also be styled to let the user type in a custom entry using JavaScript.

Use:

 A combo box is ideal when you want to offer a list of options, but also allow the user to
manually enter a value if needed (depending on how it's implemented).
Syntax:
<label for="fruit">Choose your favorite fruit:</label>
<select id="fruit" name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
<option value="grapes">Grapes</option>
<option value="orange">Orange</option>
</select>

 A <select> element is used to create a combo box.


 The <option> elements inside it represent the different items in the list.

Summary:

 List Box: A multi-select dropdown that lets users select one or multiple options.
 Hidden Field: A non-visible input field used to store data in a form.
 Combo Box: A dropdown list that allows users to select an option from the list, typically used
when there are many options.

Name: Avdhoot Nikam Lab no: L0001A


Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment No: 12
Title of Experiment Develop web page with data validation

Program code

Write a simple PHP program to check that emails are valid.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = trim($_POST["email"]);

if (empty($email)) {

echo "Email is required.";

} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo "Invalid email format.";

} else {

echo "Valid email: " . htmlspecialchars($email);

?>

<!DOCTYPE html>

<html>

<head>

<title>Email Validation</title>

</head>

<body>

<h2>PHP Email Validation</h2>

<form method="post">

Email: <input type="text" name="email">

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

</form>

</body>

</html>
Prq

Enlist and explain different method provided by php for web page validation.

1. Server-Side Validation

Server-side validation ensures that data is properly validated on the backend before
processing or storing it in a database. It is more secure than client-side validation.

Example: Server-Side Form Validation

<?php

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

$name = trim($_POST["name"]);

if (empty($name)) {

echo "Name is required";

} elseif (!preg_match("/^[a-zA-Z ]*$/", $name)) {

echo "Only letters and white space allowed";

} else {

echo "Valid name: " . htmlspecialchars($name);

?>
<form method="post">

Name: <input type="text" name="name">

<input type="submit">

</form>

2. Client-Side Validation (Using JavaScript with PHP)


PHP itself does not perform client-side validation, but it can be combined with JavaScript to
validate input before sending it to the server.
Example: JavaScript Validation with PHP
<form name="myForm" onsubmit="return validateForm()" method="post">

Name: <input type="text" name="name">

<input type="submit">

</form>

<script>

function validateForm() {

let name = document.forms["myForm"]["name"].value;

if (name == "") {

alert("Name must be filled out");

return false;

</script>

3. Built-in PHP Functions for Validation


PHP provides several built-in functions for input validation:
(a) filter_var()

Used for filtering and validating data, such as email, URLs, integers, etc.
Example: Validating an Email Address
$email = "example@domain.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo "Valid email format";

} else {

echo "Invalid email format";

(b) preg_match()

Used for pattern-based validation.


Example: Checking if a String Contains Only Letters
$name = "John Doe";
if (preg_match("/^[a-zA-Z ]+$/", $name)) {
echo "Valid name";
} else {
echo "Invalid name";
}
Name: Avdhoot Nikam Lab no: L0001A
Roll no: 22202C0059 Subject Code: 22619
Course: IF6IC Subject Teacher: Chetashri Bhusari
Semester: 6 Subject: Web based application
development with PHP

Experiment No: 16
Title of Develop a simple application to Update, Delete table data from
Experiment database.

1.Write a syntax for update and delete data in PHP.

1. Syntax for Updating Data

<?php

$conn = new mysqli("localhost", "username", "password", "database_name");

if ($conn->connect_error) {

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

// Update query syntax

$sql = "UPDATE table_name SET column1='new_value' WHERE condition";

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

echo "Record updated successfully";

} else {

echo "Error updating record: " . $conn->error;

$conn->close();

?>

2. Syntax for Deleting Data

<?php
$conn = new mysqli("localhost", "username", "password", "database_name");

if ($conn->connect_error) {

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

// Delete query syntax

$sql = "DELETE FROM table_name WHERE condition";

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

echo "Record deleted successfully";

} else {

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

$conn->close();

?>

Exercise

1.

Write a PHP program to Update table data from student database.

2.

<?php

$conn = new mysqli("localhost", "root", "", "student_db");

if ($conn->connect_error) {

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

}
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['id']) && isset($_POST['name']) &&
isset($_POST['email'])) {

$id = intval($_POST['id']);

$name = trim($_POST['name']);

$email = trim($_POST['email']);

if (!empty($id) && !empty($name) && !empty($email)) {

$stmt = $conn->prepare("UPDATE students SET name=?, email=? WHERE id=?");

$stmt->bind_param("ssi", $name, $email, $id);

if ($stmt->execute()) {

echo "Record updated successfully!";

} else {

echo "Error updating record: " . $conn->error;

$stmt->close();

} else {

echo "All fields are required!";

$id = 1;

$result = $conn->query("SELECT * FROM students WHERE id=$id");

if ($result && $result->num_rows > 0) {

$row = $result->fetch_assoc();

} else {

die("No student found with the given ID.");

?>
<!DOCTYPE html>

<html>

<head>

<title>Update Student</title>

</head>

<body>

<h2>Update Student Information</h2>

<form method="post">

<input type="hidden" name="id" value="<?php echo htmlspecialchars($row['id']); ?>">

Name: <input type="text" name="name" value="<?php echo htmlspecialchars($row['name']); ?


>" required><br><br>

Email: <input type="email" name="email" value="<?php echo htmlspecialchars($row['email']); ?


>" required><br><br>

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

</form>

</body>

</html>

<?php

$conn->close();

?>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy