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

New PHP

Uploaded by

zdi12966
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)
6 views

New PHP

Uploaded by

zdi12966
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Practical File on

Web Based Programming 313

Information Technology Management


Bachelor of Computer Application (BCA)
Guru Gobind Singh Indraprastha University, Delhi

Submitted To: Submitted By:


Ms. Suman Name: Aashutosh Rajput
(Assistant Professor - IT) EnrollmentNo:00121102020

Institute of Information Technology & Management


AASHUTOSH RAJPUT WBP LAB 00121102020

S. No. Problem Statement Date


1. Design the following static web pages required for an online book store web site. 16-09-2022
A. HOME PAGE: The static home page must contain three frames.
B. LOGIN PAGE
C. CATOLOGUE PAGE: The catalogue page should contain the details of
all the books available in the web site in a table.
D. REGISTRATION PAGE

2. Write JavaScript to validate the following fields of the Registration page. 23-09-2022
A. First Name (Name should contains alphabets and the length should not be
less than 6 characters).
B. Password (Password should not be less than 6 characters length).
C. E-mail id (should not contain any invalid and must follow the standard
pattern [email protected])
D. Mobile Number (Phone number should contain 10 digits only).
E. Last Name and Address (should not be Empty).

3. Write and explain the installation steps and method of PHP using screen shots. 30-09-2022
PHP can be installed using two ways:
1) Using WAMP
2) Using XAMP

4. Write a script to echo the following to the browser, using the variable you created: 30-09-2022
“What goes around, comes around.”

5. Write a PHP Script to calculate the area and circumference of circle. 07-10-2022

6. Write a script to reproduce the output below. Manipulate only one variable using 07-10-2022
simple and using no simple arithmetic operators (assignment operator s) to
produce the values given in the statements. In the script each statement ends with
"Value is now $variable."
Value is now 8.
Add 2. Value is now 10.
Subtract 4. Value is now 6.
Multiply by 5. Value is now 30.
Divide by 3. Value is now 10.
Increment value by one. Value is now 11.
Decrement value by one. Value is now 10.

7. Write a script using one variable “$whatisit” to print the following to the browser. 07-10-2022
Your echo statements may include no words except “Value is”.
Value is string.
Value is double.
Value is boolean.
AASHUTOSH RAJPUT WBP LAB 00121102020

Value is integer.
Value is NULL.

8. Write a PHP scripts to differentiate the print and echo command 14-10-2022

9. Write a script to display implicit casting and explicit casting 14-10-2022

10. Write a PHP scripts to differentiate the $ and $$. 14-10-2022

11. Write a program to calculate Electricity bill in PHP 21-10-2022


Conditions:
For first 50 units – Rs. 3.50/unit
For next 100 units – Rs. 4.00/unit
For next 100 units – Rs. 5.20/unit
For units above 250 – Rs. 6.50/unit
Hint:-You can use conditional statements.

12. Write a PHP script using nested for loop that creates a chess board 21-10-2022

13. Write a PHP program to find three numbers from an array such that the sum of 21-10-2022
three consecutive numbers equal to zero.

14. Create an index array with value red, green, orange, blue, pink, white and black, 28-10-2022
Count the total array and display all values of array using for loop.

15. Create an Associative array with value fruits, veggie, dry-fruits and Count the 28-10-2022
total array and display all values of array using for each loop.

16. Create an Multidimensional Array and Display the array with index and values 28-10-2022
using <pre> tag.

17. Write a PHP script to sort the following associative array : 28-10-2022
array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40") in
a) ascending order sort by value
b) ascending order sort by Key
c) descending order sorting by Value
d) descending order sorting by Key

18. WAP to swap two values (call by reference) using function 04-11-2022

19. WAP to create a PHP form according to the given format 04-11-2022
AASHUTOSH RAJPUT WBP LAB 00121102020

20. Design a form given below with validation and error message in PHP 11-11-2022

21. Write a PHP Script to demonstrate the file handling in 18-11-2022


php(fopen,fclose,fread,fwrite,file length)

22. Write a program to upload a file. 18-11-2022

23. Write a program to store the current date and time in a cookie and display the last 25-11-2022
visited date and time on the web page

24. Write a program to store page views counting session to increment the count on 25-11-2022
each refresh and to show the count on the page

25. Write and explain the steps to create a database, table, select query using 2-12-2022
PhpMyadmin.

26. Write a PHP program to 16-12-2022


 create a connection,
 create a database and
 create a table
27 Write a PHP program for sending and receiving plain text message (e -mail). 16-12-2022
28. Write a PHP program to insert record into a table 23-12-2022
29. Write a PHP program to select data and show into table format 23-12-2022
AASHUTOSH RAJPUT WBP LAB 00121102020

30. Create a student Registration in PHP and Save and Display the student Records. 30-12-2022
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.1 Design the following static web pages required for an online book store web
site.
A. HOME PAGE: The static home page must contain three frames.
B. LOGIN PAGE
C. CATOLOGUE PAGE: The catalogue page should contain the details of all
the books available in the web site in a table.
D. REGISTRATION PAGE

Source Code-

<html>

<head>
<title>Registration Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
.col-lg-9 {
float: right;
margin-top: -80px;
margin-right: 500px;
color: white;
}

.container {
background-color: #ac2727;
min-height: 300px;
}

.img-pos {
z-index: 999;
position: relative;
AASHUTOSH RAJPUT WBP LAB 00121102020

left: 70px;
top: 50px;
}

.container2 {
margin-top: 40px;
text-align: center;
max-width: 400px;
position: relative;
left: 700px;
}
</style>
</head>

<body>
<div class="container">
<div class="row">
<div class="col-lg-3">
<img class="img-pos" src="iitm-new_logo.jpg" height="82" width="160" alt="">
</div>
<div class="col-lg-9">
<h1>Institute of Information Technology & Management</h1>
<h3>Accredited Grade "A" by National Assessment and Accreditation Council
(NAAC)</h3>
<h3>Approved by AICTE</h3>
<h3>Rated as Category 'A+' by SFRC & 'A' by JAC Govt. of NCT of Delhi</h3>
<h3>Recognised U/s 2(f) of UGC Act</h3>
<h3>Affiliated to Guru Gobind Singh Indraprastha University, New Delhi</h3>
</div>
AASHUTOSH RAJPUT WBP LAB 00121102020

</div>
</div>
<div class="container2">
<form action="" method="get">
<fieldset>
<legend>Contact Details</legend>
<label for="fname">First Name:</label>
<input type="text" id="name" name="fname" minlength="6"><br><br>
<label for="name">Last Name:</label>
<input type="text" id="lname" name="lname" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" minlength="6"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<h2 id="result"></h2><br><br>
<label for="phone">Phone Number:</label>
<input type="numberic" id="phone" name="phone" maxlength="10"
onkeypress="return validateNumber(event)"><br><br>
<label for="address">Address:</label>
<textarea name="address" id="address" cols="25" rows="2"
required></textarea><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</div>

<script type="text/javascript">
const validateEmail = (email) => {
return email.match(
AASHUTOSH RAJPUT WBP LAB 00121102020

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-
9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};

const validate = () => {


const $result = $('#result');
const email = $('#email').val();
$result.text('');

if (validateEmail(email)) {
$result.text(email + ' is valid :)');
$result.css('color', 'green');
} else {
$result.text(email + ' is not valid :(');
$result.css('color', 'red');
}
return false;
}

$('#email').on('input', validate);

function validateNumber(e) {
const pattern = /^[0-9]$/;

return pattern.test(e.key)
}
</script>
</body>
AASHUTOSH RAJPUT WBP LAB 00121102020

</html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.2 Write JavaScript to validate the following fields of the


Registration page.
A. First Name (Name should contains alphabets and the
length should not be less than 6 characters).
B. Password (Password should not be less than 6 characters
length).
C. E-mail id (should not contain any invalid and must
follow the standard pattern [email protected])
D. Mobile Number (Phone number should contain 10 digits
only).
E. Last Name and Address (should not be Empty).
Source Code-
<html>
<head>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+f
zT" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">
<div align="center">
<h1>Registration Form</h1> </div>
<form class="mt-5">
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">First Name</label>
<input type="text" class="form-control" required minlength="6"> </div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Last Name</label>
<input type="text" class="form-control" required> </div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Phone No.</label>
<input type="number" oninput="javascript: if (this.value.length >
this.maxLength) this.value = this.value.slice(0, this.maxLength);" class="form-
control" required minlength="10" maxlength="10"> </div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Address</label>
<input type="text" class="form-control" required> </div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Email
address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-
describedby="emailHelp" required> </div>
<div class="mb-3">
AASHUTOSH RAJPUT WBP LAB 00121102020

<label for="exampleInputPassword1" class="form-


label">Password</label>
<input type="password" class="form-control"
id="exampleInputPassword1" required minlength="6"> </div>
<button type="submit" class="btn btn-primary">Submit</button>
</form> </div>
</body>
</html>
Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.3 Write and explain the installation steps and method of PHP using
screen shots.
PHP can be installed using two ways:
1) Using WAMP
2) Using XAMP
WAMP: WAMP Server refers to a solution stack for the Microsoft Windows operating system,
created by Romaine Bourdon and consisting of the Apache web server, Open SSL for SSL support,
MySQL database and PHP programming language

XAMP: XAMPP is a free and open-source cross-platform web server solution stack package
developed by Apache Friends, consisting mainly of the Apache HTTP Server, Maria DB database,
and interpreters for scripts written in the PHP and Perl programming languages.

Installation Steps of XAMP:


Step 1- Click on Next
AASHUTOSH RAJPUT WBP LAB 00121102020

Step 2- again click on Next

Step 3- Choose folder path and then click on next


st
AASHUTOSH RAJPUT WBP LAB 00121102020
AASHUTOSH RAJPUT WBP LAB 00121102020

Step 4- After downloading the package then click on finish.


AASHUTOSH RAJPUT WBP LAB 00121102020

WAMP installation guide

1. Double click on the wamp installation executable (we have used Wamp Server
2.0i.exe ) to start the installation.

2. Select I accept the agreement.

3. Select destination folder.


AASHUTOSH RAJPUT WBP LAB 00121102020

4. Click Install to beginning the installation.

5. Select the default browser WAMP server going to use.


AASHUTOSH RAJPUT WBP LAB 00121102020

6. Supply PHP mail parameters and click next. This finishes the installation.
AASHUTOSH RAJPUT WBP LAB 00121102020

Q. 4 Write a script to echo the following to the browser, using the variable you
created: “What goes around, comes around.”
Source Code-
<html>
<body>

<?php
$var = "What goes around, comes around.";
echo "$var";
?>
</body>
</html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.5 Write a PHP Script to calculate the area and circumference of circle.
Source Code-
<?php
$radius = 10;
$area = pi() * pow($radius, 2);
$area = round($area, 3);
$circumference = 2 * pi() * $radius;
$circumference = round($circumference, 3);
echo (" Area of circle is $area");
echo ("Circumference of the circle is $circumference");
?>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.6 Write a script to reproduce the output below. Manipulate only one
variable using simple and using no simple arithmetic operators (assignment
operator s) to produce the values given in the statements. In the script each
statement ends with
"Value is now $variable."
 Value is now 8.
 Add 2. Value is now 10.
 Subtract 4. Value is now 6.
 Multiply by 5. Value is now 30.
 Divide by 3. Value is now 10.
 Increment value by one. Value is now 11.
 Decrement value by one. Value is now 10.

Source Code-
<?php $numbers=array("8","10","6","30","11");
echo "Value is now {$numbers[0]}.<br>";
echo "Add 2. Value is now {$numbers[1]}.<br>";
echo "Subtract 4. Value is now {$numbers[2]}.<br>";
echo "Multiply by 5. Value is now{$numbers[3]}.<br>";
echo "Divide by 3. Value is now {$numbers[1]}.<br>";
echo "Increment value by one. Value is now
{$numbers[4]}.<br>";
echo "Decrement value by one. Value is now
{$numbers[1]}.<br>"; ?>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.7 Write a script using one variable “$whatisit” to print the following to the
browser. Your echo statements may include no words except
“Value is”.
 Value is string.
 Value is double.
 Value is Boolean.
 Value is integer.

Value is NULL.
Source Code-
<html>
<body>
<?php
$whatsit = '10';
echo "Value is " . gettype($whatsit) . ".<br>";
$whatsit = 10.1;
echo "Value is " . gettype($whatsit) . ".<br>";
$whatsit = true;
echo "Value is " . gettype($whatsit) . ".<br>";
$whatsit = 10;
echo "Value is " . gettype($whatsit) . ".<br>";
$whatsit = null;
echo "Value is " . gettype($whatsit) . ".<br>";
?>
</body> </html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.8 Write a PHP scripts to differentiate the print and echo command.
Source Code-
<html>
<body>
<?php

echo "IITM","Janakpuri";
echo "<br>";
print "Hello Siri";
?>
</body>
</html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.9 Write a script to display implicit casting and explicit casting.


Implicit casting
<html>
<body>
<?php
$x = 2; $y = 4;
var_dump($x / $y);
echo "<br>";
var_dump($y / $x);
?>
</body>
</html>

Output-

Explicit casting.
<html>
<body>
<?php
$x = 5.35;
$y = (int) $x;
var_dump($y);
?>
</body>
</html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.10 Write a PHP scripts to differentiate the $ and $$.


Source Code-
<?php
$x = "abc";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo $abc;
?>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.11 Write a program to calculate Electricity bill in


PHP Conditions:
For first 50 units – Rs. 3.50/unit
For next 100 units – Rs. 4.00/unit
For next 100 units – Rs. 5.20/unit
For units above 250 – Rs. 6.50/unit
Hint:-You can use conditional statements.

Source Code-
<!DOCTYPE html>

<head>
<title>Calculate Electricity Bill</title>
</head>

<?php
$result_str = $result = '';
if (isset($_POST['unit-submit'])) {
$units = $_POST['units'];
if (!empty($units)) {
$result = calculate_bill($units);
$result_str = 'Total amount of ' . $units . ' - ' . $result;
}
}
function calculate_bill($units) {
$unit_cost_first = 3.50;
$unit_cost_second = 4.00;
$unit_cost_third = 5.20;
$unit_cost_fourth = 6.50;

if($units <= 50) {


$bill = $units * $unit_cost_first;
}
else if($units > 50 && $units <= 100) {
$temp = 50 * $unit_cost_first;
$remaining_units = $units - 50;
$bill = $temp + ($remaining_units * $unit_cost_second);
}
else if($units > 100 && $units <= 200) {
$temp = (50 * 3.5) + (100 * $unit_cost_second);
$remaining_units = $units - 150;
$bill = $temp + ($remaining_units * $unit_cost_third);
}
else {
$temp = (50 * 3.5) + (100 * $unit_cost_second) + (100 * $unit_cost_third);
AASHUTOSH RAJPUT WBP LAB 00121102020

$remaining_units = $units - 250;


$bill = $temp + ($remaining_units * $unit_cost_fourth);
}
return number_format((float)$bill, 2, '.', '');
}

?>

<body>
<div id="page-wrap">
<h1>Calculate Electricity Bill</h1>

<form action="" method="post" id="quiz-form">


<input type="number" name="units" id="units" placeholder="Please enter no. of Units"
/>
<input type="submit" name="unit-submit" id="unit-submit" value="Submit" />
</form>

<div>
<?php echo '<br />' . $result_str; ?>
</div>
</div>
</body>
</html>
Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.12 Write a PHP script using nested for loop that creates a chess board.
Source Code-
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h3>Chess Board using Nested For Loop</h3>
<table width="270px" cellspacing="0px" cellpadding="0px" border="1px">
<!-- cell 270px wide (8 columns x 60px) -->
<?php
for($row=1;$row<=8;$row++) {
echo "<tr>";
for($col=1;$col<=8;$col++)
{
$total=$row+$col;
if($total%2==0) {
echo "<td height=30px width=30px bgcolor=#FFFFFF></td>";
}
else
{
echo "<td height=30px width=30px bgcolor=#000000></td>";
}
}
echo "</tr>"; }
?>
</table>
</body>
</html>
Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.13 Write a PHP program to find three numbers from an array such that the
sum of three consecutive numbers equal to zero.
Source Code-
<?php
function three_Sum_zero($arr) {
$count = count($arr) - 2;
$result=[];
for ($x = 0; $x < $count; $x++) {
if ($arr[$x] + $arr[$x+1] + $arr[$x+2] == 0)
{
array_push($result, "{$arr[$x]} + {$arr[$x+1]} + {$arr[$x+2]} = 0");
} }
return $result;
}
$nums1= array(-1,0,1,2,-1,-4);
$nums2 = array(-25,-10,-7,-3,2,4,8,10);
print_r(three_Sum_zero($nums1));
print_r(three_Sum_zero($nums2));
?>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.14 Create an index array with value red, green, orange, blue, pink, white and
black, Count the total array and display all values of array using for loop.
Source Code-
<html>
<head> <title>ARRAYS</title>
</head>
<body>
<?php
$count = 0;
$arr = array("red", "green", "orange", "blue", "pink", "white"
, "black");
foreach($arr as $val) {
$count++;
echo "The number is: $val <br>"; }
echo "<br>";
echo "Number of Elements:$count";
?>
</body> </html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.15 Create an Associative array with value fruits, veggie, dry-fruits and Count
the total array and display all values of array using for each loop.
Source Code-
<html>
<head>
<title>assossciative array with fruits</title>
</head>
<body>
<?php
$count = 0;
$arr = array("fruits" => "1", "veggies" => "2", "dryfruits" =>
"3");
foreach($arr as $val => $arr1) {
$count++;
echo "" . $val ." :".$arr1. "<br/>"; }
echo "<br>";
echo "Number of Elements:$count";
?>
</body>
</html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.16 Create an Multidimensional Array and Display the array with index and
values using <pre> tag.
Source Code-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
/* Multidimensional 2D array for 4 books and each book having a different array containing
book name, cost and type. */
$books = array(
array("Fiction ", "Action and Adventure ", 800),
array("Fiction ", "Anthology ", 1000),
array("Non- Fiction ", "Biography ", 600),
array("Non- Fiction ", "Cook Book ", 900)
);
echo '<pre>',print_r($books,1),'</pre>';

echo "<br>";

?>
</body>
</html>
AASHUTOSH RAJPUT WBP LAB 00121102020

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.17 Write a PHP script to sort the following associative array :


array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=
>"40") in
a) ascending order sort by value
b) ascending order sort by Key
c) descending order sorting by Value
d) descending order sorting by Key

Source Code-
<?php
echo "Ascending order sort by value";

$arr2=array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40");
echo"<br>";
asort($arr2);
foreach($arr2 as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}

echo "<br>";
echo "Ascending order sort by Key";
echo"<br>";
ksort($arr2);
foreach($arr2 as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
echo"<br>";
echo "descending order sorting by Value";
echo"<br>";
arsort($arr2);
foreach($arr2 as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
echo"<br>";
echo "descending order sorting by Key";
echo"<br>";
krsort($arr2);
foreach($arr2 as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
AASHUTOSH RAJPUT WBP LAB 00121102020

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.18 WAP to swap two values (call by reference) using function.


Source Code-
<?php

function swap(&$x, &$y) {


$temp = $x;
$x = $y;
$y = $temp;
echo "The value of x is: ".$x."<br>";
echo "The value of y is: ".$y."<br><br>";
}

$a = 10;
$b = 20;
swap($a, $b);
echo "The value of a is: ".$a."<br>";
echo "The value of b is: ".$b."<br>";

?>
Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.19 WAP to create a PHP form according to the given format.

Source Code-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $ageErr = "";
$name = $age= "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter your full Name: <input type="text" name="name" value="<?php echo $name;?>">
AASHUTOSH RAJPUT WBP LAB 00121102020

<span class="error">* <?php echo $nameErr;?></span>


<br><br>
Enter Your Age:<input type="number" name="age" value="<?php echo $age;?>">
<span class="error">* <?php echo $ageErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $age;
?>
</body>
</html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.20 Design a form given below with validation and error message in PHP.

Source Code-
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
AASHUTOSH RAJPUT WBP LAB 00121102020

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
AASHUTOSH RAJPUT WBP LAB 00121102020

<span class="error">* <?php echo $nameErr;?></span>


<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo
$comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo
"checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo
"checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo
"checked";?> value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>
AASHUTOSH RAJPUT WBP LAB 00121102020

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.21 Write a PHP Script to demonstrate the file handling in php


(fopen,fclose,fread,fwrite,file length).

Source Code-
<?php
$myfile = fopen("text.txt", "a+") or die("Unable to open file!");
echo fread($myfile,filesize("text.txt"));
$filesize = filesize("text.txt");
$txt = "Suman Mam\n";
fwrite($myfile, $txt);
echo fread($myfile,filesize("text.txt"));
echo $filesize;
fclose($myfile);
?>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.22 Write a program to upload a file.


Source Code-
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.23 Write a program to store the current date and time in a cookie and display
the last visited date and time on the web page.
Source Code-
<html>
<body bgcolor="87ceeb">
<center><h2> Last visited time on the web page</h2></center>
<br>
<?php
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
if(isset($_COOKIE['lastVisit']))

{
$visit = $_COOKIE['lastVisit'];
echo "Your last visit was - ". $visit;
}
else
echo "You've got some stale cookies!";
?>
</body>
</html>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.24 Write a program to store page views counting session to increment the
count on each refresh and to show the count on the page.
Source Code-
<?php

session_start();

if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+1;
else
$_SESSION['views']=1;

echo"views = ".$_SESSION['views'];

?>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.25 Write and explain the steps to create a database, table, select query using
PhpMyadmin.
1 Creating a Database

2 Creating Table
AASHUTOSH RAJPUT WBP LAB 00121102020
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.26 Write a PHP program to


 create a connection,
 create a database and
 create a table
Source Code-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else
echo "connection established<br>";

$sql = "CREATE DATABASE testdb";


if ($conn->query($sql) === TRUE) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . $conn->error;
}
$dbname="testdb";
$con = new mysqli($servername, $username, $password,$dbname);
$sql = "CREATE TABLE test (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstnameVARCHAR(30) NOT NULL,
lastnameVARCHAR(30) NOT NULL,
email VARCHAR(50)
)";
if ($con->query($sql) === TRUE) {
AASHUTOSH RAJPUT WBP LAB 00121102020

echo "Table test created successfully<br>";


} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>

Output-
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.27 Write a PHP program for sending and receiving plain text message (e -
mail).
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.28 Write a PHP program to insert record into a table.


<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

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

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

$sql="insert into record values('kshitiz','[email protected]')";


if(mysqli_query($conn,$sql))
{
echo "Records inserted:<br>";
}
$fetch = "select * from record";
$result = mysqli_query($conn, $fetch);
while ($row = mysqli_fetch_assoc($result)) {
echo"name: ".$row['name']." ,Email: ".$row['email']."<br>";
}
?>
Output:
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.29 Write a PHP program to select data and show into table format.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

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

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

$fetch = "select * from record";


$result = mysqli_query($conn, $fetch);
echo"<table border='3'>";
echo"<tr><td>Name</td><td>Email</td></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo"<tr><td>".$row['name']."</td><td>".$row['email']."</td></tr>";
}
echo"</table>";
?>
AASHUTOSH RAJPUT WBP LAB 00121102020

Output:
AASHUTOSH RAJPUT WBP LAB 00121102020

Q.30 Create a student Registration in PHP and Save and Display the student
Records.

Source Code-
<html>
<head>
<title>Student Registration Form</title>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"
integrity="sha384-
oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-
mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD"
crossorigin="anonymous"></script>
<style type="text/css">
body{
background-color: #800000;
color: white;
}
.form-control{
AASHUTOSH RAJPUT WBP LAB 00121102020

margin-left: 50px;
}
</style>
</head>
<body>
<div class="container">
<center><h1>Student Registration Form</h1></center>
<form class="form-control" action="connection.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" required><br><br>
<label for="dob">D.O.B:</label>
<input type="date" name="dob" required><br><br>
<label for="sex">Sex:</label>
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female">Female<br><br>
<label for="email">Email:</label>
<input type="email" name="email" required><br><br>
<label for="address">Address:</label>
<input type="text" name="address" required><br><br>
<label for="school">School:</label>
<select name="school" required>
<option value="ABCSchool">ABC School</option>
<option value="DEFSchool">DEF School</option>
<option value="GHISchool">GHI School</option>
</select><br><br>
<label for="department">Department:</label>
<select name="department" required>
<option value="ABCdpt">ABC Department</option>
AASHUTOSH RAJPUT WBP LAB 00121102020

<option value="DEFdpt">DEF Department</option>


<option value="GHIdpt">GHI Department</option>
</select><br><br>
<label for="course">Courses:</label>
<select name="course" required>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="BCom">B.Com</option>
</select><br><br>
<label for="mobile">Mobil No</label>
<input type="text" name="mobile" required><br><br>
<input type="submit" name="reset" value="Reset">
<input type="submit" name="sumbit" value="Submit">
</form>
</div>
</body>
</html>
AASHUTOSH RAJPUT WBP LAB 00121102020

Output-

You might also like