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

lab9

This document outlines Lab 9's objectives, which include creating a login page, displaying a form upon successful login, and implementing CRUD operations using PHP and MySQL. It details the process of connecting to a MySQL database using MySQLi, creating a database, and handling user data input and display. The document also provides code examples for login, user creation, data retrieval, and management functionalities.

Uploaded by

cameronrobin495
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)
5 views

lab9

This document outlines Lab 9's objectives, which include creating a login page, displaying a form upon successful login, and implementing CRUD operations using PHP and MySQL. It details the process of connecting to a MySQL database using MySQLi, creating a database, and handling user data input and display. The document also provides code examples for login, user creation, data retrieval, and management functionalities.

Uploaded by

cameronrobin495
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/ 13

LAB 9: DATABASE CONNECTIVITY USING PHP AND CRUD

OBJECTIVE
 To create a login page and perform login operation taking reference of
LAB 8.
 To display a form after successful login.
 To write a PHP script to create a database, create a table, input data in the
database and display the stored data.

THEORY
MySQL is a highly popular database management system that can power
projects of all sizes. Its ability to handle huge volumes of data without breaking
a sweat is one of its biggest selling points. Connect MySQL with PHP code, you
can make use of one of three methodologies.
There are three types of methods in PHP to connect MySQL database through
backend:
MySQL
MySQLi
PDO
MySQLi
MySQLi is an API used as a connector function to link the backend of the PHP
app to the MySQL database. It works just like the previous version, but it is
safer and faster, and provides a better set of functions and extensions.
Connect MySQL using Localhost Server
Create MySQL Database at the Localhost
 Create Database
 Create a Folder in htdocs
 Create Database Connection File In PHP
 Create new php file to check your database connection
 Run it

QUESTIONS
1. Create a login page and perform login operation using email and
password combination taking reference of Lab 8.
2. On Successful login a home page must be provided for the user which
should appear something like below:
3. The form that appears above should be filled by user and the data must be
inserted to database.
4. From the view Data Tab you must be able to view the created users in a
tabulated manner as below:

5. On Clicking the delete and update options, data must be deleted and
updated accordingly.
ANSWER:1
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<? php if (isset($error)) { echo "<p
style='color:red;'>$error</p>"; } ?>
<h2>Login Page</h2>
<form method="post">
<label>Email:</label>
<input type="email" name="email"
required><br>
<label>Password:</label>
<input type="password" name="password"
required><br>
<input type="submit" value="Login">
</form>
</body>
</html>

<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "WebTech";
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["email"];
$password = $_POST["password"];

$conn = new mysqli($host, $user, $pass, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn-
>connect_error);
}
$sql = "SELECT * FROM Student WHERE
email='$email' AND password='$password'";
$result = $conn->query($sql);
if ($result->num_rows == 1) {

$row = $result->fetch_assoc();
$_SESSION["user_id"] = $row["id"];
header("Location: createuser.php");
exit();
} else {
$error = "Invalid email or password";
}
$conn->close();
}
?>
OUTPUT
ANSWER:2

<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "WebTech";
session_start();
if (!isset($_SESSION["user_id"])) {
header("Location: login.php");
exit();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {

$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$gender = $_POST["gender"];
$education_level = implode(",",
$_POST["education_level"]);
$email = $_POST["email"];
$address = $_POST["address"];
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn-
>connect_error);
}
$sql = "INSERT INTO userdata (firstname,
lastname, gender, education_level, email, address)
VALUES ('$firstname', '$lastname', '$gender',
'$education_level', '$email', '$address')";
if ($conn->query($sql) === TRUE) {
$success = "User created successfully";
} else {
$error = "Error creating user: " . $conn-
>error;
}

$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<link rel="stylesheet" href="./styles.css"/>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div class="flex flex-row w-full">
<img src="./pngfind.com-placeholder-png-6104451.png"
width="150px"/>
<div class="bg-green-500 grow text-center">
<h1 class="text-2xl">Data Collection Center</h1>
<h2 class="text-xl">Babarmahal, Kathmandu</h2>
<p>You are logged in as user ID <?php echo
$_SESSION["user_id"]; ?></p>
</div>
</div>
<div>
<ul class="flex flex-row justify-center w-full
gap-4 bg-gray-500">
<li><a class="text-lg"
href="createuser.php">Home Page</a></li><p>|</p>
<li><a class="text-lg"
href="viewuser.php">View Data</a></li><p>|</p>
<li><a class="text-lg"
href="viewuser.php">Profile</a></li><p>|</p>
<li><a class="text-lg"
href="viewuser.php">Feedback</a></li><p>|</p>
<li><a class="text-lg"
href="logout.php">Logout</a></li><p>|</p>
</ul>
</div>
<div class="bg-sky-300 py-12 px-24">
<div class="bg-gray-400 px-24">
<?php if (isset($success)) { echo "<p
style='color:green;'>$success</p>"; } ?>
<?php if (isset($error)) { echo "<p
style='color:red;'>$error</p>"; } ?>
<h2 class="text-center text-xl">Create a new
user</h2>
<form method="post" 0" class="flex flex-col gap-
4">
<div>
<label>First name:</label>
<input type="text" name="firstname"
required><br>
</div>
<div>
<label>Last name:</label>
<input type="text" name="lastname"
required><br>
</div>
<div>
<label>Gender:</label>
<select name="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br>
</div>
<div class="flex flex-row w-full gap-4">
<label>Education level:</label><br>

<input type="checkbox"
name="education_level[]" value="SLC"> SLC<br>
<input type="checkbox"
name="education_level[]" value="+2"> +2<br>
<input type="checkbox"
name="education_level[]" value="Bachelors">
Bachelors<br>
<input type="checkbox"
name="education_level[]" value="Masters"> Masters<br>
<input type="checkbox"
name="education_level[]" value="PHD"> PHD<br>
</div>
<div>
<label>Email:</label>
<input type="email" name="email"
required><br>
</div>
<div>
<label>Address:</label>
<textarea name="address"
required></textarea><br>
</div>
<input type="submit" value="Create">
</form>
</div>
</div>
</body>
</html>
OUTPUT

ANSWER:3
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<link rel="stylesheet" href="./styles.css"/>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div class="flex flex-row w-full">
<img src="./pngfind.com-placeholder-png-6104451.png"
width="150px"/>
<div class="bg-green-500 grow text-center">
<h1 class="text-2xl">Data Collection Center</h1>
<h2 class="text-xl">Babarmahal, Kathmandu</h2>
<p>You are logged in as user ID <?php echo
$_SESSION["user_id"]; ?></p>
</div>
</div>
<div>
<ul class="flex flex-row justify-center w-full
gap-4 bg-gray-500">
<li><a class="text-lg"
href="createuser.php">Home Page</a></li><p>|</p>
<li><a class="text-lg"
href="viewuser.php">View Data</a></li><p>|</p>
<li><a class="text-lg"
href="viewuser.php">Profile</a></li><p>|</p>
<li><a class="text-lg"
href="viewuser.php">Feedback</a></li><p>|</p>
<li><a class="text-lg"
href="logout.php">Logout</a></li><p>|</p>
</ul>
</div>
<div class="bg-sky-300 py-12 px-24">
<div class="bg-gray-400 px-24">
<h2 class="text-center text-xl">Create a new
user</h2>
<?php if (isset($success)) { echo "<p
style='color:green;'>$success</p>"; } ?>
<?php if (isset($error)) { echo "<p
style='color:red;'>$error</p>"; } ?>
<form method="post" 0" class="flex flex-col gap-
4">
<div>
<label>First name:</label>
<input type="text" name="firstname"
required><br>
</div>
<div>
<label>Last name:</label>
<input type="text" name="lastname"
required><br>
</div>
<div>
<label>Gender:</label>
<select name="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br>
</div>
<div class="flex flex-row w-full gap-4">
<label>Education level:</label><br>

<input type="checkbox"
name="education_level[]" value="SLC"> SLC<br>
<input type="checkbox"
name="education_level[]" value="+2"> +2<br>
<input type="checkbox"
name="education_level[]" value="Bachelors">
Bachelors<br>
<input type="checkbox"
name="education_level[]" value="Masters"> Masters<br>
<input type="checkbox"
name="education_level[]" value="PHD"> PHD<br>
</div>
<div>
<label>Email:</label>
<input type="email" name="email"
required><br>
</div>
<div>
<label>Address:</label>
<textarea name="address"
required></textarea><br>
</div>
<input type="submit" value="Create">
</form>
</div>
</div>
</body>
</html>

<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbname = "WebTech";
session_start();
if (!isset($_SESSION["user_id"])) {
header("Location: login.php");
exit();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$gender = $_POST["gender"];
$education_level = implode(",",
$_POST["education_level"]);
$email = $_POST["email"];
$address = $_POST["address"];
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn-
>connect_error);
}
$sql = "INSERT INTO userdata (firstname,
lastname, gender, education_level, email, address)
VALUES ('$firstname', '$lastname', '$gender',
'$education_level', '$email', '$address')";
if ($conn->query($sql) === TRUE) {
$success = "User created successfully";
} else {
$error = "Error creating user: " . $conn-
>error;
}
$conn->close();
}
?>
OUTPUT

ANSWER:4 and 5
<?php
// Connect to the database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "WebTech";
$conn = mysqli_connect($servername, $username,
$password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " .
mysqli_connect_error());
}
// Insert data into the database
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$gender = $_POST['gender'];
$education_level = implode(",",
$_POST['education_level']);
$email = $_POST['email'];
$address = $_POST['address'];
$sql = "INSERT INTO userdata (firstname,
lastname, gender, education_level, email, address)
VALUES ('$firstname', '$lastname',
'$gender', '$education_level', '$email',
'$address')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" .
mysqli_error($conn);
}
}
// Delete data from the database
if (isset($_GET['delete'])) {
$id = $_GET['delete'];
$sql = "DELETE FROM userdata WHERE id=$id";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " .
mysqli_error($conn);
}
}
// Update data in the database
if ($_SERVER['REQUEST_METHOD'] == 'POST' &&
isset($_POST['update'])) {
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$gender = $_POST['gender'];
$education_level = implode(",",
$_POST['education_level']);
$email = $_POST['email'];
$address = $_POST['address'];
$sql = "UPDATE userdata SET
firstname='$firstname', lastname='$lastname',
gender='$gender', education_level='$education_level',
email='$email', address='$address' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " .
mysqli_error($conn);
}
}
// Retrieve data from the database
$sql = "SELECT * FROM userdata";
$result = mysqli_query($conn, $sql);
// Display the data in a table
echo "<table>";
echo "<tr><th>ID</th><th>First Name</th><th>Last
Name</th><th>Gender</th><th>Education
Level</th><th>Email</th><th>Address</th><th>Actions</
th></tr>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['education_level'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td><a href='update.php?id=" . $row['id'] .
"'>Edit</a></td>";
echo "<td><a href='viewuser.php?delete=" .
$row['id'] . "' onclick=\"return confirm('Are you
sure you want to delete this
record?')\">Delete</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
OUTPUT

CONCLUSION
In conclusion, in this lab we learned how to connect database to php. We alsp
learned how to update , delect and insert data into the database.

You might also like