0% found this document useful (0 votes)
17 views69 pages

Install WAMP Server and PHP Basics

The document outlines practical exercises for a BCA semester course, focusing on PHP programming. It includes step-by-step instructions for installing WAMP server, writing PHP scripts for various tasks, and performing operations with arrays and matrices. Each practical exercise provides code examples and expected outputs.

Uploaded by

rawatdishita06
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)
17 views69 pages

Install WAMP Server and PHP Basics

The document outlines practical exercises for a BCA semester course, focusing on PHP programming. It includes step-by-step instructions for installing WAMP server, writing PHP scripts for various tasks, and performing operations with arrays and matrices. Each practical exercise provides code examples and expected outputs.

Uploaded by

rawatdishita06
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

DWD LAB FILE BCA SEM - III E1 01521102024

Practical No.1
AIM- Write the steps to install Wamp server on your PC
Solution: Steps to install WAMP Server on your PC:

1. Download WAMP Server:


○ Visit WAMP Server's official website.
○ Download the appropriate version (32-bit or 64-bit).
2. Run the Installer:
○ Double-click the downloaded file to start the installation.
○ Select your preferred language (usually English).
○ Choose the installation directory (default: C:\wamp\).
○ Click "Next" and then "Install".

3. Start WAMP Server:


○ Once installed, open WAMP from the desktop shortcut or Start Menu.
○ Click on the WAMP icon in the system tray and select "Start All Services".

Page-1
DWD LAB FILE BCA SEM - III E1 01521102024
4. Test WAMP Server:
○ Open a web browser and go to localhost or [Link].
○ You should see the WAMP Server homepage.
5. Create a PHP Test File :
○ Navigate to C:\wamp\www\ and create a file called [Link].
○ Add <?php phpinfo(); ?> and save it.
○ Go to localhost/[Link] in your browser to see the PHP info page.
6. Start Developing Websites:
○ Create a folder in C:\wamp\www\ for your project.
○ Access your website by going to localhost/yourprojectname in the browser

Page-2
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.2
AIM- Write a PHP Script to get the PHP Version
Solution:
<?php
$php_version = phpversion();
echo "Current PHP Version: " . $php_version;
?>

OUTPUT:

Page-3
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.3
AIM- Write a PHP Script to display configuration information by using the function
phpinfo().
Solution:
<?php
phpinfo();
?>

OUTPUT:

Page-4
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.4
AIM- Create a PHP Page and print hello everyone write steps of execution
Solution:
<?php
echo "Hello Everyone";
?>
1. Create a new file named [Link].
2. Add this code inside [Link]:
3. Place [Link] in your web server’s document root folder (e.g., htdocs or www).
4. Start your web server (Apache, Nginx, etc.).
5. Open a web browser and navigate to [Link]
6. View the output: Hello Everyone displayed in the browser.

OUTPUT:

Page-5
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.5
AIM- Write a PHP Script to display the following:
LEARN PHP
STUDY PHP at IITM
I’m about to learn PHP!
This string was made with multiple parameters
Solution:
<?php
// Display the required messages using echo
echo "LEARN PHP<br>";
echo "STUDY PHP at IITM<br>";
echo "I’m about to learn PHP!<br>";
echo "This string was made with multiple parameters";
?>

OUTPUT:

Page-6
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.6
AIM: Write a script using a variable "$whatisit" to print the following to the browser. Your
echo statements may include no words except "Value is". Value is String, Value is
Integer, Value is Boolean, Value is None.
Solution:
<?php
$whatisit = "String.";
echo "Value is " . $whatisit;
?>
OUTPUT:

Page-7
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.7

AIM- Write a PHP script to create a constant:

(i) Creates a case-sensitive constant, with the value of "Welcome to PHP


[Link]!!!"

(ii) Creates a case-insensitive constant, with the value of "Welcome to [Link]!!!"

Solution:

<?php
define("WELCOME_MESSAGE", "Welcome to PHP [Link]!!!");
define("WELCOME_MESSAGE_INSENSITIVE", "Welcome to [Link]!!!", true);
echo WELCOME_MESSAGE . "<br>";
echo WELCOME_MESSAGE_INSENSITIVE . "<br>";
?>

OUTPUT:

Page-8
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.8
AIM- PHP Script to Find the Area of a Triangle
Solution:
<?php
$base = 10;
$height = 5;
$area = 0.5 * $base * $height;
echo "The area of the triangle is: " . $area . " square units.";
?>

OUTPUT:

Page-9
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.9
AIM- Write a script using one variable "Sumit" to print the following to the browser.
Convert or set the data type using settype() function for the following:
Value is string.
Value is double.
Value is Boolean.
Value is integer.
Solution:
<?php
$Sumit = "Hello, this is a string";
echo "Value is string: " . $Sumit . "<br>";
settype($Sumit, "double");
echo "Value is double: " . $Sumit . "<br>";
settype($Sumit, "boolean");
echo "Value is Boolean: " . ($Sumit ? "true" : "false") . "<br>";
settype($Sumit, "integer");
echo "Value is integer: " . $Sumit . "<br>";
$Sumit = "123";
settype($Sumit, "integer");
echo "Converted from string to integer: " . $Sumit . "<br>";
$Sumit = 12.34;
settype($Sumit, "string");
echo "Converted from double to string: " . $Sumit . "<br>";
$Sumit = true;
settype($Sumit, "double");
echo "Converted from boolean to double: " . $Sumit . "<br>";
$Sumit = 10;
settype($Sumit, "boolean");
echo "Converted from integer to boolean: " . ($Sumit ? "true" : "false") . "<br>";
?>
OUTPUT:

Page-10
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.10
AIM- Program to find whether the number is even or odd
Solution:
<?php
$number = 10;
if ($number % 2 == 0) {
echo "$number is an even number.";
} else {
echo "$number is an odd number.";
}
?>

OUTPUT:

Page-11
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.11
AIM- Write a program to display whether a number is prime or not
Solution:
<?php
function is_prime($num) {
if ($num <= 1) {
return false;
}
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}

$num = (int)readline("Enter a number: ");

if (is_prime($num)) {
echo "$num is a prime number.\n";
} else {
echo "$num is not a prime number.\n";
}
?>

OUTPUT:

Page-12
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.12
AIM- Write a program to check out a number is leap or not
Solution:
<?php
function is_leap_year($year) {
if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
return true;
}
return false;
}

$year = (int)readline("Enter a year: ");

if (is_leap_year($year)) {
echo "$year is a leap year.\n";
} else {
echo "$year is not a leap year.\n";
}
?>

OUTPUT:

Page-13
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.13
AIM- Program to swap two values of numbers using 3 variables
Solution:
<?php
function swap_values(&$a, &$b) {
$temp = $a;
$a = $b;
$b = $temp;
}

$x = 10;
$y = 11;

swap_values($x, $y);

echo "After swapping: x = $x, y = $y\n";


?>

OUTPUT:

Page-14
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.14
AIM- Write a program to check largest number between two numbers using if else
statements and conditional operators
Solution:
● If else
Solution:
<?php
function find_largest($a, $b) {
if ($a > $b) {
return $a;
} elseif ($b > $a) {
return $b;
} else {
return "Both are equal";
}
}

$num1 = 10;
$num2 = 15;

echo "The largest number is: " . find_largest($num1, $num2) . "\n";


?>

● Conditional Operator
Solution:
<?php
$num1 = 10;
$num2 = 15;

$largest = ($num1 > $num2) ? $num1 : $num2;

echo "The largest number is: $largest\n";


?>

OUTPUT:

Page-15
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.15
AIM- WAP to print the Factorial of a number.
Solution:
<?php
function factorial($n) {
if ($n == 0 || $n == 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}

$num = 5;

echo "The factorial of $num is: " . factorial($num) . "\n";


?>

OUTPUT:

Page-16
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.16
AIM- Program to Display the Sum of Integers from 1 to n
Solution:
<?php
$n = 10;
$sum = 0;

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


$sum += $i;
}

echo "The sum of integers from 1 to $n is: $sum\n";


?>

OUTPUT:

Page-17
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.17
AIM- Create an Index Array Using Both Methods and Display All Values with and
Without Index Value.
Solution:
<?php
$array1 = array(10, 20, 30, 40, 50);
$array2[] = 10;
$array2[] = 20;
$array2[] = 30;
$array2[] = 40;
$array2[] = 50;

echo "Array 1 (with index values):\n";


foreach ($array1 as $index => $value) {
echo "Index $index: $value\n";
}

echo "\nArray 2 (with index values):\n";


foreach ($array2 as $index => $value) {
echo "Index $index: $value\n";
}

echo "\nArray 1 (without index values):\n";


foreach ($array1 as $value) {
echo "$value\n";
}

echo "\nArray 2 (without index values):\n";


foreach ($array2 as $value) {
echo "$value\n";
}
?>
OUTPUT:

Page-18
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.18
AIM- Create an Index Array and Find the Sum of Its Elements
Solution:
<?php
$array = array(10, 20, 30, 40, 50);
$sum = array_sum($array);

echo "The sum of the elements in the array is: $sum\n";


?>

OUTPUT:

Page-19
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.19
AIM- Create an associative array:
● Count the array element and display all values of the array using for each loop.
● Create a 2D associative array and display its element with each loop.
● Find the following:
○ Sum of two matrices.
○ Difference between two matrices.
○ Product of two matrices.
o Transpose of a matrix.
Solution:
<?php
$array = array("a" => 10, "b" => 20, "c" => 30);
echo "Number of elements: " . count($array) . "\n";

foreach ($array as $key => $value) {


echo "Key: $key, Value: $value\n";
}

$array2D = array(
"row1" => array("a" => 1, "b" => 2),
"row2" => array("c" => 3, "d" => 4)
);

echo "\n2D Array values:\n";


foreach ($array2D as $row => $values) {
foreach ($values as $key => $value) {
echo "Row: $row, Key: $key, Value: $value\n";
}
}

$matrix1 = array(
array(1, 2),
array(3, 4)
);

$matrix2 = array(
array(5, 6),
array(7, 8)
);
echo "\nSum of matrices:\n";
for ($i = 0; $i < 2; $i++) {
for ($j = 0; $j < 2; $j++) {
echo $matrix1[$i][$j] + $matrix2[$i][$j] . " ";

Page-20
DWD LAB FILE BCA SEM - III E1 01521102024
}
echo "\n";
}

echo "\nDifference of matrices:\n";


for ($i = 0; $i < 2; $i++) {
for ($j = 0; $j < 2; $j++) {
echo $matrix1[$i][$j] - $matrix2[$i][$j] . " ";
}
echo "\n";
}

echo "\nProduct of matrices:\n";


for ($i = 0; $i < 2; $i++) {
for ($j = 0; $j < 2; $j++) {
$product = 0;
for ($k = 0; $k < 2; $k++) {
$product += $matrix1[$i][$k] * $matrix2[$k][$j];
}
echo $product . " ";
}
echo "\n";
}

echo "\nTranspose of matrix 1:\n";


for ($i = 0; $i < 2; $i++) {
for ($j = 0; $j < 2; $j++) {
echo $matrix1[$j][$i] . " ";
}
echo "\n";
}
?>

Page-21
DWD LAB FILE BCA SEM - III E1 01521102024
OUTPUT:

Page-22
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.20

AIM- Create a program in php to find the following:

● Sum of two matrices.


● Difference of two matrices.
● Product of two matrices.
● Transpose of two matrices.

Solution: <?php

$matrix1 = array(

array(1, 2, 3),

array(4, 5, 6),

array(7, 8, 9)

);

$matrix2 = array(

array(9, 8, 7),

array(6, 5, 4),

array(3, 2, 1)

);

function display_matrix($matrix) {

foreach ($matrix as $row) {

echo implode("\t", $row) . "\n";

function matrix_sum($matrix1, $matrix2) {

$result = array();

for ($i = 0; $i < count($matrix1); $i++) {

for ($j = 0; $j < count($matrix1[$i]); $j++) {

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


Page-23
DWD LAB FILE BCA SEM - III E1 01521102024
}

return $result;

function matrix_difference($matrix1, $matrix2) {

$result = array();

for ($i = 0; $i < count($matrix1); $i++) {

for ($j = 0; $j < count($matrix1[$i]); $j++) {

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

return $result;

function matrix_product($matrix1, $matrix2) {

$result = array();

for ($i = 0; $i < count($matrix1); $i++) {

for ($j = 0; $j < count($matrix2[0]); $j++) {

$result[$i][$j] = 0;

for ($k = 0; $k < count($matrix2); $k++) {

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

return $result;

function transpose_matrix($matrix) {

Page-24
DWD LAB FILE BCA SEM - III E1 01521102024
$result = array();

for ($i = 0; $i < count($matrix[0]); $i++) {

for ($j = 0; $j < count($matrix); $j++) {

$result[$i][$j] = $matrix[$j][$i];

return $result;

echo "Matrix 1:\n";

display_matrix($matrix1);

echo "\nMatrix 2:\n";

display_matrix($matrix2);

echo "\nSum of Matrix 1 and Matrix 2:\n";

$sum = matrix_sum($matrix1, $matrix2);

display_matrix($sum);

echo "\nDifference of Matrix 1 and Matrix 2:\n";

$difference = matrix_difference($matrix1, $matrix2);

display_matrix($difference);

echo "\nProduct of Matrix 1 and Matrix 2:\n";

$product = matrix_product($matrix1, $matrix2);

display_matrix($product);

echo "\nTranspose of Matrix 1:\n";

$transpose1 = transpose_matrix($matrix1);

display_matrix($transpose1);

echo "\nTranspose of Matrix 2:\n";

$transpose2 = transpose_matrix($matrix2);

Page-25
DWD LAB FILE BCA SEM - III E1 01521102024
display_matrix($transpose2);

?>

OUTPUT:

Page-26
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.21

AIM- Write a PHP script to sort the following associative array:

● Ascending order sort by value.


● Ascending order sort by key.
● Descending order sorting by value.
● Descending order sorting by key.
● Display all the keys of the array.
● Display all the values of the array.
● Display all key-value pairs.

Solution:

<?php

$array = array("apple" => 2, "banana" => 3, "orange" => 1, "mango" => 4);

asort($array);

echo "Ascending order sort by value:\n";

print_r($array);

ksort($array);

echo "Ascending order sort by key:\n";

print_r($array);

arsort($array);

echo "Descending order sort by value:\n";

print_r($array);

krsort($array);

echo "Descending order sort by key:\n";

print_r($array);

echo "All keys:\n";

print_r(array_keys($array));

echo "All values:\n";

Page-27
DWD LAB FILE BCA SEM - III E1 01521102024
print_r(array_values($array));

?>

OUTPUT:

Page-28
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.22
AIM- Write a program in PHP to demonstrate the use of following functions: arrrat_pad(),
array_slice(), array_splice(), list().
Solution:
<?php
// 1. array_pad()
$input = [1, 2, 3];
$paddedArray = array_pad($input, 5, 0); // Pads to length 5 with 0
echo "array_pad():\n";
print_r($paddedArray);

// 2. array_slice()
$fruits = ["apple", "banana", "cherry", "date", "fig"];
$slicedArray = array_slice($fruits, 1, 3); // Get 3 elements starting from index 1
echo "\narray_slice():\n";
print_r($slicedArray);

// 3. array_splice()
$numbers = [10, 20, 30, 40, 50];
$removed = array_splice($numbers, 2, 2, [99, 100]);
// Remove 2 elements starting at index 2 (30, 40) and replace with [99, 100]
echo "\narray_splice():\n";
echo "Removed elements: ";
print_r($removed);
echo "Modified array: ";
print_r($numbers);

// 4. list()
$data = ["John", "Doe", 30];
list($firstName, $lastName, $age) = $data;
echo "\nlist():\n";
echo "First Name: $firstName\n";
echo "Last Name: $lastName\n";
echo "Age: $age\n";
?>

Page-29
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.23
Aim- Write a function to reverse a string.
Solution:
<?php
function rev($str) {
$reversed = '';
// Loop through the string from the end to the beginning
for ($i = strlen($str) - 1; $i >= 0; $i--) {
$reversed .= $str[$i];
}
return $reversed;
}

$ori = "Hello, world!";


echo "Original: $ori\n";
echo "Reversed: ".rev($ori)."\n";
?>

OUTPUT:

Page-30
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.24
Aim- Write a php function that checks whether a passed string is palindrome or not.
Solution:
<?php
function isPalindrome($string) {

$string = strtolower(str_replace(' ', '', $string));

$reversed = strrev($string);

if ($string === $reversed) {


echo "The string '$string' is a palindrome.\n";
} else {
echo "The string '$string' is not a palindrome.\n";
}
}

isPalindrome("Madam");
isPalindrome("sir");
isPalindrome("MOM");
?>

OUTPUT:

Page-31
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.25
Aim- Write a PHP script:
i. Transform a string to all uppercase letters.
ii. Transform a string to all lowercase letters.
iii. Make a string’s first character uppercase.
Make a string’s first character of all the words uppercase.
Solution:
<?php
$string = "welcome to php programming";

$uppercase = strtoupper($string);

$lowercase = strtolower($string);

$firstCharUpper = ucfirst($string);

$allWordsUpper = ucwords($string);

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

echo "All Uppercase: $uppercase<br>";

echo "All Lowercase: $lowercase<br>";

echo "First Character Uppercase: $firstCharUpper<br>";

echo "First Character of All Words Uppercase: $allWordsUpper<br>";


?>
OUTPUT:

Page-32
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.26
Aim- Write a program in PHP to perform sorting on an array using a user-defined function.
Solution:
<?php
function sortArray($arr) {

for ($i = 0; $i < count($arr); $i++) {

for ($j = $i + 1; $j < count($arr); $j++) {

if ($arr[$i] > $arr[$j]) {

$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
}
}

return $arr;
}

$numbers = array(45, 12, 78, 34, 23, 56);

echo "Original Array: ";


print_r($numbers);

$sorted = sortArray($numbers);

echo "<br><br>Sorted Array: ";


print_r($sorted);
?>
OUTPUT:

Page-33
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.27
Aim- Write a program in PHP to demonstrate the use of
(i) The $_GET variables
(ii) The $_POST variables
(iii) $_REQUEST variables
Solution:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>GET, POST and REQUEST Example</title>
</head>
<body>

<h2>Using GET Method</h2>


<form action="[Link]" method="get">
Name: <input type="text" name="name"><br><br>
Age: <input type="text" name="age"><br><br>
<input type="submit" value="Submit using GET">
</form>

<h2>Using POST Method</h2>


<form action="[Link]" method="post">
Name: <input type="text" name="name"><br><br>
Age: <input type="text" name="age"><br><br>
<input type="submit" value="Submit using POST">
</form>

<h2>Using REQUEST Method</h2>


<form action="[Link]" method="post">
Name: <input type="text" name="name"><br><br>
Age: <input type="text" name="age"><br><br>
<input type="submit" value="Submit using REQUEST">
</form>

</body>
</html>

[Link]
<?php
echo "Using \$_GET Variables<br><br>";

$name = $_GET['name'];
$age = $_GET['age'];

Page-34
DWD LAB FILE BCA SEM - III E1 01521102024

echo "Name: " . $name . "<br>";


echo "Age: " . $age . "<br>";
?>

[Link]
<?php
echo "Using \$_POST Variables<br><br>";

$name = $_POST['name'];
$age = $_POST['age'];

echo "Name: " . $name . "<br>";


echo "Age: " . $age . "<br>";
?>

[Link]
<?php
echo "Using \$_REQUEST Variables<br><br>";

$name = $_REQUEST['name'];
$age = $_REQUEST['age'];

echo "Name: " . $name . "<br>";


echo "Age: " . $age . "<br>";
?>
Output:

Page-35
DWD LAB FILE BCA SEM - III E1 01521102024

Page-36
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.28
Aim- Write a program in PHP to
(i) Create a file
(ii) Read and Display the contents of previously created file
(iii) Modify the contents of an existing file
Solution:
<?php
$filename = "[Link]";
$file = fopen($filename, "w");

fwrite($file, "Hello, this is the first line in the file.\n");


fwrite($file, "PHP makes file handling easy!\n");
fclose($file);

echo "File created and data written successfully.<br><br>";


$file = fopen($filename, "r");

echo "<b>Contents of the file:</b><br>";


while (!feof($file)) {
echo fgets($file) . "<br>";
}
fclose($file);

$file = fopen($filename, "a");


fwrite($file, "This line was added later using append mode.\n");
fclose($file);

echo "<br>File modified successfully. Check the file for updated contents.";
?>
OUTPUT:

Page-37
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.29
Aim- Create a form in PHP to upload and display images.
Solution:

<!DOCTYPE html>
<html>
<head>
<title>Image Upload and Display</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" required>
<input type="submit" name="upload" value="Upload">
</form>

<?php
if(isset($_POST['upload'])){
$target_dir = "uploads/";
if(!is_dir($target_dir)){
mkdir($target_dir);
}
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$allowed_types = array("jpg","jpeg","png","gif");
if(in_array($file_type, $allowed_types)){
if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){
echo "<h3>Image Uploaded Successfully</h3>";
echo "<img src='$target_file' width='300'>";
} else {
echo "Error uploading file.";
}
} else {
echo "Only JPG, JPEG, PNG & GIF files are allowed.";
}
}
?>

</body>
</html>

OUTPUT:

Page-38
DWD LAB FILE BCA SEM - III E1 01521102024

Page-39
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.30
Aim- Write a program to create a cookie. Read cookie value, and delete a cookie.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<?php
if(isset($_POST['create'])){
setcookie("username", $_POST['username'], time()+3600);
echo "Cookie created successfully.";
}
if(isset($_POST['read'])){
if(isset($_COOKIE['username'])){
echo "Cookie Value: " . $_COOKIE['username'];
} else {
echo "No cookie found.";
}
}
if(isset($_POST['delete'])){
setcookie("username", "", time()-3600);
echo "Cookie deleted successfully.";
}
?>
<form method="post">
<input type="text" name="username" placeholder="Enter Name">
<input type="submit" name="create" value="Create Cookie">
<input type="submit" name="read" value="Read Cookie">
<input type="submit" name="delete" value="Delete Cookie">
</form>
</body>
</html>

OUTPUT:

Page-40
DWD LAB FILE BCA SEM - III E1 01521102024

Page-41
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.31
Aim- Write a program in PHP to
(i) Start a PHP Session
(ii) Store Session variables
(iii) Destroy a session
Solution:
<html>
<head>
<title>Session Example</title>
</head>
<body>
<?php
session_start();
if(isset($_POST['store'])){
$_SESSION['user'] = $_POST['username'];
echo "Session variable stored successfully.";
}
if(isset($_POST['display'])){
if(isset($_SESSION['user'])){
echo "Session Value: " . $_SESSION['user'];
} else {
echo "No session found.";
}
}
if(isset($_POST['destroy'])){
session_unset();
session_destroy();
echo "Session destroyed successfully.";
}
?>
<form method="post">
<input type="text" name="username" placeholder="Enter Name">
<input type="submit" name="store" value="Store Session">
<input type="submit" name="display" value="Display Session">
<input type="submit" name="destroy" value="Destroy Session">
</form>
</body>
</html>
OUTPUT:

Page-42
DWD LAB FILE BCA SEM - III E1 01521102024

Page-43
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.32
Aim- Create Admin Login and Logout forms using Session variables.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Admin Login System</title>
</head>
<body>
<?php
session_start();
$admin_user = "admin";
$admin_pass = "12345";

if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == $admin_user && $password == $admin_pass){
$_SESSION['admin'] = $username;
echo "<h3>Login Successful. Welcome, $username!</h3>";
echo '<form method="post"><input type="submit" name="logout" value="Logout"></form>';
} else {
echo "<h3>Invalid Credentials</h3>";
}
} elseif(isset($_POST['logout'])){
session_unset();
session_destroy();
echo "<h3>You have been logged out.</h3>";
} elseif(isset($_SESSION['admin'])){
echo "<h3>Welcome, ".$_SESSION['admin']."!</h3>";
echo '<form method="post"><input type="submit" name="logout" value="Logout"></form>';
} else {
?>
<form method="post">
<h2>Admin Login</h2>
<input type="text" name="username" placeholder="Username" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>
<input type="submit" name="login" value="Login">
</form>
<?php
}
?>
</body>
</html>

Page-44
DWD LAB FILE BCA SEM - III E1 01521102024
OUTPUT:

Page-45
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.33
Aim- Write a program in PHP to create a class Student. Define constructors, destructors,
and methods to display student information, percentage, and grade. Use appropriate data
members.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Student Class Example</title>
</head>
<body>
<?php
class Student {
public $name;
public $roll_no;
public $marks = array();
public $total;
public $percentage;
public $grade;

function __construct($name, $roll_no, $marks) {


$this->name = $name;
$this->roll_no = $roll_no;
$this->marks = $marks;
$this->calculatePercentage();
$this->calculateGrade();
}

function calculatePercentage() {
$this->total = array_sum($this->marks);
$this->percentage = $this->total / count($this->marks);
}

function calculateGrade() {
if($this->percentage >= 90)
$this->grade = "A+";
elseif($this->percentage >= 75)
$this->grade = "A";
elseif($this->percentage >= 60)
$this->grade = "B";
elseif($this->percentage >= 50)
$this->grade = "C";
else
$this->grade = "Fail";

Page-46
DWD LAB FILE BCA SEM - III E1 01521102024
}

function displayInfo() {
echo "<h3>Student Information</h3>";
echo "Name: $this->name<br>";
echo "Roll No: $this->roll_no<br>";
echo "Total Marks: $this->total<br>";
echo "Percentage: $this->percentage%<br>";
echo "Grade: $this->grade<br>";
}

function __destruct() {
echo "<br>Object destroyed.";
}
}

$marks = array(85, 90, 94, 92, 90);


$student = new Student("Dishita", 15, $marks);
$student->displayInfo();
?>
</body>
</html>

OUTPUT:

Page-47
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.34
Aim- Write a program in PHP to create a class Person. Create another class Customer
which is a subclass of the class Person.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Inheritance Example</title>
</head>
<body>
<?php
class Person {
public $name;
public $age;
public $address;

function __construct($name, $age, $address) {


$this->name = $name;
$this->age = $age;
$this->address = $address;
}

function displayPersonInfo() {
echo "<h3>Person Details</h3>";
echo "Name: $this->name<br>";
echo "Age: $this->age<br>";
echo "Address: $this->address<br>";
}
}

class Customer extends Person {


public $customer_id;
public $purchase_amount;

function __construct($name, $age, $address, $customer_id, $purchase_amount) {


parent::__construct($name, $age, $address);
$this->customer_id = $customer_id;
$this->purchase_amount = $purchase_amount;
}

function displayCustomerInfo() {
$this->displayPersonInfo();
echo "<h4>Customer Details</h4>";
echo "Customer ID: $this->customer_id<br>";
echo "Purchase Amount: ₹$this->purchase_amount<br>";
Page-48
DWD LAB FILE BCA SEM - III E1 01521102024
}
}

$customer1 = new Customer("Dishita Rawat", 19, "Delhi", 1001, 8500);


$customer1->displayCustomerInfo();
?>
</body>
</html>

OUTPUT:

Page-49
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.35
Aim- Write a program in PHP to demonstrate the use of access modifiers.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Access Modifiers Example</title>
</head>
<body>
<?php
class Employee {
public $name;
private $salary;
protected $position;

function __construct($name, $salary, $position) {


$this->name = $name;
$this->salary = $salary;
$this->position = $position;
}

public function showPublicInfo() {


echo "Name: $this->name<br>";
}

private function showPrivateInfo() {


echo "Salary: ₹$this->salary<br>";
}

protected function showProtectedInfo() {


echo "Position: $this->position<br>";
}

public function showAllDetails() {


$this->showPublicInfo();
$this->showPrivateInfo();
$this->showProtectedInfo();
}
}

class Manager extends Employee {


public function showManagerDetails() {
echo "<h3>Manager Details</h3>";
echo "Name: $this->name<br>";
echo "Position: $this->position<br>";
Page-50
DWD LAB FILE BCA SEM - III E1 01521102024
}
}

$emp = new Employee("Dishita", 80000, "Developer");


echo "<h3>Employee Details</h3>";
$emp->showAllDetails();

echo "<br>";

$mgr = new Manager("Riya", 90000, "Project Manager");


$mgr->showManagerDetails();
?>
</body>
</html>

OUTPUT:

Page-51
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.36
Aim- Write steps to create a database in phpMyAdmin. Create users and assign privileges.
Solution:
Step 1: Open phpMyAdmin
• Open your browser
• Type: [Link]
• Press Enter.

Step 2: Log In
• Enter username and password (usually root / your password).

(Add to the [Link] File to log in automatically)

Step 3: Go to the “Databases” Tab


• On the top menu, click Databases.

Page-52
DWD LAB FILE BCA SEM - III E1 01521102024

Step 4: Enter a Database Name


• In the “Create database” section
→ Type your database name (example: dr_php).
Step 5: Select Collation (Optional)
• Collation decides the character encoding.
• If you want default, keep it as it is.

Step 6: Click “Create”


• Your database will now be created and will appear on the left panel.

Create Users and Assign Privileges in PHP


Solution:
<?php
// Connection as root user (or any admin user)
$conn = new mysqli("localhost", "root", "dishita");

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

Page-53
DWD LAB FILE BCA SEM - III E1 01521102024
}
$new_user = "newroot";
$new_password = "newdishita";

$sql1 = "CREATE USER '$new_user'@'localhost' IDENTIFIED BY '$new_password'";

$sql2 = "GRANT ALL PRIVILEGES ON dishita.* TO '$new_user'@'localhost'";

$sql3 = "FLUSH PRIVILEGES";


if ($conn->query($sql1) === TRUE) {
echo "User created successfully<br>";
} else {
echo "Error creating user: " . $conn->error . "<br>";
}
if ($conn->query($sql2) === TRUE) {
echo "Privileges granted<br>";
} else {
echo "Error granting privileges: " . $conn->error . "<br>";
}
$conn->query($sql3);
$conn->close();
?>

OUTPUT:

Page-54
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.37
AIM- Write a program in PHP to create a database table using appropriate data types and
constraints.
Solution:
<?php
$servername = "localhost";
$username = "root"; // default user for local server
$password = "dishita"; // keep blank if no password
$dbname = "dishita"; // make sure this database already exists

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

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

$sql = "CREATE TABLE IF NOT EXISTS Students_PHP (


student_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
gender ENUM('Male', 'Female', 'Other') NOT NULL,
dob DATE,
course VARCHAR(50) NOT NULL,
marks DECIMAL(5,2) CHECK(marks >= 0 AND marks <= 100),
registered_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)";

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


echo "Table Students_PHP created successfully.";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

OUTPUT:

Page-55
DWD LAB FILE BCA SEM - III E1 01521102024

Page-56
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.38
AIM- Write a program in PHP to open a Connection to the MySQL Server, insert at least
10 records in a database table, display the inserted records and Close the Connection.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Insert and Display Records</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "dishita";
$dbname = "dishita";

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

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

$sql = "CREATE TABLE IF NOT EXISTS Students_PHP (


student_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
course VARCHAR(50) NOT NULL,
marks DECIMAL(5,2) CHECK(marks >= 0 AND marks <= 100)
)";
$conn->query($sql);

$records = [
['Aditi Sharma', 'BCA', 85.5],
['Rahul Mehta', 'BBA', 78.0],
['Sneha Kapoor', '[Link]', 92.3],
['Arjun Verma', 'BCA', 67.8],
['Priya Singh', 'BA', 73.4],
['Karan Patel', '[Link]', 88.1],
['Neha Jain', '[Link]', 81.7],
['Rohit Yadav', 'BCA', 69.5],
['Anjali Gupta', 'BBA', 90.2],
['Vivek Rao', '[Link]', 76.9]
];

foreach ($records as $student) {


$sql = "INSERT INTO Students_PHP (name, course, marks)
Page-57
DWD LAB FILE BCA SEM - III E1 01521102024
VALUES ('$student[0]', '$student[1]', $student[2])";
$conn->query($sql);
}

echo "<h3>Inserted Records:</h3>";


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

if ($result->num_rows > 0) {
echo "<table border='1' cellpadding='5'>
<tr><th>ID</th><th>Name</th><th>Course</th><th>Marks</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['student_id']}</td>
<td>{$row['name']}</td>
<td>{$row['course']}</td>
<td>{$row['marks']}</td>
</tr>";
}
echo "</table>";
} else {
echo "No records found.";
}

$conn->close();
echo "<br>Connection closed successfully.";
?>
</body>
</html>
OUTPUT:

Page-58
DWD LAB FILE BCA SEM - III E1 01521102024

Page-59
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.39
AIM- Write a PHP program to perform UPDATE and DELETE operations on a database
table.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Update and Delete Example</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "dishita";
$dbname = "dishita";

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


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

$sql = "CREATE TABLE IF NOT EXISTS Students_PHP (


student_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
course VARCHAR(50),
marks DECIMAL(5,2)
)";
$conn->query($sql);

if(isset($_POST['update'])){
$id = $_POST['id'];
$marks = $_POST['marks'];
$sql = "UPDATE Students_PHP SET marks=$marks WHERE student_id=$id";
if($conn->query($sql))
echo "<p>Record with ID $id updated successfully.</p>";
else
echo "<p>Error updating record: " . $conn->error . "</p>";
}

if(isset($_POST['delete'])){
$id = $_POST['id'];
$sql = "DELETE FROM Students_PHP WHERE student_id=$id";
if($conn->query($sql))
echo "<p>Record with ID $id deleted successfully.</p>";
else
Page-60
DWD LAB FILE BCA SEM - III E1 01521102024
echo "<p>Error deleting record: " . $conn->error . "</p>";
}

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


if ($result->num_rows > 0) {
echo "<h3>Student Records</h3>
<table border='1' cellpadding='5'>
<tr><th>ID</th><th>Name</th><th>Course</th><th>Marks</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['student_id']}</td>
<td>{$row['name']}</td>
<td>{$row['course']}</td>
<td>{$row['marks']}</td>
</tr>";
}
echo "</table>";
} else {
echo "<p>No records found.</p>";
}
?>

<h3>Update Marks</h3>
<form method="post">
Enter Student ID: <input type="number" name="id" required><br><br>
Enter New Marks: <input type="number" name="marks" step="0.01" required><br><br>
<input type="submit" name="update" value="Update Record">
</form>

<h3>Delete Record</h3>
<form method="post">
Enter Student ID: <input type="number" name="id" required><br><br>
<input type="submit" name="delete" value="Delete Record">
</form>

<?php
$conn->close();
?>
</body>
</html>

OUTPUT:

Page-61
DWD LAB FILE BCA SEM - III E1 01521102024

Page-62
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.40
AIM- Write a PHP program to display records from a database table using different
conditions.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>Display Records with Conditions</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "dishita";
$dbname = "dishita";

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


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

$sql = "CREATE TABLE IF NOT EXISTS Students_PHP (


student_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
course VARCHAR(50),
marks DECIMAL(5,2)
)";
$conn->query($sql);

$records = [
['Aditi Sharma', 'BCA', 85.5],
['Rahul Mehta', 'BBA', 78.0],
['Sneha Kapoor', '[Link]', 92.3],
['Arjun Verma', 'BCA', 67.8],
['Priya Singh', 'BA', 73.4],
['Karan Patel', '[Link]', 88.1],
['Neha Jain', '[Link]', 81.7],
['Rohit Yadav', 'BCA', 69.5],
['Anjali Gupta', 'BBA', 90.2],
['Vivek Rao', '[Link]', 76.9]
];
foreach ($records as $student) {
$conn->query("INSERT IGNORE INTO Students_PHP (name, course, marks)
VALUES ('$student[0]', '$student[1]', $student[2])");
}
Page-63
DWD LAB FILE BCA SEM - III E1 01521102024

if(isset($_POST['condition'])){
$condition = $_POST['condition'];
if($condition == "all"){
$sql = "SELECT * FROM Students_PHP";
} elseif($condition == "above80"){
$sql = "SELECT * FROM Students_PHP WHERE marks > 80";
} elseif($condition == "bca"){
$sql = "SELECT * FROM Students_PHP WHERE course='BCA'";
} elseif($condition == "name"){
$name = $_POST['name_search'];
$sql = "SELECT * FROM Students_PHP WHERE name LIKE '%$name%'";
}

$result = $conn->query($sql);
if($result->num_rows > 0){
echo "<h3>Filtered Records:</h3>
<table border='1' cellpadding='5'>
<tr><th>ID</th><th>Name</th><th>Course</th><th>Marks</th></tr>";
while($row = $result->fetch_assoc()){
echo "<tr>
<td>{$row['student_id']}</td>
<td>{$row['name']}</td>
<td>{$row['course']}</td>
<td>{$row['marks']}</td>
</tr>";
}
echo "</table>";
} else {
echo "<p>No records found.</p>";
}
}
?>

<h3>Display Records Based on Conditions</h3>


<form method="post">
<select name="condition">
<option value="all">Show All Records</option>
<option value="above80">Show Students with Marks > 80</option>
<option value="bca">Show Students Enrolled in BCA</option>
<option value="name">Search by Name</option>
</select><br><br>
Enter Name (if searching by name): <input type="text" name="name_search"><br><br>
<input type="submit" value="Display Records">
</form>

Page-64
DWD LAB FILE BCA SEM - III E1 01521102024

<?php
$conn->close();
?>
</body>
</html>

OUTPUT:

Page-65
DWD LAB FILE BCA SEM - III E1 01521102024
Practical No.41
AIM- Write a program in PHP to perform insert, update, delete, and select operations using
PDO.
Solution:
<!DOCTYPE html>
<html>
<head>
<title>CRUD using PDO</title>
</head>
<body>
<?php
$host = "localhost";
$dbname = "dishita";
$username = "root";
$password = "dishita";

try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<h3>Connected successfully using PDO</h3>";

$sql = "CREATE TABLE IF NOT EXISTS Students_PHP (


student_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
course VARCHAR(50),
marks DECIMAL(5,2)
)";
$conn->exec($sql);

if (isset($_POST['insert'])) {
$stmt = $conn->prepare("INSERT INTO Students_PHP (name, course, marks) VALUES (:name, :course,
:marks)");
$stmt->bindParam(':name', $_POST['name']);
$stmt->bindParam(':course', $_POST['course']);
$stmt->bindParam(':marks', $_POST['marks']);
$stmt->execute();
echo "<p>Record inserted successfully.</p>";
}

if (isset($_POST['update'])) {
$stmt = $conn->prepare("UPDATE Students_PHP SET marks = :marks WHERE student_id = :id");
$stmt->bindParam(':marks', $_POST['marks']);
$stmt->bindParam(':id', $_POST['id']);
$stmt->execute();
echo "<p>Record updated successfully.</p>";
Page-66
DWD LAB FILE BCA SEM - III E1 01521102024
}

if (isset($_POST['delete'])) {
$stmt = $conn->prepare("DELETE FROM Students_PHP WHERE student_id = :id");
$stmt->bindParam(':id', $_POST['id']);
$stmt->execute();
echo "<p>Record deleted successfully.</p>";
}

echo "<h3>Student Records:</h3>";


$stmt = $conn->prepare("SELECT * FROM Students_PHP");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($stmt->rowCount() > 0) {
echo "<table border='1' cellpadding='5'>
<tr><th>ID</th><th>Name</th><th>Course</th><th>Marks</th></tr>";
foreach ($result as $row) {
echo "<tr>
<td>{$row['student_id']}</td>
<td>{$row['name']}</td>
<td>{$row['course']}</td>
<td>{$row['marks']}</td>
</tr>";
}
echo "</table>";
} else {
echo "No records found.";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

<h3>Insert Record</h3>
<form method="post">
Name: <input type="text" name="name" required><br><br>
Course: <input type="text" name="course" required><br><br>
Marks: <input type="number" step="0.01" name="marks" required><br><br>
<input type="submit" name="insert" value="Insert Record">
</form>

<h3>Update Record</h3>
<form method="post">

Page-67
DWD LAB FILE BCA SEM - III E1 01521102024
Student ID: <input type="number" name="id" required><br><br>
New Marks: <input type="number" step="0.01" name="marks" required><br><br>
<input type="submit" name="update" value="Update Record">
</form>

<h3>Delete Record</h3>
<form method="post">
Student ID: <input type="number" name="id" required><br><br>
<input type="submit" name="delete" value="Delete Record">
</form>
</body>
</html>

OUTPUT:

Page-68
DWD LAB FILE BCA SEM - III E1 01521102024

Page-69

You might also like