0% found this document useful (0 votes)
6 views39 pages

PHP Basics: Scripts and Authentication

Uploaded by

dhruvnarayan8069
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 views39 pages

PHP Basics: Scripts and Authentication

Uploaded by

dhruvnarayan8069
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

Experiment 1: Create a Simple PHP Script that Echoes "Hello, World!

"
to the Browser

Objective:

To create a basic PHP script that outputs the message "Hello, World!" in a web browser.
This experiment serves as an introduction to PHP and basic server-side scripting.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
2. Create the PHP File:
a. Open your text editor and create a new file.
b. Write the following PHP code:

<?php
echo "Hello, World!";
?>

c. Save the file with a .php extension. For this experiment, name the file
[Link].
3. Save the File to the Web Server Directory:
a. Locate the root directory of your web server:
i. For XAMPP, this is typically C:\xampp\htdocs\.
ii. For WAMP, this is usually C:\wamp64\www\.
iii. For MAMP, this is generally Applications/MAMP/htdocs/.
b. Save the [Link] file in this directory.
4. Run the PHP Script:
a. Open your web browser.
b. Navigate to [Link]
5. Observe the Output:
a. The browser should display the text: Hello, World!
Expected Output:

When the steps are followed correctly, the web browser will display the message
"Hello, World!" indicating that the PHP script has been executed successfully on the
server side and the result has been sent to the browser.
Experiment 2: Build a Basic Web-Based Calculator

Objective:

To create a web-based calculator that performs basic arithmetic operations (addition,


subtraction, multiplication, and division) based on user input. This experiment helps
understand the integration of HTML and PHP for creating interactive web applications.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
2. Create the HTML Form:
a. Open your text editor and create a new file named [Link].
b. Add the following HTML code to create a form for user input:

<html>
<head>
<title>Basic Calculator</title>
</head>
<body>
<form method="POST" action="[Link]">
Enter First Number: <input type="number" name="num1"
required><br>
Enter Second Number: <input type="number" name="num2"
required><br>
Select Operation:
<select name="operation">
<option value="add">Add</option>
<option value="sub">Subtract</option>
<option value="mul">Multiply</option>
<option value="div">Divide</option>
</select><br>
<button type="submit">Calculate</button>
</form>
</body>
</html>

c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
3. Create the PHP Script:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to process the form data and perform
calculations:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operation = $_POST['operation'];

switch ($operation) {
case "add":
$result = $num1 + $num2;
break;
case "sub":
$result = $num1 - $num2;
break;
case "mul":
$result = $num1 * $num2;
break;
case "div":
if ($num2 != 0) {
$result = $num1 / $num2;
} else {
echo "Cannot divide by zero!";
exit;
}
break;
default:
echo "Invalid operation selected.";
exit;
}

echo "Result: " . $result;


}
?>
c. Save the file in the web server directory.
4. Run the Calculator:
a. Open your web browser.
b. Navigate to [Link]
5. Use the Calculator:
a. Enter two numbers in the input fields.
b. Select an arithmetic operation (addition, subtraction, multiplication, or
division) from the dropdown menu.
c. Click the "Calculate" button.
6. Observe the Output:
a. The result of the arithmetic operation will be displayed on the screen.

Expected Output:

When the steps are followed correctly, the web-based calculator will display the result
of the arithmetic operation selected by the user.
Experiment 3: Create a User Authentication System

Objective:

To build a secure user authentication system that allows users to log in and log out. This
experiment will involve creating a login form, validating user credentials, and
maintaining a logged-in state using sessions.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).
3. A database (such as MySQL) to store user credentials.

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
b. Create a database and a table to store user credentials. For this
experiment, we will use MySQL.
2. Create the Database and Table:
a. Open your database management tool (like phpMyAdmin) and create a
database named auth_system.
b. Create a table named users with the following columns:

sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);

3. Insert Sample User Data:


a. Insert a sample user into the users table:

sql
INSERT INTO users (username, password) VALUES ('admin',
PASSWORD('12345'));

4. Create the Login Form:


a. Open your text editor and create a new file named [Link].
b. Add the following HTML code to create a login form:

<html>
<head>
<title>Login</title>
</head>
<body>
<form method="POST" action="[Link]">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password"
required><br>
<button type="submit">Login</button>
</form>
</body>
</html>

c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
5. Create the Login Script:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle login requests:

<?php
session_start();
$conn = new mysqli('localhost', 'root', '', 'auth_system');

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE username = '$username'";


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

if ($result->num_rows > 0) {
$user = $result->fetch_assoc();
if (password_verify($password, $user['password'])) {
$_SESSION['username'] = $username;
header("Location: [Link]");
} else {
echo "Invalid password.";
}
} else {
echo "No user found with that username.";
}
}
$conn->close();
?>

6. Create the Welcome Page:


a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to display a welcome message to logged-in
users:

php
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: [Link]");
exit();
}
?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<a href="[Link]">Logout</a>
</body>
</html>

7. Create the Logout Script:


a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle logout requests:

php
<?php
session_start();
session_unset();
session_destroy();
header("Location: [Link]");
exit();
?>

8. Test the Authentication System:


a. Open your web browser.
b. Navigate to [Link]
c. Enter the sample user credentials (admin / 12345) and click the "Login"
button.
d. Upon successful login, you should be redirected to the welcome page.
e. Click the "Logout" link to test the logout functionality.

Expected Output:

When the steps are followed correctly, the user authentication system will allow users
to log in and log out securely. Upon successful login, users will be redirected to a
welcome page, and upon logging out, they will be redirected back to the login page.
Experiment 4: Build a To-Do List Application

Objective:

To create a web-based to-do list application that allows users to add, edit, and delete
tasks. This experiment will involve creating a user interface for task management and
implementing server-side logic to handle these operations.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).
3. A database (such as MySQL) to store tasks.

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
b. Create a database and a table to store tasks. For this experiment, we will
use MySQL.
2. Create the Database and Table:
a. Open your database management tool (like phpMyAdmin) and create a
database named todo_app.
b. Create a table named tasks with the following columns:

sql
CREATE TABLE tasks (
id INT AUTO_INCREMENT PRIMARY KEY,
task VARCHAR(255) NOT NULL,
status VARCHAR(10) NOT NULL DEFAULT 'pending'
);

3. Create the HTML Form:


a. Open your text editor and create a new file named [Link].
b. Add the following HTML code to create a form for adding tasks and a list
to display them:

html
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form method="POST" action="add_task.php">
<input type="text" name="task" required placeholder="New
Task">
<button type="submit">Add Task</button>
</form>
<ul id="taskList">
<?php
$conn = new mysqli('localhost', 'root', '', 'todo_app');
$result = $conn->query("SELECT * FROM tasks");
while ($row = $result->fetch_assoc()) {
echo "<li>{$row['task']} <a
href='edit_task.php?id={$row['id']}'>Edit</a> <a
href='delete_task.php?id={$row['id']}'>Delete</a></li>";
}
$conn->close();
?>
</ul>
</body>
</html>

c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
4. Create the PHP Script for Adding Tasks:
a. Open your text editor and create a new file named add_task.php.
b. Add the following PHP code to handle adding tasks:

php
<?php
$task = $_POST['task'];
$conn = new mysqli('localhost', 'root', '', 'todo_app');

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

$sql = "INSERT INTO tasks (task) VALUES ('$task')";


if ($conn->query($sql) === TRUE) {
header("Location: [Link]");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

c. Save the file in the web server directory.


5. Create the PHP Script for Editing Tasks:
a. Open your text editor and create a new file named edit_task.php.
b. Add the following PHP code to handle editing tasks:

php
<?php
$id = $_GET['id'];
$conn = new mysqli('localhost', 'root', '', 'todo_app');

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$task = $_POST['task'];
$sql = "UPDATE tasks SET task='$task' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
header("Location: [Link]");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
$result = $conn->query("SELECT * FROM tasks WHERE id=$id");
$row = $result->fetch_assoc();
echo "<form method='POST'>
<input type='text' name='task' value='{$row['task']}'
required>
<button type='submit'>Update Task</button>
</form>";
}

$conn->close();
?>

c. Save the file in the web server directory.


6. Create the PHP Script for Deleting Tasks:
a. Open your text editor and create a new file named delete_task.php.
b. Add the following PHP code to handle deleting tasks:

php
<?php
$id = $_GET['id'];
$conn = new mysqli('localhost', 'root', '', 'todo_app');

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

$sql = "DELETE FROM tasks WHERE id=$id";


if ($conn->query($sql) === TRUE) {
header("Location: [Link]");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

c. Save the file in the web server directory.


7. Run the To-Do List Application:
a. Open your web browser.
b. Navigate to [Link]
8. Use the To-Do List Application:
a. Add tasks by entering the task description in the input field and clicking
the "Add Task" button.
b. Edit tasks by clicking the "Edit" link next to a task.
c. Delete tasks by clicking the "Delete" link next to a task.

Expected Output:

When the steps are followed correctly, the to-do list application will allow users to add,
edit, and delete tasks. The tasks will be displayed in a list format with options to edit or
delete each task.
Experiment 5: Design a Contact Form that Sends User Messages via
Email

Objective:

To create a contact form that allows users to send messages via email when submitted.
This experiment involves designing the form, implementing server-side validation to
ensure data integrity, and sending the email using PHP.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).
3. An email server (such as your local SMTP server or an external email service like
Gmail).

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
2. Create the HTML Form:
a. Open your text editor and create a new file named [Link].
b. Add the following HTML code to create the contact form:

html
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="POST" action="send_email.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="message">Message:</label>
<textarea id="message" name="message"
required></textarea><br>
<button type="submit">Send</button>
</form>
</body>
</html>

c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
3. Create the PHP Script for Handling Form Submission:
a. Open your text editor and create a new file named send_email.php.
b. Add the following PHP code to handle the form submission and send the
email:

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate input fields
$name = filter_input(INPUT_POST, 'name',
FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email',
FILTER_VALIDATE_EMAIL);
$message = filter_input(INPUT_POST, 'message',
FILTER_SANITIZE_STRING);

if ($name && $email && $message) {


$to = 'your-email@[Link]'; // Replace with your email
address
$subject = 'New Contact Form Message';
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$email_body = "Name: $name\nEmail:
$email\n\nMessage:\n$message";

// Send the email


if (mail($to, $subject, $email_body, $headers)) {
echo "Message sent successfully!";
} else {
echo "Failed to send message.";
}
} else {
echo "Invalid input. Please check your form fields.";
}
} else {
echo "Invalid request method.";
}
?>

c. Save the file in the web server directory.


4. Test the Contact Form:
a. Open your web browser.
b. Navigate to [Link]
c. Fill in the contact form with your details and a message.
d. Click the "Send" button.
5. Observe the Output:
a. If the form submission is successful and the email is sent, you will see a
success message.
b. If there are any validation errors, appropriate error messages will be
displayed.

Expected Output:

When the steps are followed correctly, the contact form will validate the input fields
and send the user's message via email. The user will receive feedback on whether the
message was sent successfully or if there were any errors.
Experiment 6: Build an Online Quiz System with Multiple-Choice
Questions

Objective:

To create an online quiz system that presents multiple-choice questions, collects user
responses, and keeps track of the user's score. This experiment involves creating an
interactive web interface, storing questions and user responses, and calculating the
final score.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).
3. A database (such as MySQL) to store quiz questions and user responses.

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
b. Create a database and a table to store quiz questions. For this
experiment, we will use MySQL.
2. Create the Database and Table:
a. Open your database management tool (like phpMyAdmin) and create a
database named quiz_app.
b. Create a table named questions with the following columns:

sql
CREATE TABLE questions (
id INT AUTO_INCREMENT PRIMARY KEY,
question TEXT NOT NULL,
option1 VARCHAR(255) NOT NULL,
option2 VARCHAR(255) NOT NULL,
option3 VARCHAR(255) NOT NULL,
option4 VARCHAR(255) NOT NULL,
correct_option INT NOT NULL
);

3. Insert Sample Questions:


a. Insert sample multiple-choice questions into the questions table:
sql
INSERT INTO questions (question, option1, option2, option3, option4,
correct_option) VALUES
('What is the capital of France?', 'Berlin', 'London', 'Paris',
'Madrid', 3),
('What is 2 + 2?', '3', '4', '5', '6', 2),
('Which planet is known as the Red Planet?', 'Earth', 'Mars',
'Jupiter', 'Saturn', 2);

4. Create the HTML Form for the Quiz:


a. Open your text editor and create a new file named [Link].
b. Add the following HTML and PHP code to display the quiz questions and
handle user responses:

<?php
$conn = new mysqli('localhost', 'root', '', 'quiz_app');
if ($conn->connect_error) {

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


}

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


?>

<html>
<head>
<title>Online Quiz</title>
</head>
<body>
<h1>Online Quiz</h1>
<form method="POST" action="[Link]">
<?php while ($row = $result->fetch_assoc()) { ?>
<p><?php echo $row['question']; ?></p>
<input type="radio" name="question<?php echo
$row['id']; ?>" value="1"> <?php echo $row['option1']; ?><br>
<input type="radio" name="question<?php echo
$row['id']; ?>" value="2"> <?php echo $row['option2']; ?><br>
<input type="radio" name="question<?php echo
$row['id']; ?>" value="3"> <?php echo $row['option3']; ?><br>
<input type="radio" name="question<?php echo
$row['id']; ?>" value="4"> <?php echo $row['option4']; ?><br>
<?php } ?>
<button type="submit">Submit</button>
</form>
</body>
</html>

<?php
$conn->close();
?>

c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
5. Create the PHP Script to Process Quiz Results:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to process the user responses and calculate
the score:

<?php
$conn = new mysqli('localhost', 'root', '', 'quiz_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$score = 0;
$result = $conn->query("SELECT * FROM questions");

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


$question_id = $row['id'];
$selected_option = $_POST["question$question_id"];

if ($selected_option == $row['correct_option']) {
$score++;
}
}

echo "Your score: $score/" . $result->num_rows;

$conn->close();
?>

c. Save the file in the web server directory.


6. Run the Quiz System:
a. Open your web browser.
b. Navigate to [Link]
7. Take the Quiz:
a. Answer the multiple-choice questions displayed on the quiz page.
b. Click the "Submit" button.
8. Observe the Output:
a. The result page will display your score based on the number of correct
answers.

Expected Output:

When the steps are followed correctly, the online quiz system will display multiple-
choice questions, collect user responses, and calculate the final score based on the
user's answers.
Experiment 7: Develop a User Registration Form that Collects User
Data, Validates It, and Stores It in a Database

Objective:

To create a user registration form that collects user data, validates the input, and stores
the data in a database. This experiment covers designing the form, implementing
server-side validation to ensure data integrity, and inserting the validated data into a
database.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).
3. A database (such as MySQL) to store user information.

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
2. Create the Database and Table:
a. Open your database management tool (like phpMyAdmin) and create a
database named user_registration.
b. Create a table named users with the following columns:

sql
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE
);

3. Create the HTML Form:


a. Open your text editor and create a new file named [Link].
b. Add the following HTML code to create the registration form:

html
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>Register</h1>
<form method="POST" action="[Link]">
<label for="username">Username:</label>
<input type="text" id="username" name="username"
required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"
required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<button type="submit">Register</button>
</form>
</body>
</html>

c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
4. Create the PHP Script for Handling Form Submission:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle the form submission, validate the
input, and store the data in the database:

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = filter_input(INPUT_POST, 'username',
FILTER_SANITIZE_STRING);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = filter_input(INPUT_POST, 'email',
FILTER_VALIDATE_EMAIL);

if ($username && $password && $email) {


$conn = new mysqli('localhost', 'root', '',
'user_registration');

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

$sql = "INSERT INTO users (username, password, email) VALUES


('$username', '$password', '$email')";
if ($conn->query($sql) === TRUE) {
echo "Registration successful!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
} else {
echo "Invalid input. Please check your form fields.";
}
} else {
echo "Invalid request method.";
}
?>

c. Save the file in the web server directory.


5. Test the Registration Form:
a. Open your web browser.
b. Navigate to [Link]
c. Fill in the registration form with a username, password, and email
address.
d. Click the "Register" button.
6. Observe the Output:
a. If the form submission is successful and the data is stored in the
database, you will see a success message.
b. If there are any validation errors, appropriate error messages will be
displayed.

Expected Output:

When the steps are followed correctly, the user registration form will validate the input
fields and store the user's data in the database. The user will receive feedback on
whether the registration was successful or if there were any errors.

Explanation:

 HTML Form: The form collects user input (username, password, and email) and
sends it to the PHP script for processing.
 PHP Script: The script validates the form data, sanitizes the input to prevent
security issues, hashes the password for secure storage, and inserts the data
into the database.
 Server-Side Validation: Ensures that the input fields contain valid data before
storing it in the database.

This experiment demonstrates how to create a user registration form with server-side
validation and data storage using HTML, PHP, and MySQL, providing a foundational
understanding of web form processing, data validation, and secure data handling.
Experiment 8: Create a Website to Perform CRUD Operations on a
Database

Objective:

To develop a web application that allows users to perform Create, Read, Update, and
Delete (CRUD) operations on a database. This experiment includes designing the user
interface, implementing server-side logic to handle these operations, and interacting
with a database.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).
3. A database (such as MySQL) to store and manage data.

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
b. Create a database and a table to store records. For this experiment, we
will use MySQL.
2. Create the Database and Table:
a. Open your database management tool (like phpMyAdmin) and create a
database named crud_app.
b. Create a table named items with the following columns:

sql
CREATE TABLE items (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3. Create the HTML Interface:


a. Open your text editor and create a new file named [Link].
b. Add the following HTML code to create the user interface for managing
items:

html
<html>
<head>
<title>CRUD Application</title>
</head>
<body>
<h1>CRUD Application</h1>
<form method="POST" action="[Link]">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="description">Description:</label>
<textarea id="description" name="description"
required></textarea><br>
<button type="submit">Create</button>
</form>

<h2>Items</h2>
<ul>
<?php
$conn = new mysqli('localhost', 'root', '', 'crud_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

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


while ($row = $result->fetch_assoc()) {
echo "<li>{$row['name']} - {$row['description']} <a
href='[Link]?id={$row['id']}'>Edit</a> <a
href='[Link]?id={$row['id']}'>Delete</a></li>";
}

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

c. Save the file in the web server directory (e.g., htdocs for XAMPP or www
for WAMP).
4. Create the PHP Script for Creating Items:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle creating items:
php
<?php
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$description = filter_input(INPUT_POST, 'description',
FILTER_SANITIZE_STRING);

if ($name && $description) {


$conn = new mysqli('localhost', 'root', '', 'crud_app');

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

$sql = "INSERT INTO items (name, description) VALUES ('$name',


'$description')";
if ($conn->query($sql) === TRUE) {
header("Location: [Link]");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
} else {
echo "Invalid input.";
}
?>

c. Save the file in the web server directory.


5. Create the PHP Script for Editing Items:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle editing items:

php
<?php
$conn = new mysqli('localhost', 'root', '', 'crud_app');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$id = $_POST['id'];
$name = filter_input(INPUT_POST, 'name',
FILTER_SANITIZE_STRING);
$description = filter_input(INPUT_POST, 'description',
FILTER_SANITIZE_STRING);

if ($name && $description) {


$sql = "UPDATE items SET name='$name',
description='$description' WHERE id=$id";
if ($conn->query($sql) === TRUE) {
header("Location: [Link]");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
echo "Invalid input.";
}
} else {
$id = $_GET['id'];
$result = $conn->query("SELECT * FROM items WHERE id=$id");
$row = $result->fetch_assoc();
echo "<form method='POST'>
<input type='hidden' name='id' value='$id'>
<label for='name'>Name:</label>
<input type='text' id='name' name='name'
value='{$row['name']}' required><br>
<label for='description'>Description:</label>
<textarea id='description' name='description'
required>{$row['description']}</textarea><br>
<button type='submit'>Update</button>
</form>";
}

$conn->close();
?>

c. Save the file in the web server directory.


6. Create the PHP Script for Deleting Items:
a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle deleting items:

php
<?php
$id = $_GET['id'];
$conn = new mysqli('localhost', 'root', '', 'crud_app');

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

$sql = "DELETE FROM items WHERE id=$id";


if ($conn->query($sql) === TRUE) {
header("Location: [Link]");
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

c. Save the file in the web server directory.


7. Run the CRUD Application:
a. Open your web browser.
b. Navigate to [Link]
8. Use the CRUD Application:
a. Create new items by entering the item name and description in the input
fields and clicking the "Create" button.
b. Edit items by clicking the "Edit" link next to an item, updating the fields,
and submitting the form.
c. Delete items by clicking the "Delete" link next to an item.

Expected Output:

When the steps are followed correctly, the CRUD application will allow users to create,
read, update, and delete items in the database. The user will be able to manage items
through a web interface.
Experiment 9: Develop a Simple E-Commerce Shopping Cart

Objective:

To create a simple e-commerce shopping cart that allows users to add and remove
products, calculate the total price, and proceed to checkout. This experiment involves
designing the user interface, implementing server-side logic to handle cart operations,
and managing data using a database.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).
3. A database (such as MySQL) to store product information.

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
b. Create a database and a table to store product information. For this
experiment, we will use MySQL.
2. Create the Database and Table:
a. Open your database management tool (like phpMyAdmin) and create a
database named ecommerce.
b. Create a table named products with the following columns:

sql
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description TEXT NOT NULL
);

3. Insert Sample Products:


a. Insert sample products into the products table:

sql
INSERT INTO products (name, price, description) VALUES
('Product 1', 10.00, 'Description for product 1'),
('Product 2', 20.00, 'Description for product 2'),
('Product 3', 30.00, 'Description for product 3');

4. Create the HTML Interface for Displaying Products:


a. Open your text editor and create a new file named [Link].
b. Add the following HTML and PHP code to display the products and handle
cart operations:

php
<?php
session_start();
$conn = new mysqli('localhost', 'root', '', 'ecommerce');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_id = $_POST['product_id'];
if (isset($_POST['add_to_cart'])) {
if (!in_array($product_id, $_SESSION['cart'])) {
$_SESSION['cart'][] = $product_id;
}
} elseif (isset($_POST['remove_from_cart'])) {
if (($key = array_search($product_id,
$_SESSION['cart'])) !== false) {
unset($_SESSION['cart'][$key]);
}
}
}

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


?>

<html>
<head>
<title>E-Commerce Shopping Cart</title>
</head>
<body>
<h1>Products</h1>
<ul>
<?php while ($row = $result->fetch_assoc()) { ?>
<li>
<?php echo $row['name']; ?> - $<?php echo
$row['price']; ?><br>
<?php echo $row['description']; ?><br>
<form method="POST" action="">
<input type="hidden" name="product_id"
value="<?php echo $row['id']; ?>">
<?php if (in_array($row['id'],
$_SESSION['cart'])) { ?>
<button type="submit"
name="remove_from_cart">Remove from Cart</button>
<?php } else { ?>
<button type="submit" name="add_to_cart">Add
to Cart</button>
<?php } ?>
</form>
</li>
<?php } ?>
</ul>

<h2>Shopping Cart</h2>
<ul>
<?php
$total_price = 0;
if (!empty($_SESSION['cart'])) {
$cart_ids = implode(',', $_SESSION['cart']);
$cart_result = $conn->query("SELECT * FROM products
WHERE id IN ($cart_ids)");
while ($cart_row = $cart_result->fetch_assoc()) {
echo "<li>{$cart_row['name']} -
${cart_row['price']}</li>";
$total_price += $cart_row['price'];
}
} else {
echo "<li>Your cart is empty.</li>";
}
?>
</ul>
<p>Total Price: $<?php echo $total_price; ?></p>
<form method="POST" action="[Link]">
<button type="submit" name="checkout">Proceed to
Checkout</button>
</form>
</body>
</html>

<?php
$conn->close();
?>

5. Create the PHP Script for Handling Checkout:


a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle the checkout process:

php
<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST" &&


isset($_POST['checkout'])) {
// In a real application, you would process the payment and
create an order
// For this simple example, we'll just clear the cart and show a
success message
unset($_SESSION['cart']);
echo "Thank you for your purchase!";
} else {
echo "Invalid request.";
}
?>
<br>
<a href="[Link]">Back to Products</a>

6. Run the E-Commerce Shopping Cart Application:


a. Open your web browser.
b. Navigate to [Link]
7. Use the Shopping Cart:
a. Add products to the cart by clicking the "Add to Cart" button.
b. Remove products from the cart by clicking the "Remove from Cart"
button.
c. View the total price of the items in the cart.
d. Proceed to checkout by clicking the "Proceed to Checkout" button.
Expected Output:

When the steps are followed correctly, the e-commerce shopping cart will allow users
to add and remove products, calculate the total price, and proceed to checkout. The
user will receive feedback on the cart operations and the checkout process.
Experiment 10: Develop a Simple E-Commerce Shopping Cart

Objective:

To create a simple e-commerce shopping cart that allows users to add and remove
products, calculate the total price, and proceed to checkout. This experiment involves
designing the user interface, implementing server-side logic to handle cart operations,
and managing data using a database.

Materials:

1. A computer with a web server installed (such as XAMPP, WAMP, or MAMP).


2. A text editor (such as Notepad++, Sublime Text, or Visual Studio Code).
3. A database (such as MySQL) to store product information.

Procedure:

1. Setup the Environment:


a. Ensure that your local web server is installed and running. This could be
XAMPP, WAMP, MAMP, or any other web server software.
b. Create a database and a table to store product information. For this
experiment, we will use MySQL.
2. Create the Database and Table:
a. Open your database management tool (like phpMyAdmin) and create a
database named ecommerce.
b. Create a table named products with the following columns:

sql
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description TEXT NOT NULL
);

3. Insert Sample Products:


a. Insert sample products into the products table:

sql
INSERT INTO products (name, price, description) VALUES
('Product 1', 10.00, 'Description for product 1'),
('Product 2', 20.00, 'Description for product 2'),
('Product 3', 30.00, 'Description for product 3');

4. Create the HTML Interface for Displaying Products:


a. Open your text editor and create a new file named [Link].
b. Add the following HTML and PHP code to display the products and handle
cart operations:

php
<?php
session_start();
$conn = new mysqli('localhost', 'root', '', 'ecommerce');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$product_id = $_POST['product_id'];
if (isset($_POST['add_to_cart'])) {
if (!in_array($product_id, $_SESSION['cart'])) {
$_SESSION['cart'][] = $product_id;
}
} elseif (isset($_POST['remove_from_cart'])) {
if (($key = array_search($product_id,
$_SESSION['cart'])) !== false) {
unset($_SESSION['cart'][$key]);
}
}
}

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


?>

<html>
<head>
<title>E-Commerce Shopping Cart</title>
</head>
<body>
<h1>Products</h1>
<ul>
<?php while ($row = $result->fetch_assoc()) { ?>
<li>
<?php echo $row['name']; ?> - $<?php echo
$row['price']; ?><br>
<?php echo $row['description']; ?><br>
<form method="POST" action="">
<input type="hidden" name="product_id"
value="<?php echo $row['id']; ?>">
<?php if (in_array($row['id'],
$_SESSION['cart'])) { ?>
<button type="submit"
name="remove_from_cart">Remove from Cart</button>
<?php } else { ?>
<button type="submit" name="add_to_cart">Add
to Cart</button>
<?php } ?>
</form>
</li>
<?php } ?>
</ul>

<h2>Shopping Cart</h2>
<ul>
<?php
$total_price = 0;
if (!empty($_SESSION['cart'])) {
$cart_ids = implode(',', $_SESSION['cart']);
$cart_result = $conn->query("SELECT * FROM products
WHERE id IN ($cart_ids)");
while ($cart_row = $cart_result->fetch_assoc()) {
echo "<li>{$cart_row['name']} -
${cart_row['price']}</li>";
$total_price += $cart_row['price'];
}
} else {
echo "<li>Your cart is empty.</li>";
}
?>
</ul>
<p>Total Price: $<?php echo $total_price; ?></p>
<form method="POST" action="[Link]">
<button type="submit" name="checkout">Proceed to
Checkout</button>
</form>
</body>
</html>

<?php
$conn->close();
?>

5. Create the PHP Script for Handling Checkout:


a. Open your text editor and create a new file named [Link].
b. Add the following PHP code to handle the checkout process:

php
<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST" &&


isset($_POST['checkout'])) {
// In a real application, you would process the payment and
create an order
// For this simple example, we'll just clear the cart and show a
success message
unset($_SESSION['cart']);
echo "Thank you for your purchase!";
} else {
echo "Invalid request.";
}
?>
<br>
<a href="[Link]">Back to Products</a>

6. Run the E-Commerce Shopping Cart Application:


a. Open your web browser.
b. Navigate to [Link]
7. Use the Shopping Cart:
a. Add products to the cart by clicking the "Add to Cart" button.
b. Remove products from the cart by clicking the "Remove from Cart"
button.
c. View the total price of the items in the cart.
d. Proceed to checkout by clicking the "Proceed to Checkout" button.
Expected Output:

When the steps are followed correctly, the e-commerce shopping cart will allow users
to add and remove products, calculate the total price, and proceed to checkout. The
user will receive feedback on the cart operations and the checkout process.

You might also like