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

PHP HTML Experiments

The document outlines a series of experiments focused on web development using HTML, CSS, and PHP. Each experiment includes an aim, objectives, theoretical background, code examples, execution steps, and questions for further understanding. Key topics covered include form handling, arrays, functions, CSS styling, the box model, and element positioning.
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)
6 views

PHP HTML Experiments

The document outlines a series of experiments focused on web development using HTML, CSS, and PHP. Each experiment includes an aim, objectives, theoretical background, code examples, execution steps, and questions for further understanding. Key topics covered include form handling, arrays, functions, CSS styling, the box model, and element positioning.
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/ 27

Sr. No.

Name of Experiments
To create a web form that collects user input (name,
1 email, and age) and displays the submitted data using
PHP.
To create a PHP script that stores a list of numbers in an
2
array, calculates their sum, and displays the result.
To create a PHP script that uses a function to check if a
3
number is even or odd and displays the result.
To create a webpage with styled text and a background
4
color/image.
To demonstrate the CSS box model using margins,
5
padding, and borders.
To demonstrate CSS positioning
6
using relative and absolute positioning.
7 To create a database and a table using PHP and MySQL.
To insert data into a table and retrieve it using PHP and
8
MySQL.
To delete data from a table and drop the table using
9
PHP and MySQL.
10 To update existing data in a table using PHP and MySQL.
Experiment 1: Form Handling with PHP
Aim To create a web form that collects user input (name, email, and age) and displays the
submitted data using PHP.
Objective
 Learn how to create an HTML form.
 Understand how to handle form data using PHP.
 Display the submitted data on the webpage.
Theory
 HTML forms are used to collect user input.
 PHP can process form data using the $_POST or $_GET superglobal arrays.
 The form's method attribute determines how data is sent (POST or GET).
Code
HTML Form (form.html):
<!DOCTYPE html>
<html>
<head>
<title>User Form</title>
</head>
<body>
<h2>Enter Your Details</h2>
<form action="process.php" method="POST">
Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
Age: <input type="number" name="age"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Script (process.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];

echo "<h2>Submitted Data:</h2>";


echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
echo "Age: " . $age . "<br>";
}
?>
Steps to Execute
1. Save the HTML code in a file named form.html.
2. Save the PHP code in a file named process.php.
3. Place both files in the root directory of your web server (e.g., htdocs for XAMPP).
4. Open a browser and navigate to http://localhost/form.html.
5. Fill in the form and click "Submit".
6. The submitted data will be displayed on the process.php page.
Result
 The form will collect the user's name, email, and age.
 After submission, the data will be displayed on the process.php page.

Questions:
1. What is the purpose of the $_POST superglobal in PHP, and how is it used to collect
form data?
2. Explain the difference between the GET and POST methods for form submission in
PHP. Which method is more secure for collecting sensitive data like email and age,
and why?
3. Write the HTML code to create a form with three input fields: name, email, and age.
The form should submit data to a PHP script using the POST method.
4. Write the PHP code to display the user-submitted name, email, and age on the same
page after the form is submitted.
5. How would you validate the form input in PHP to ensure that the name is not empty,
the email is in a valid format, and the age is a numeric value? Write the PHP code to
implement these validations.
Experiment 2: Working with Arrays and Loops
Aim To create a PHP script that stores a list of numbers in an array, calculates their sum,
and displays the result.
Objective
 Learn how to declare and use arrays in PHP.
 Understand how to use loops to iterate through arrays.
 Perform arithmetic operations on array elements.
Theory
 Arrays are used to store multiple values in a single variable.
 Loops (e.g., for, foreach) are used to iterate through arrays.
 Arithmetic operations can be performed on array elements.
Code
<?php
// Declare an array of numbers
$numbers = array(10, 20, 30, 40, 50);
// Initialize sum variable
$sum = 0;
// Use a foreach loop to calculate the sum
foreach ($numbers as $number) {
$sum += $number;
}
// Display the result
echo "The sum of the numbers is: " . $sum;
?>
Steps to Execute
1. Save the PHP code in a file named array_sum.php.
2. Place the file in the root directory of your web server.
3. Open a browser and navigate to http://localhost/array_sum.php.
4. The script will execute and display the sum of the numbers.
Result
 The script will output: The sum of the numbers is: 150.

Questions:

1. What is an array in PHP, and how does it help in storing and manipulating a list of
numbers?
2. Explain how the array_sum() function works in PHP. How does it simplify the process
of calculating the sum of array elements?
3. Write a PHP script that creates an array of five numbers and calculates the sum of
these numbers using a loop (without using array_sum()).
4. Write a PHP script that creates an array of numbers and uses the array_sum()
function to calculate and display the sum of the numbers.
5. How would you modify the PHP script to handle an array of numbers input by a user
through a form (using the POST method), calculate their sum, and display the result?
Write the PHP code to implement this.
Experiment 3: Using Functions and Control Structures
Aim To create a PHP script that uses a function to check if a number is even or odd and
displays the result.
Objective
 Learn how to define and use functions in PHP.
 Understand how to use control structures (e.g., if...else) in functions.
 Display the result based on the function's logic.
Theory
 Functions are reusable blocks of code that perform specific tasks.
 Control structures like if...else are used to make decisions in code.
 The modulus operator (%) is used to check if a number is even or odd.
Code
<?php
// Function to check if a number is even or odd
function checkEvenOdd($number) {
if ($number % 2 == 0) {
return "Even";
} else {
return "Odd";
}
}
// Test the function
$number = 7;
$result = checkEvenOdd($number);
// Display the result
echo "The number " . $number . " is " . $result;
?>
Steps to Execute
1. Save the PHP code in a file named even_odd.php.
2. Place the file in the root directory of your web server.
3. Open a browser and navigate to http://localhost/even_odd.php.
4. The script will execute and display whether the number is even or odd.
Result:
The PHP script correctly identifies and displays whether the number is "Even" or "Odd"
based on the input; for example, with the input 7, it displays "The number 7 is Odd", and
with 8, it displays "The number 8 is Even."

Questions:

1. What is the purpose of functions in PHP, and how do they help in organizing code
efficiently?
2. Explain the modulus operator (%) in PHP. How can it be used to determine if a
number is even or odd?
3. Write a PHP function that takes a number as input and returns whether it is "Even" or
"Odd". Then, call this function with a sample number and display the result.
4. Write a PHP script that prompts the user to input a number through a form, passes
the number to a function, and displays whether the number is even or odd.
5. How would you modify the PHP script to validate that the input is a valid integer
before checking if it is even or odd? Write the PHP code for input validation and
checking the number.
Experiment 4: Styling Text and Background
Aim To create a webpage with styled text and a background color/image.
Objective
 Learn how to apply CSS to style text and set background properties.
 Understand the use of internal and external CSS.
Theory
 CSS is used to style HTML elements.
 The color, font-family, font-size, and background-color properties are commonly
used for text and background styling.
Code
HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<title>Styled Text and Background</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to CSS Styling</h1>
<p>This is a paragraph with styled text and background.</p>
</body>
</html>

CSS (styles.css):
body {
background-color: lightblue;
font-family: Arial, sans-serif;
}
h1 {
color: darkblue;
text-align: center;
}
p{
color: green;
font-size: 18px;
background-color: white;
padding: 10px;
border-radius: 5px;
}
Steps to Execute
1. Create a folder named experiment1.
2. Inside the folder, create two files:
o index.html (for HTML code).
o styles.css (for CSS code).
3. Copy the HTML and CSS code into their respective files.
4. Open index.html in a browser.
Result
 The webpage will have:
o A light blue background.
o A centered heading in dark blue.
o A paragraph with green text, white background, and padding.

Questions:

1. What is the difference between using background-color and background-image in


CSS for the webpage background?
2. Explain how the background-size: cover property works in CSS. Why is it used in web
design?
3. Write the HTML and CSS code to create a webpage with a heading styled in a specific
color, and a background color of your choice.
4. Write CSS code to make the text in a paragraph have a shadow effect and change
color when hovered over.
5. How can you apply a background image to a webpage in CSS? Provide an example
using a URL or local image.
Experiment 5: Box Model (Margin, Padding, Border)
Aim To demonstrate the CSS box model using margins, padding, and borders.
Objective
 Understand the concept of the box model.
 Learn how to use margin, padding, and border properties.
Theory
 The box model consists of:
o Content: The actual content (text, image, etc.).
o Padding: Space between content and border.
o Border: A line around the padding.
o Margin: Space outside the border.
Code
HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<title>Box Model</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="box">This is a box with margin, padding, and border.</div>
</body>
</html>
CSS (styles.css):
.box {
width: 300px;
height: 150px;
background-color: lightgreen;
padding: 20px;
border: 5px solid darkgreen;
margin: 30px;
text-align: center;
line-height: 150px;
}
Steps to Execute
1. Create a folder named experiment2.
2. Inside the folder, create two files:
o index.html (for HTML code).
o styles.css (for CSS code).
3. Copy the HTML and CSS code into their respective files.
4. Open index.html in a browser.
Result
 A green box will appear with:
o 20px padding inside the border.
o A 5px dark green border.
o 30px margin outside the border.
o Centered text inside the box.

Questions:

1. What is the CSS box model, and how do the components (content, padding, border,
and margin) affect the overall size of an element?
2. How do padding and margin differ in the CSS box model, and when should each be
used?
3. Write the CSS code to create a box with a width of 200px, padding of 15px, a border
of 3px solid red, and a margin of 25px. What will be the total width of the box
including margin, padding, and border?
4. How can you adjust the box model to include the border and padding within the
element's defined width using the box-sizing property? Write the CSS code to
implement this.
5. Write a CSS rule to create a box that has a background color, padding of 20px, and a
border radius of 10px. What effect does the border-radius have on the appearance of
the box?
Experiment 6: Positioning Elements
Aim To demonstrate CSS positioning using relative and absolute positioning.
Objective
 Learn how to position elements using CSS.
 Understand the difference between relative and absolute positioning.
Theory
 Relative Positioning: Positions an element relative to its normal position.
 Absolute Positioning: Positions an element relative to its nearest positioned ancestor
(or the document if none exists).
Code
HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<title>Positioning Elements</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="box1">Box 1 (Relative)</div>
<div class="box2">Box 2 (Absolute)</div>
</div>
</body>
</html>
CSS (styles.css):
.container {
position: relative;
width: 400px;
height: 200px;
background-color: lightgray;
margin: 50px auto;
}

.box1 {
position: relative;
top: 20px;
left: 30px;
width: 100px;
height: 50px;
background-color: lightblue;
text-align: center;
line-height: 50px;
}

.box2 {
position: absolute;
top: 50px;
right: 20px;
width: 100px;
height: 50px;
background-color: lightcoral;
text-align: center;
line-height: 50px;
}
Steps to Execute
1. Create a folder named experiment3.
2. Inside the folder, create two files:
o index.html (for HTML code).
o styles.css (for CSS code).
3. Copy the HTML and CSS code into their respective files.
4. Open index.html in a browser.
Result
 A light gray container will appear with:
o A light blue box positioned 20px from the top and 30px from the left (relative
to its normal position).
o A light coral box positioned 50px from the top and 20px from the right (relative
to the container).

Questions:

1. What is the difference between relative and absolute positioning in CSS?


2. When using absolute positioning, what does the element’s position depend on if
there is no explicitly positioned ancestor element?
3. How does the position: relative; property affect the layout of an element and its
surrounding elements?
4. Write CSS code to position an element 20px from the top and 50px from the right of
its parent container using absolute positioning.
5. How would you use relative positioning to move an element 40px down from its
normal position while keeping it in the document flow? Write the CSS code to
implement this.
6. In the context of CSS positioning, how would you ensure that a child element with
position: absolute; is positioned relative to its parent container and not the whole
document? Provide a code example.
Experiment 7: Creating a Database and Table
Aim To create a database and a table using PHP and MySQL.
Objective
 Learn how to connect to a MySQL server.
 Create a database and a table using PHP.
Theory
 A database is a collection of structured data.
 A table is a set of rows and columns used to store data.
 PHP uses SQL commands to interact with MySQL.
Code
<?php
// Step 1: Connect to MySQL server
$servername = "localhost";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br>";
// Step 2: Create a database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
// Step 3: Select the database
mysqli_select_db($conn, "myDB");
// Step 4: Create a table
$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
Steps to Execute
1. Install XAMPP/WAMP/MAMP and start Apache and MySQL.
2. Open a text editor (e.g., Notepad, VS Code) and paste the code.
3. Save the file as create_db_table.php in the htdocs folder (e.g., C:\xampp\htdocs).
4. Open your browser and go to http://localhost/create_db_table.php.
5. Observe the output.
Result
 The script will:
1. Connect to the MySQL server.
2. Create a database named myDB.
3. Create a table named users with columns: id, username, email, and reg_date.

Questions:

1. What is the purpose of using MySQL with PHP in web development, and how do they
work together to manage dynamic data?
2. Explain the role of the mysqli_connect() function in PHP when interacting with a
MySQL database. What is the importance of establishing a connection before
performing queries?
3. Write PHP code to create a MySQL database called test_db using mysqli in PHP.
4. Write PHP code to create a table called users in the test_db database with the
following fields: id, name, and email.
5. Write PHP code to insert a record into the users table with values for name and
email, and then retrieve and display all the records from the users table
Experiment 8: Inserting and Retrieving Data
Aim To insert data into a table and retrieve it using PHP and MySQL.
Objective
 Learn how to insert data into a table.
 Retrieve and display data from a table.
Theory
 Use the INSERT INTO SQL command to add data.
 Use the SELECT SQL command to retrieve data.
Code
<?php
// Step 1: Connect to MySQL server and select database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br>";
// Step 2: Insert data into the table
$sql = "INSERT INTO users (username, email)
VALUES ('JohnDoe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "Data inserted successfully<br>";
} else {
echo "Error inserting data: " . mysqli_error($conn);
}
// Step 3: Retrieve and display data
$sql = "SELECT id, username, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['id'] . " - Username: " . $row['username'] . " - Email: " . $row['email'] .
"<br>";
}
} else {
echo "No results found";
}
// Close connection
mysqli_close($conn);
?>
Steps to Execute
1. Save the code as insert_retrieve_data.php in the htdocs folder.
2. Open your browser and go to http://localhost/insert_retrieve_data.php.
3. Observe the output.
Result
 The script will:
1. Insert a new row into the users table.
2. Retrieve and display all rows from the users table.

Questions:

1. How does the INSERT INTO SQL statement work in MySQL when inserting data into a
table, and why is it important to sanitize user inputs in PHP before executing such
statements?
2. Explain the role of the mysqli_query() function in PHP when executing SQL queries.
What are the potential risks of using it without prepared statements or data
sanitization?
3. Write PHP code to insert a record into the users table (created in the previous
example) with values for name and email.
4. Write PHP code to retrieve all records from the users table and display them in an
HTML table format.
5. Write PHP code to retrieve a specific record (e.g., by id) from the users table and
display it.
Experiment 9: Deleting Data and Dropping a Table
Aim To delete data from a table and drop the table using PHP and MySQL.
Objective
 Learn how to delete specific rows from a table.
 Drop a table from the database.
Theory
 Use the DELETE SQL command to remove rows.
 Use the DROP TABLE SQL command to delete a table.
Code
<?php
// Step 1: Connect to MySQL server and select database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br>";
// Step 2: Delete a specific row
$sql = "DELETE FROM users WHERE id = 1";
if (mysqli_query($conn, $sql)) {
echo "Data deleted successfully<br>";
} else {
echo "Error deleting data: " . mysqli_error($conn);
}
// Step 3: Drop the table
$sql = "DROP TABLE users";
if (mysqli_query($conn, $sql)) {
echo "Table dropped successfully";
} else {
echo "Error dropping table: " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
Steps to Execute
1. Save the code as delete_drop_table.php in the htdocs folder.
2. Open your browser and go to http://localhost/delete_drop_table.php.
3. Observe the output.
Result
 The script will:
1. Delete the row with id = 1 from the users table.
2. Drop the users table from the myDB database.

Questions:

1. What is the difference between the DELETE and DROP SQL statements in MySQL?
When should each be used in a PHP script?
2. Why is it important to use prepared statements or escape user input when deleting
or dropping tables in MySQL with PHP?
3. Write PHP code to delete a record from the users table where the id is a specific
value (e.g., id = 5).
4. Write PHP code to delete all records from the users table without deleting the table
structure.
5. Write PHP code to drop the entire users table from the test_db database using
MySQL in PHP.
Experiment 10: Updating Data in a Table
Aim To update existing data in a table using PHP and MySQL.
Objective
 Learn how to update specific rows in a table.
 Understand the use of the UPDATE SQL command.
Theory
 The UPDATE SQL command is used to modify existing data in a table.
 The WHERE clause specifies which rows to update. Without it, all rows will be
updated.
Code
<?php
// Step 1: Connect to MySQL server and select database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br>";
// Step 2: Insert sample data (if not already inserted)
$sql = "INSERT INTO users (username, email)
VALUES ('JohnDoe', '[email protected]')";
mysqli_query($conn, $sql);
// Step 3: Update data in the table
$sql = "UPDATE users SET email='[email protected]' WHERE username='JohnDoe'";
if (mysqli_query($conn, $sql)) {
echo "Data updated successfully<br>";
} else {
echo "Error updating data: " . mysqli_error($conn);
}
// Step 4: Retrieve and display updated data
$sql = "SELECT id, username, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['id'] . " - Username: " . $row['username'] . " - Email: " . $row['email'] .
"<br>";
}
} else {
echo "No results found";
}
// Close connection
mysqli_close($conn);
?>
Steps to Execute
1. Save the code as update_data.php in the htdocs folder.
2. Open your browser and go to http://localhost/update_data.php.
3. Observe the output.
Result
 The script will:
1. Insert a sample row into the users table (if not already inserted).
2. Update the email of the user with the username JohnDoe.
3. Retrieve and display the updated data from the users table.

Questions:
1. What is the UPDATE SQL statement used for in MySQL, and how does it allow
modification of existing data in a table?
2. Why is it important to use prepared statements or data sanitization when updating
records in a MySQL database via PHP, and what security risks exist without these
practices?
3. Write PHP code to update the email field of a user in the users table where the id is
1.
4. Write PHP code to update the name and email fields for a user in the users table
based on a specific id.
5. Write PHP code to update multiple records in the users table by changing the name
field for users who share the same email.

You might also like