Advanced Web Development
Advanced Web Development
Link: h(ps://www.apachefriends.org/
<?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>
<?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>
<?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]";
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.
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.
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>
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);
}
```
Explana7on:
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
Using prepared statements makes your code more secure by separafng SQL code from
data.
Below is a basic implementafon of a login system using HTML, JavaScript, and PHP.
```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>
<script>
funcfon validateForm() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
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);
}
$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:
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
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
<?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);
}
echo "</table>";
} else {
echo "0 results";
}
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.
```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
```
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.
```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>
```
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);
}
echo "</table>";
} else {
echo "0 results";
}
Explana7on:
- 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.
- Closing Connecfon:
- The database connecfon is closed aser all operafons.
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')";
```
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: