Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Lab # 06: Interfacing PHP with MySQL

Spring 2024
Database Management System
Submitted by: Sibgha Noor
Registration No. 21PWCSE1975
Section: C

“On my honor, as student of University of Engineering and Technology, I have


neither given nor received unauthorized assistance on this academic work.”

Student Signature: ________________

Submitted to:
Mam Summayea Salahudin
DATED: 17/ May/ 2024

Department of Computer Systems Engineering


University of Engineering and Technology, Peshawar
Lab # 06: Interfacing PHP with MySQL

OBJECTIVES OF THE LAB


------------------------------------------------------------------------------------------------------------
This lab aims at the understanding of:

• Type of MySQL Drivers in PHP


• PHP-MySQL Interfaces
----------------------------------------------------------------------------------------------------

---------------------------Task 6.1---------------------------
Complete Example 3 by providing a suitable query, its result, and then freeing result variable.
Code:
<?php
//step 1. Database Connection + Database Selection
//server name, user, user's password, and database
//must be provided.
$servername = "localhost";
$username = "root";
$password = "";

$database = "sibgha";

// Create Connection
$conn = new mysqli($servername, $username, $password, $database);

//step 2. Check Connection


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

?>

<!DOCTYPE html>
<head>
<title>PHP MySqli (Object-Oriented) Basics</title>
</head>
<body>

<?php
$sql = "SELECT * FROM department";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Name = ".$row["name"]. "<br/>"; // Corrected placement of <br/>
}
} else {
echo "0 results";
}

?>
</body>
</html>

<?php
//step 6. Close Database Connection
$conn->close();
?>

Output:

---------------------------Task 6.2---------------------------
Write PHP-MYSQLI Object-Oriented interface script that connects with one of the tables of your
DBMS Lab Project (For instance, user table or accounts table or any of your choice). Perform
the following:

a. Apply the insert command on the table. Take the data from user via HTML Form
constructs.
b. Apply the update command on the table. Take the data from user via HTML Form
constructs.
c. Apply the delete query on the table. Take the data from user via HTML Form constructs.
d. Apply the select query on the same table to retrieve data. Show the data in HTML Form
Constructs.
Code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lab6t2";

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

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

if(isset($_POST['submit'])) {
$depname = $_POST['depname'];
$sql = "INSERT INTO department (depname) VALUES ('$depname')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

if(isset($_POST['update'])) {
$depID = $_POST['depID'];
$depname = $_POST['depname'];
$sql = "UPDATE department SET depname='$depname' WHERE depID='$depID'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}

if(isset($_POST['delete'])) {
$depID = $_POST['depID'];
$sql = "DELETE FROM department WHERE depID='$depID'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}

$sql = "SELECT * FROM department";


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

<!DOCTYPE html>
<html>
<head>
<title>Department Management</title>
</head>
<body>
<h1>Department Management</h1>
<h2>Add Department</h2>
<form method="post" action="">
<label for="depname">Department Name:</label>
<input type="text" id="depname" name="depname">
<input type="submit" name="submit" value="Add Department">
</form>

<h2>Update Department</h2>
<form method="post" action="">
<label for="depID">Department ID:</label>
<input type="text" id="depID" name="depID">
<label for="depname">Department Name:</label>
<input type="text" id="depname" name="depname">
<input type="submit" name="update" value="Update Department">
</form>

<h2>Delete Department</h2>
<form method="post" action="">
<label for="depID">Department ID:</label>
<input type="text" id="depID" name="depID">
<input type="submit" name="delete" value="Delete Department">
</form>

<h2>Departments</h2>
<?php
if ($result->num_rows > 0) {

echo "<table border='1'>";


echo "<tr><th>Department ID</th><th>Department Name</th></tr>";
while($row = $result->fetch_assoc()) {
echo
"<tr><td>".$row["depID"]."</td><td>".$row["depname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</body>
</html>

<?php
// Close Connection
$conn->close();
?>

Output:

---------------------------Task 6.3---------------------------
Perform Task 6.2 using PHP-PDO (PHP Data Objects) interface.

Code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lab6t2"; // Change this to the name of your newly created database

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully<br><br>";

// Insert Operation
if(isset($_POST['submit'])) {
$depname = $_POST['depname'];
$sql = "INSERT INTO department (depname) VALUES (:depname)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':depname', $depname);
if ($stmt->execute()) {
echo "New record created successfully<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

// Update Operation
if(isset($_POST['update'])) {
$depID = $_POST['depID'];
$depname = $_POST['depname'];
$sql = "UPDATE department SET depname=:depname WHERE depID=:depID";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':depID', $depID);
$stmt->bindParam(':depname', $depname);
if ($stmt->execute()) {
echo "Record updated successfully<br>";
} else {
echo "Error updating record: " . $conn->error;
}
}

// Delete Operation
if(isset($_POST['delete'])) {
$depID = $_POST['depID'];
$sql = "DELETE FROM department WHERE depID=:depID";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':depID', $depID);
if ($stmt->execute()) {
echo "Record deleted successfully<br>";
} else {
echo "Error deleting record: " . $conn->error;
}
}

// Select Operation
$sql = "SELECT * FROM department";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}

?>

<!DOCTYPE html>
<html>
<head>
<title>Department Management (PHP PDO)</title>
</head>
<body>
<h1>Department Management (PHP PDO)</h1>
<h2>Add Department</h2>
<form method="post" action="">
<label for="depname">Department Name:</label>
<input type="text" id="depname" name="depname">
<input type="submit" name="submit" value="Add Department">
</form>

<h2>Update Department</h2>
<form method="post" action="">
<label for="depID">Department ID:</label>
<input type="text" id="depID" name="depID">
<label for="depname">Department Name:</label>
<input type="text" id="depname" name="depname">
<input type="submit" name="update" value="Update Department">
</form>
<h2>Delete Department</h2>
<form method="post" action="">
<label for="depID">Department ID:</label>
<input type="text" id="depID" name="depID">
<input type="submit" name="delete" value="Delete Department">
</form>

<h2>Departments</h2>
<?php
if ($result) {
echo "<table border='1'>";
echo "<tr><th>Department ID</th><th>Department Name</th></tr>";
foreach ($result as $row) {
echo
"<tr><td>".$row["depID"]."</td><td>".$row["depname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</body>
</html>

<?php
$conn = null; // Close Connection
?>

Output:
---------------------------Task 6.4---------------------------
Perform Task 6.2 using LARAVEL.

Code:
Routes.php:

Index.blade:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Management</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Departments</h1>

@if($departments->isEmpty())
<p>No departments found.</p>
@else
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach($departments as $department)
<tr>
<td>{{ $department->id }}</td>
<td>{{ $department->name }}</td>
<td>
<a href="{{ route('departments.show',
$department->id) }}" class="btn btn-primary">View</a>
<a href="{{ route('departments.edit',
$department->id) }}" class="btn btn-warning">Edit</a>
<form action="{{ route('departments.destroy',
$department->id) }}" method="POST" style="display: inline;">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger"
onclick="return confirm('Are you sure you want to delete this
department?')">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
@endif

<a href="{{ route('departments.create') }}" class="btn btn-success">Add


Department</a>
</div>

<script src="{{ asset('js/app.js') }}"></script>


</body>
</html>

Create.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Department</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Create Department</h1>
<form action="{{ route('departments.store') }}" method="POST">
@csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name"
required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>

<script src="{{ asset('js/app.js') }}"></script>


</body>
</html>

Edit.blade.php: <!DOCTYPE html>


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Department</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Edit Department</h1>

<form action="{{ route('departments.update', $department->id) }}"


method="POST">
@csrf
@method('PUT')
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name"
value="{{ $department->name }}" required>
</div>
<button type="submit" class="btn btn-primary">Update</button>
</form>
</div>

<script src="{{ asset('js/app.js') }}"></script>


</body>
</html>
Show.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Details</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Department Details</h1>
<p>ID: {{ $department->id }}</p>
<p>Name: {{ $department->name }}</p>
</div>

<script src="{{ asset('js/app.js') }}"></script>


</body>
</html>

Delete.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete Department</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Delete Department</h1>

<p>Are you sure you want to delete this department?</p>

<form action="{{ route('departments.destroy', $department->id) }}"


method="POST">
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Output:

You might also like