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

Advanced Web Development

Uploaded by

deepakjami27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Advanced Web Development

Uploaded by

deepakjami27
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Advanced Web Development

Task 1: Installa7on of XAMPP

Link: h(ps://www.apachefriends.org/

For Mac: h(ps://www.mamp.info/en/downloads/

1. Download and Install XAMPP


2. Run XAMPP Control Panel
3. Start APACHE and MySQL and below screen show come.

Video Tutorial: h(ps://www.youtube.com/watch?v=G2VEf-8nepc

Task 2: Execu7on of PHP file

1. Create a folder ‘CSDFPT’ in the htdocs folder ( C:/xampp/htdocs )


2. Create a file task2.php
3. Write the below code and save it.

<?php
echo "My first PHP script!";
?>
4. Open Browser and in URL type: h(p://localhost/CSDFPT/task2.php
5. Check if you are geeng output.
Task 3: Create a FORM with PHP
1. Create a file task3.php
2. Write the below code:

<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

3. Save it and open the URL : h(p://localhost/CSDFPT/task3.php


4. Below output shall be there.

Task 4: Create a database and a table

Task 5: Connect PHP to database

<?php
// Database credenfals
$servername = "localhost"; // usually 'localhost'
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

// Check connecfon
if ($conn->connect_error) {
die("Connecfon failed: " . $conn->connect_error);
}

// Data to be inserted
$name = "John Doe";
$email = "[email protected]";

// SQL query to insert data


$sql = "INSERT INTO your_table_name (name, email) VALUES ('$name', '$email')";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the connecfon


$conn->close();
?>

Explana7on:
• Database Connec7on:
o Replace localhost, your_username, your_password, and your_database with
your actual MySQL database details.
• Data to be Inserted:
o Replace your_table_name, name, and email with the actual table name and
column names in your database.
o You can also replace the $name and $email variables with the data you want
to insert.
• SQL Query:
o The SQL query is a simple INSERT INTO statement that inserts values into the
specified columns of your table.
• Error Handling:
o If the query is successful, it will output "New record created successfully". If
there is an error, it will output the error message.
• Closing Connec7on:
o Always close the connecfon aser execufng your queries to free up
resources.

This is a basic script; depending on your applicafon, you may want to use prepared
statements to prevent SQL injecfon.

Task 6: Connect FORM to PHP and then add value

PHP script that demonstrates how to connect a HTML form to a PHP script and then add
the submi(ed values to a MySQL database.

1. Create a HTML Form

First, create an HTML form (`form.html`) that allows users to input their data:

```html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, inifal-scale=1.0">
<ftle>Simple Form</ftle>
</head>
<body>
<form acfon="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

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

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


</form>
</body>
</html>
```

2. Create the PHP Script to Handle Form Submission

Next, create the PHP script (`submit.php`) to handle the form data and insert it into the
database:

```php
<?php
// Database credenfals
$servername = "localhost"; // usually 'localhost'
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

// Check connecfon
if ($conn->connect_error) {
die("Connecfon failed: " . $conn->connect_error);
}

// Check if form is submi(ed


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect form data
$name = $_POST['name'];
$email = $_POST['email'];

// SQL query to insert data


$sql = "INSERT INTO your_table_name (name, email) VALUES ('$name', '$email')";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

// Close the connecfon


$conn->close();
?>

```

Explana7on:

1. HTML Form (`form.html`):


- The form uses the `POST` method to submit data to `submit.php`.
- It has two input fields: one for the user's name and one for their email.

2. PHP Script (`submit.php`):


- Database Connecfon:
- Replace `localhost`, `your_username`, `your_password`, and `your_database` with
your actual MySQL database credenfals.
- Form Data Handling:
- The script checks if the form is submi(ed using `$_SERVER["REQUEST_METHOD"] ==
"POST"`.
- It retrieves the form data using `$_POST['name']` and `$_POST['email']`.
- SQL Query:
- The form data is inserted into the table using the `INSERT INTO` SQL query.
- Replace `your_table_name`, `name`, and `email` with your actual table and column
names.
- Error Handling:
- If the query is successful, a success message is shown; otherwise, an error message
is displayed.
- Closing Connecfon:
- The connecfon is closed aser the query execufon.

Security Note:
This basic example directly inserts user input into the database, which can lead to SQL
injecfon. For producfon use, you should use prepared statements with parameterized
queries to mifgate this risk:

```php

$stmt = $conn->prepare("INSERT INTO your_table_name (name, email) VALUES (?, ?)");


$stmt->bind_param("ss", $name, $email);
$stmt->execute();
```

Using prepared statements makes your code more secure by separafng SQL code from
data.

Task 7: Create a login page

Below is a basic implementafon of a login system using HTML, JavaScript, and PHP.

1. HTML for Login Page (`login.html`)

This is the front-end code for the login form:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, inifal-scale=1.0">
<ftle>Login Page</ftle>
</head>
<body>
<h2>Login</h2>
<form id="loginForm" acfon="login.php" method="post" onsubmit="return
validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>

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


</form>

<script>
funcfon validateForm() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;

if (username === "" || password === "") {


alert("Username and Password are required");
return false;
}
return true;
}
</script>
</body>
</html>
```

2. PHP Script for Processing Login (`login.php`)

This is the server-side script that processes the login form data:

```php
<?php
// Start the session
session_start();

// Database credenfals
$servername = "localhost"; // usually 'localhost'
$username = "your_db_username";
$password = "your_db_password";
$dbname = "your_database";

// Create connecfon
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connecfon
if ($conn->connect_error) {
die("Connecfon failed: " . $conn->connect_error);
}

// Check if form is submi(ed


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

// Prepare and bind


$stmt = $conn->prepare("SELECT id FROM users WHERE username = ? AND password
= ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_result();

// Check if user exists


if ($stmt->num_rows > 0) {
// Login successful
$_SESSION['username'] = $username;
echo "Login successful! Welcome, " . $username;
// Redirect to a protected page
// header("Locafon: protected_page.php");
} else {
// Login failed
echo "Invalid username or password";
}

$stmt->close();
}

// Close connecfon
$conn->close();
?>
```

3. Explana7on

HTML (`login.html`):
- Form:
- The form uses the `POST` method to submit data to `login.php`.
- There are two input fields for the username and password, both required.

- JavaScript Validafon:
- The `validateForm()` funcfon ensures that both fields are filled out before the form is
submi(ed. If either field is empty, an alert is shown, and the form submission is halted.

PHP (`login.php`):
- Session Handling:
- The script starts a session to manage user login state.

- Database Connecfon:
- Replace `your_db_username`, `your_db_password`, and `your_database` with your
actual MySQL database credenfals.

- Prepared Statement:
- The script uses a prepared statement to securely query the database, prevenfng SQL
injecfon.
- It checks if a user exists with the provided username and password.

- Login Success/Failure:
- If a user is found, a session variable is set, and a success message is displayed.
- If no matching user is found, an error message is displayed.

Security Considera7on:
- Password Hashing:
- This example directly compares plain-text passwords, which is not secure. In
producfon, always store hashed passwords using funcfons like `password_hash()` and
verify them using `password_verify()`.

Here’s how you can modify the script to use hashed passwords:

1. Register Users with Hashed Passwords:


- During user registrafon, hash the password before storing it in the database:
```php
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
```

2. Verify Hashed Passwords:


- When checking the login credenfals:
```php
$stmt = $conn->prepare("SELECT id, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($id, $hashed_password);
$stmt->fetch();

if (password_verify($password, $hashed_password)) {
$_SESSION['username'] = $username;
echo "Login successful! Welcome, " . $username;
} else {
echo "Invalid username or password";
}
```

4. Protec7ng Pages

To protect other pages (e.g., `protected_page.php`), add a session check at the top:

```php
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Locafon: login.html");
exit;
}
?>
```

This ensures that only logged-in users can access certain pages.

Task 8: Send Data in POST method, /// see above for same in Task 7

Task 9: Write a PHP script to display all data of the table/database

Here’s a PHP script that connects to a MySQL database and displays all the data from a
specific table in an HTML table format.

PHP Script to Display All Data from a Table (`display_data.php`)

```php
<?php
// Database credenfals
$servername = "localhost"; // usually 'localhost'
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

// Check connecfon
if ($conn->connect_error) {
die("Connecfon failed: " . $conn->connect_error);
}

// SQL query to select all data from a table


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

// Check if there are results


if ($result->num_rows > 0) {
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>"; // Modify column
headers as per your table structure

// Output data of each row


while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>"; // Replace 'id' with your actual column name
echo "<td>" . $row["name"] . "</td>"; // Replace 'name' with your actual column
name
echo "<td>" . $row["email"] . "</td>"; // Replace 'email' with your actual column
name
echo "</tr>";
}

echo "</table>";
} else {
echo "0 results";
}

// Close the connecfon


$conn->close();
?>
```

Explana7on:

1. Database Connecfon:
- Replace `localhost`, `your_username`, `your_password`, and `your_database` with
your actual MySQL database credenfals.

2. SQL Query:
- The script selects all rows from `your_table_name`. Replace this with the actual name
of the table you want to query.

3. Displaying Results:
- If there are rows in the table, the script outputs them in an HTML table format.
- Replace `id`, `name`, `email`, and the column headers with the actual column names
in your table.
- If there are no rows in the table, the script outputs "0 results".

4. Closing Connecfon:
- The database connecfon is closed aser the query execufon.

Example Use Case:


Assume you have a table named `users` with columns `id`, `name`, and `email`. The
script would display all records from the `users` table in a structured HTML table:

```php
$sql = "SELECT * FROM users"; // Query to select all data from 'users' table
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>"; // Column headers
```

Running the Script:


- Place this PHP file on your server (e.g., in your `htdocs` directory for XAMPP or `www`
directory for WAMP).
- Access it via your web browser (e.g., `h(p://localhost/display_data.php`).
- The script will output all records from the specified table in a neat, forma(ed HTML
table.

This basic script is useful for quickly displaying the contents of a database table in a web
interface.

Task 10: Write a PHP script to add data to database and display all data of database.

Here's a PHP script that allows you to add data to a database and then display all the
data from that database table immediately aser the addifon.

1. HTML Form to Add Data (`index.html`)

This is a simple HTML form to collect user input:

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, inifal-scale=1.0">
<ftle>Add Data</ftle>
</head>
<body>
<h2>Add Data to Database</h2>
<form acfon="add_and_display.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<input type="submit" value="Add Data">
</form>
</body>
</html>
```

2. PHP Script to Add Data and Display All Records (`add_and_display.php`)

This PHP script handles the form submission, adds the data to the database, and then
displays all records from the table:

```php
<?php
// Database credenfals
$servername = "localhost"; // usually 'localhost'
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

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

// Check connecfon
if ($conn->connect_error) {
die("Connecfon failed: " . $conn->connect_error);
}

// Check if form is submi(ed


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect form data
$name = $_POST['name'];
$email = $_POST['email'];

// SQL query to insert data


$sql = "INSERT INTO your_table_name (name, email) VALUES ('$name', '$email')";

// Execute the query


if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br><br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

// SQL query to select all data from the table


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

// Check if there are results


if ($result->num_rows > 0) {
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>"; // Modify column
headers as per your table structure

// Output data of each row


while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>"; // Replace 'id' with your actual column name
echo "<td>" . $row["name"] . "</td>"; // Replace 'name' with your actual column
name
echo "<td>" . $row["email"] . "</td>"; // Replace 'email' with your actual column
name
echo "</tr>";
}

echo "</table>";
} else {
echo "0 results";
}

// Close the connecfon


$conn->close();
?>
```

Explana7on:

1. HTML Form (`index.html`):


- The form collects a user's name and email and sends it via POST to
`add_and_display.php`.

2. PHP Script (`add_and_display.php`):


- Database Connecfon:
- Replace `localhost`, `your_username`, `your_password`, and `your_database` with
your actual MySQL database credenfals.

- Form Submission:
- The script checks if the form was submi(ed using `$_SERVER["REQUEST_METHOD"]
== "POST"`.
- The submi(ed data (`name` and `email`) is inserted into the specified table using an
`INSERT INTO` SQL query.

- Displaying All Records:


- Aser adding the new data, the script fetches all records from the table using a
`SELECT * FROM your_table_name` query.
- The records are then displayed in an HTML table format.

- Closing Connecfon:
- The database connecfon is closed aser all operafons.

Example Use Case:

Assume you have a table named `users` with columns `id`, `name`, and `email`. The
script would look like this:

- Inserfng Data:
```php
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
```

- Fetching and Displaying Data:


```php
$sql = "SELECT * FROM users";
```

Running the Script:

1. Place the Files on Your Server:


- Put `index.html` and `add_and_display.php` in your server's root directory (e.g.,
`htdocs` for XAMPP).

2. Access the Form:


- Open the form in your web browser by navigafng to `h(p://localhost/index.html`.

3. Submit Data:
- Enter the data and submit the form. The page will reload, adding the data to the
database and displaying all current records.

This setup allows users to add new entries to your database and view all exisfng entries
in real fme.

Extra:

1. Write a script to update the data.


2. Write a script to delete the data.

You might also like