All programs
Web Technology Lab · BCSL504 Web Tech (HTML · CSS · JS)

Problem Statement Program 8b

Develop a PHP program (with HTML/CSS) to sort the student records which are stored in the database using Selection Sort.

Web Tech (HTML · CSS · JS) Code 2 files

student_db.sql
CREATE DATABASE student_db;
USE student_db;

CREATE TABLE students (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  grade INT NOT NULL
);

INSERT INTO students (name, grade) VALUES
('Abhishek', 85),
('Basava', 92),
('Santosh', 78),
('Aaditya', 88),
('Dileep', 95);
student_recors.php
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Student Records Sorting</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      margin-top: 50px;
    }

    table {
      margin: 20px auto;
      border-collapse: collapse;
      width: 50%;
    }

    th,
    td {
      border: 1px solid #ccc;
      padding: 10px;
      text-align: center;
    }

    th {
      background-color: #f4f4f4;
    }
  </style>
</head>

<body>

<h1>Sorted Student Records</h1>

<?php

// Database connection
$conn = new mysqli('localhost', 'root', '', 'student_db');

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

// Fetch student records
$result = $conn->query("SELECT * FROM students");
$students = [];

while ($row = $result->fetch_assoc()) {
    $students[] = $row;
}

// Selection Sort Function
function selectionSort(&$arr) {
    $n = count($arr);

    for ($i = 0; $i < $n - 1; $i++) {
        $minIdx = $i;

        for ($j = $i + 1; $j < $n; $j++) {

            if ($arr[$j]['grade'] < $arr[$minIdx]['grade']) {
                $minIdx = $j;
            }

        }

        // Swap
        $temp = $arr[$minIdx];
        $arr[$minIdx] = $arr[$i];
        $arr[$i] = $temp;
    }
}

// Sort the records
selectionSort($students);

// Display sorted records
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Grade</th></tr>";

foreach ($students as $student) {
    echo "<tr>";
    echo "<td>{$student['id']}</td>";
    echo "<td>{$student['name']}</td>";
    echo "<td>{$student['grade']}</td>";
    echo "</tr>";
}

echo "</table>";

$conn->close();

?>

</body>
</html>

Output 1 screenshot

Download the clean, watermark-free output image — ₹1.00
Protected content · © VTU Developer · Unauthorised distribution is prohibited