diff --git a/index.php b/index.php index 95290b6ba0646090d4d4ac3146cccda66e8684b9..51c0daf002b4611ba56b0e4ac0b032b6824b2288 100644 --- a/index.php +++ b/index.php @@ -1,28 +1,38 @@ <?php -echo "Ruk buaruang 65160264"; - +// Database configuration $servername = "db"; -$username = "Lab2"; -$password = "Ruk241246<3"; -$dbname = "Lab2"; +$username = "Lab2"; +$password = "Ruk241246<3"; +$dbname = "Lab2"; -// Create connection -$conn = new mysqli($servername, $username, $password, $dbname); -// Check connection -if ($conn->connect_error) { - die("Connection failed: " . $conn->connect_error); -} +try { + // Create connection + $conn = new mysqli($servername, $username, $password, $dbname); + + // Check connection + if ($conn->connect_error) { + throw new Exception("Connection failed: " . $conn->connect_error); + } -$sql = "SELECT id, fname, lname FROM student"; -$result = $conn->query($sql); + // Query to fetch students + $sql = "SELECT id, fname, lname FROM student"; + $result = $conn->query($sql); -if ($result->num_rows > 0) { - // output data of each row - while($row = $result->fetch_assoc()) { - echo "id: " . $row["id"]. " - Name: " . $row["fname"]. " " . $row["lname"]. "<br>"; - } -} else { - echo "0 results"; + // Display results + if ($result->num_rows > 0) { + echo "<h2>Student List</h2>"; + echo "<ul>"; + while ($row = $result->fetch_assoc()) { + echo "<li><strong>ID:</strong> {$row['id']} - <strong>Name:</strong> {$row['fname']} {$row['lname']}</li>"; + } + echo "</ul>"; + } else { + echo "<p>No students found.</p>"; + } +} catch (Exception $e) { + echo "<p style='color:red;'>Error: " . $e->getMessage() . "</p>"; +} finally { + // Close connection + $conn->close(); } -$conn->close(); ?>