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

Sss External

The documents demonstrate form validation and database insertion using JavaScript, PHP and MySQL. Client-side validation is performed using regular expressions to validate form fields. On submission, the form data is inserted into a database table using a prepared statement. AJAX techniques are used to retrieve and display dynamic data from server.

Uploaded by

divyakesari2003
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)
44 views

Sss External

The documents demonstrate form validation and database insertion using JavaScript, PHP and MySQL. Client-side validation is performed using regular expressions to validate form fields. On submission, the form data is inserted into a database table using a prepared statement. AJAX techniques are used to retrieve and display dynamic data from server.

Uploaded by

divyakesari2003
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
You are on page 1/ 24

SET-1:

1A)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation and Database Insertion</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>Form Validation and Database Insertion</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
method="post" id="myForm">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<span id="usernameError" class="error"></span><br>

<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<span id="passwordError" class="error"></span><br>

<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<span id="emailError" class="error"></span><br>

<label for="phone">Phone Number:</label><br>


<input type="tel" id="phone" name="phone"><br>
<span id="phoneError" class="error"></span><br>

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


</form>

<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
let isValid = true;
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
const email = document.getElementById('email').value.trim();
const phone = document.getElementById('phone').value.trim();

const usernameError = document.getElementById('usernameError');


const passwordError = document.getElementById('passwordError');
const emailError = document.getElementById('emailError');
const phoneError = document.getElementById('phoneError');
usernameError.textContent = '';
passwordError.textContent = '';
emailError.textContent = '';
phoneError.textContent = '';

const usernameRegex = /^[a-zA-Z0-9_-]{3,16}$/;


if (!usernameRegex.test(username)) {
usernameError.textContent = 'Username must be 3-16 characters
long and can only contain letters, numbers, underscores, and hyphens';
isValid = false;
}

const passwordRegex =
/^(?=.\d)(?=.[a-z])(?=.[A-Z])(?=.[a-zA-Z]).{8,}$/;
if (!passwordRegex.test(password)) {
passwordError.textContent = 'Password must be at least 8
characters long and contain at least one uppercase letter, one
lowercase letter, and one number';
isValid = false;
}

const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;


if (!emailRegex.test(email)) {
emailError.textContent = 'Invalid email format';
isValid = false;
}

const phoneRegex = /^\d{10}$/;


if (!phoneRegex.test(phone)) {
phoneError.textContent = 'Phone number must be 10 digits';
isValid = false;
}

if (!isValid) {
event.preventDefault();
}
});
</script>
1B)
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Check if form is submitted


if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Form data
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$phone = $_POST['phone'];

// SQL to insert data into Person table


$sql = "INSERT INTO Person (username, password, email, phone) VALUES
('$username', '$password', '$email', '$phone')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

$conn->close();
?>

</body>
</html>
SET-2:
2A)
<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.responseText;
}
xhttp.open("GET", "file.txt ");
xhttp.send();
}
</script>

</body>
</html>

File.txt:
Some matter should be in file

2B)
<!DOCTYPE html>
<title>XML Data Display</title>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
</head>
<body>

<div id="container">
<h1>XML Data Display</h1>
<button type="button" onclick="fun()">Load Data</button>
<table id="tab"></table>
</div>
<script>
function fun() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ab.xml");
xhttp.onload = function() {
var xt = this.responseXML;
var table = "<tr><th>Name</th><th>Age</th></tr>";
var cds = xt.getElementsByTagName("cd");
for (var i = 0; i < cds.length; i++) {
var name = cds[i].getElementsByTagName("name")[0].textContent;
var age = cds[i].getElementsByTagName("age")[0].textContent;
table += "<tr><td>" + name + "</td><td>" + age + "</td></tr>";
}
document.getElementById("tab").innerHTML = table;
};
xhttp.send();
}
</script>

</body>
</html>

XML File:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<name>Artist 1</name>
<age>30</age>
</cd>
<cd>
<name>Artist 2</name>
<age>25</age>
</cd>
<!-- Add more <cd> entries as needed -->
</catalog>
SET-3:
3A)
XML File:
<IDOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Database Demo</title>
</head>
<body>
<h1>AJAX Database Demo</h1>
<input type="text" id="searchinput" placeholder="Type here..." oninput="sendData()">
<div id="searchResults"></div>
<script>
function sendData() {
var input Text document.getElementById("searchinput").value;
var url =“search.php?query”+ inputText;
var xhttp new XMLHttpRequest():
xhttp.onreadystatechange function() {
if (this.readyState 4 && this.status == 200) {
document.getElementById('search Results").innerHTML this.responseText:
}
xhttp.open("GET", url, true);
xhttp.send():
}
</script>
</body>
</html>

Gethint.php:
$names = ["Anna", "Brittany", "Cinderella", "Diana", "Eva", "Fiona", "Gunda", "Hege",
"Inga", "Johanna","Kitty", "Linda", "Nina", "Ophelia", "Petunia", "Amanda", "Raquel",
"Cindy", "Doris", "Eve","Evita", "Sunniva", "Tove", "Unni", "Violet", "Liza", "Elizabeth",
"Ellen", "Wenche", "Vicky"];
$q = strtolower($_REQUEST["query"] );
$hint = "";
if (!empty($q)) {
foreach ($names as $name) {
if (stristr($name, $q)) {
if ($hint !== "") {
$hint .= ", ";
}
$hint .= $name;
}
}
}
echo $hint ?: "no suggestion";
3B)
XML File:
<IDOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Database Demo</title>
</head>
<body>
<h1>AJAX Database Demo</h1>
<input type="text" id="searchinput" placeholder="Type here..." oninput="sendData()">
<div id="searchResults"></div>
<script>
function sendData() {
var input Text document.getElementById("searchinput").value;
var url =“search.php?query”+ inputText;
var xhttp new XMLHttpRequest():
xhttp.onreadystatechange function() {
if (this.readyState 4 && this.status == 200) {
document.getElementById('search Results").innerHTML this.responseText:
}
xhttp.open("GET", url, true);
xhttp.send():
}
</script>
</body>
</html>

PHP
With database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
$query = $_REQUEST['query'];
$sql = "SELECT * FROM your_table WHERE column_name LIKE '%$query%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>" . $row['column_name'] . "</p>"; // Display search results
}
} else {
echo "<p>No results found</p>";}

$conn->close();
?>
SET-4:

4A)
<html>
<body>
<form action="welcome_get.php" method="GET">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

Welcome_get.php

<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>

4B)
<!DOCTYPE html>
<html>
<head>
<title>Employee Form</title>
</head>
<body>
<form action="insert_employee.php" method="post">
<label>Name: </label>
<input type="text" name="name" required><br>
<label>Age: </label>
<input type="number" name="age" required><br>
<label>Designation: </label>
<input type="text" name="designation" required><br>
<label>Email: </label>
<input type="email" name="email" required><br>
<label>Phone Number: </label>
<input type="tel" name="phone" required><br>
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
Insert_employee.php

<?php
$conn = mysqli_connect("localhost", "root", "", "employee");

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

if (isset($_POST['submit'])) {
$name = $_POST['name'] ?? '';
$age = $_POST['age'] ?? '';
$designation = $_POST['designation'] ?? '';
$email = $_POST['email'] ?? '';
$phone = $_POST['phone'] ?? '';

if (!empty($name) && !empty($age) && !empty($designation) && !empty($email) &&


!empty($phone)) {
$stmt = $conn->prepare("INSERT INTO employee (name, age, designation, email,
phone) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sisss", $name, $age, $designation, $email, $phone);

if ($stmt->execute()) {
echo "Employee added successfully!";
} else {
echo "Error: " . $stmt->error;
}

$stmt->close();
} else {
echo "Please fill in all fields.";
}
}

mysqli_close($conn);
?>
SET-5

5A)

creating a cookie :

<?php
setcookie("username", "JohnDoe", time() + 3600, "/");
?>

Retrieving a cookie:

<?php
if (isset($_COOKIE['username'])) {
$username = $_COOKIE['username'];
echo "Welcome back, $username!";
// Further operations using $username
} else {
echo "Cookie 'username' not found or has expired.";
// Perform alternative actions or set the cookie if not present
}
?>

Updating a cookie :

<?php
if (isset($_COOKIE['username'])) {
// Proceed with updating
setcookie("username", "NewValue", time() + 3600, "/");
}
?>

Deleting a cookie :

<?php
if (isset($_COOKIE['username'])) {
// Proceed with deleting
setcookie("username", "", time() - 3600, "/");
}
?>

5B)

Creating a session :

<?php
session_start();
$_SESSION["username"] = "JohnDoe";
?>
Retrieving a session Variable :

<?php
session_start();
if (isset($_SESSION["username"])) {
$username = $_SESSION["username"];
echo "Welcome back, $username!";
// Further operations using $username
} else {
echo "Session variable 'username' not found or session not started.";
// Perform alternative actions or start the session if not started
}
?>
Updating a Session Variable :

<?php
session_start();
if (isset($_SESSION["username"])) {
// Proceed with updating
$_SESSION["username"] = "NewValue";
}
?>

Deleting a Session Variable :

<?php
session_start();
if (isset($_SESSION["username"])) {
// Proceed with deleting
unset($_SESSION["username"]);
}
?>
SET-6:

6A)
<html>
<body>
<form action="welcome_post.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Welcome_POST.php

<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>

6B)

Upload.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h2>Upload File</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" &&
isset($_FILES["fileToUpload"])) {
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

// Check if file already exists


if (file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

// Allow certain file formats


$allowedTypes = array("txt", "pdf", "jpg", "png", "gif");
if (!in_array($fileType, $allowedTypes)) {
echo "Sorry, only TXT, PDF, JPG, PNG, GIF files are allowed.";
$uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error


if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
// Upload the file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file ". htmlspecialchars(basename($_FILES["fileToUpload"]["name"])).
" has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
</body>
</html>

File Download.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Download</title>
</head>
<body>
<h2>Download File</h2>
<ul>
<?php
$targetDir = "uploads/";
$files = scandir($targetDir);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
echo "<li><a href='downloads.php?file=$file'>$file</a></li>";
}
}
?>
</ul>

<?php
if (isset($_GET['file'])) {
$file = $_GET['file'];
$filePath = $targetDir . $file;

if (file_exists($filePath)) {
// Set headers to force download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));

// Read the file


readfile($filePath);
exit;
} else {
echo "File not found.";
}
}
?>
</body>
</html>
SET-7:

7A)
CREATE TABLE Names (
FirstName VARCHAR(50),
LastName VARCHAR(50)
);

<!DOCTYPE html>
<html>
<head>
<title>Add Name</title>
</head>
<body>
<h2>Add Name</h2>
<form method="post" action="insert_data.php">
<label for="firstName">First Name:</label><br>
<input type="text" id="firstName" name="firstName"><br>
<label for="lastName">Last Name:</label><br>
<input type="text" id="lastName" name="lastName"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

insert_data.php
<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];

// Connect to the database


$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

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


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

// Insert data into the database


$sql = "INSERT INTO Names (FirstName, LastName) VALUES ('$firstName',
'$lastName')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
}
?>

display_names.php
<!DOCTYPE html>
<html>
<head>
<title>Names</title>
</head>
<body>
<h2>Names</h2>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<?php
// Connect to the database
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

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


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

// Retrieve data from the database


$sql = "SELECT FirstName, LastName FROM Names";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["FirstName"]. "</td><td>" . $row["LastName"].
"</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</table>
</body>
</html>
7B)

<!DOCTYPE html>
<html>
<head>
<title>AJAX Demo</title>
<script>
function fetchData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhttp.open("GET", "fetch_data.php", true);
xhttp.send();}
</script>
</head>
<body>
<h2>Fetch Data from Database</h2>
<button onclick="fetchData()">Fetch Data</button>
<div id="data"></div>
</body>
</html>

<?php
// Connect to the database
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

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


if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve data from the database
$sql = "SELECT FirstName, LastName FROM Names";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "First Name: " . $row["FirstName"]. " - Last Name: " . $row["LastName"]. "<br>";
}} else {
echo "0 results";}
$conn->close();
?>
SET-8:
8A)
Index.html)
<!DOCTYPE html>
<html>
<body>
<h2>Enter Student Details</h2>
<form action="insert.php" method="post">
ID: <input type="text" name="id"><br>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
<input type="submit">
</form>
</body>
</html>

Insert.php)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "students";

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

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];

$sql = "INSERT INTO class1 (id, firstname, lastname)


VALUES ('$id', '$firstname', '$lastname')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
8B)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "students";
$conn = new mysqli($servername, $username, $password, $dbname);

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

$sql = "SELECT id, firstname, lastname FROM class1";


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

if ($result->num_rows > 0) {
echo "<table border='1'>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>";

while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["id"] . "</td>
<td>" . $row["firstname"] . "</td>
<td>" . $row["lastname"] . "</td>
</tr>";
}

// Close the table


echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
SET-9:

9A)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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


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

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

9B)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>
SET-10:
Create-student.php:
<!DOCTYPE html>
<html>
<title>Student Database</title>
<body>
<h2>Student Form</h2>
<form action="" method="POST">
<fieldset>
<legend>Student information:</legend>
Name:<br>
<input type="text" name="name" > <br>
Age:<br>
<input type="text" name="age"> <br>
Email:<br>
<input type="email" name="email"><br>
<br><br>
<input type="submit" name="submit" value="submit">
</fieldset>
</form>
</body>
</html>

<?php
include "dbconfig.php";
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$sql = "INSERT INTO `students`(`name`, `age`, `email`) VALUES
('$name','$age','$email')";
if ($name && $age && $email) {
$result = $conn->query($sql);
if ($result == TRUE) {
echo "New record created successfully.";
header('Location: view-student.php');
}else{
echo "Error:". $sql . "<br>". $conn->error;
}
}
else{
echo "please enter all details";
}
$conn->close();
}
?>

Dbconfig.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>

Update-student.php
<?php
include "dbconfig.php";
if (isset($_POST['update'])) {
$stu_id = $_POST['stu_id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$sql = "UPDATE `students` SET `name`='$name',`age`='$age',`email`='$email' WHERE
`id`='$stu_id'";
$result = $conn->query($sql);
if ($result == TRUE) {
echo "Record updated successfully.";
header('Location: view-student.php');
}else{
echo "Error:" . $sql . "<br>" . $conn->error;
}

if (isset($_GET['id'])) {
$stu_id = $_GET['id'];
$sql = "SELECT * FROM students WHERE id='$stu_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$name = $row['name'];
$age = $row['age'];
$email = $row['email'];
}
?>

<h2>Student details Update Form</h2>


<form action="" method="post">
<fieldset>
<legend>Personal information:</legend>
Name:<br>
<input type="text" name="name" value="<?php echo $name; ?>">
<input type="hidden" name="stu_id" value="<?php echo $id; ?>">
<br>
Age:<br>
<input type="text" name="age" value="<?php echo $age; ?>">
<br>
Email:<br>
<input type="email" name="email" value="<?php echo $email; ?>">
<br><br>
<input type="submit" value="Update" name="update">
</fieldset>
</form>
</body>
</html>

<?php
} else{
header('Location: view-student.php');
}
}

?>

View-student.php
<?php
include "dbconfig.php";
?>

<!DOCTYPE html>
<html>
<head>
<title>Student Database</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
</head>
<body>

<div class="container">
<h2>Student Details</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Action</th>

</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['age']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><a class="btn btn-info" href="update-student.php?id=<?php echo $row['id'];
?>">Edit</a>
&nbsp;
<a class="btn btn-danger" href="delete-student.php?id=<?php echo $row['id'];
?>">Delete</a>
</td>
</tr>
<?php }
}
?>
</tbody>
</table>
</div>
</body>
</html>

Delete-student.php
<?php
include "dbconfig.php";
if (isset($_GET['id'])) {
$stu_id = $_GET['id'];
$sql = "DELETE FROM students WHERE id ='$stu_id'";
$result = $conn->query($sql);
if ($result == TRUE) {
echo "Record deleted successfully.";
header('Location: view-student.php');
}else{
echo "Error:" . $sql . "<br>" . $conn->error;
}
}
?>

You might also like